Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Need to reference items based on if they are in an array?

Discussion in 'Scripting' started by kjp6269, Sep 9, 2023.

  1. kjp6269

    kjp6269

    Joined:
    Feb 18, 2023
    Posts:
    3
    Can anyone tell me why this wont work ingame? I get no errors in the script but im not sure where i went wrong, i have an array with 4 items that im trying to do specific things depending on what the player runs into


    Code (CSharp):
    1.   private void OnCollisionEnter2D(Collision2D collision)
    2.     {
    3.         if (collision.gameObject.tag == "Item")
    4.         {
    5.             // Check which item was collided with and trigger a different response
    6.             if (collision.gameObject == neededItems[0])
    7.             {
    8.                 Debug.Log("Got Party Supplys");
    9.             }
    10.             else if (collision.gameObject == neededItems[1])
    11.             {
    12.                 Debug.Log("Got Pizza");
    13.             }
    14.             else if (collision.gameObject == neededItems[2])
    15.             {
    16.                 Debug.Log("Got Cake");
    17.             }
    18.             else if (collision.gameObject == neededItems[3])
    19.             {
    20.                 Debug.Log("Got Games");
    21.             }
    22.  
    23.         }
    24.     }
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,978
    Is the type of neededItems
    GameObject[]
    or some other type? Did you fill the array in with in-scene references to the needed items, or are they references to prefab assets?
     
  3. kjp6269

    kjp6269

    Joined:
    Feb 18, 2023
    Posts:
    3
    Yes neededItems are
    Code (CSharp):
    1. public GameObject[] neededItems = new GameObject[4];
    , The array is using prefabs but the player is colliding with Instantiations of them, is that the problem?
     
  4. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,978
    Yes. When you instantiate from an original, it's a whole new object. This is true for dragging Prefab Assets into the Scene, Duplicating objects in the Scene, or for using the Instantiate() API. Reference equality checks will then return false, as they're not referring to the same object.

    When you instantiate things you need to find again, you should keep the new references.
     
    DragonCoder likes this.
  5. kjp6269

    kjp6269

    Joined:
    Feb 18, 2023
    Posts:
    3
    Great thanks for your help!