0

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 Answers2

0

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");

David
  • 15,894
  • 22
  • 55
  • 66
0

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.

piojo
  • 6,351
  • 1
  • 26
  • 36
  • It only show log the first item 1, not show items 2, 3, ...9. Although, i press to item 2, 3, ...9 May be, because i define a prefab, and then i load this prefab? – Nguyễn Hải Long Dec 19 '14 at 09:55
  • Yeah, then you should think how are these items being created? If your prefab is item 1 and you instantiate it several times, you will have lots of clones of "item 1", not any "item 2". If you manually rename the objects, then they can be "item 2", "item 3"... – piojo Dec 20 '14 at 18:52
  • Thank you David and piojo! I have completed :) – Nguyễn Hải Long Dec 22 '14 at 04:47