How to identify the different prefab items in Unity3D?

282 Views Asked by At

I have defined a prefab with name is "Item" and contain in Resources Then, I load that prefab in GUI (Unity3D)

  Object prefab_item = Resources.Load("Item");
  GameObject g = Instantiate(prefab_item) as GameObject;
  g.transform.parent = this.transform; 
  g.transform.position = pos;
  Sprite sprite = Resources.Load("Images/item_" + item, typeof(Sprite)) as Sprite;
  g.GetComponent<SpriteRenderer>().sprite = sprite;

I want to load a list of different items by "Item" prefab, How to identify the different items when pressing them?

Thanks all!

2

There are 2 best solutions below

2
On BEST ANSWER

You can give each game object you created a name:

int i=1;
g.name = string.Format("item {0}", i);

Then you can identify it using:

var object = GameObject.Find("item 1");

In case you want to handle it when it is pressed, you can:

  1. add a collider component to the game object;
  2. add OnMouseDown() function in that MonoBehaviour script
  3. attach the MonoBehaviour script to the game object programatically:

    g.AddComponent("YourOnMouseDownScript");

3
On

Instead of:

Debug.Log ("item name: " + gameObject.name);

You can write this:

Debug.Log ("item name: " + gameObject.name, gameObject);

Then the message will be clickable in the log window. The object will be selected when you click the log message.