Search code examples
unity-game-enginengui

How to identify the different prefab items in Unity3D?


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!


Solution

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