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

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

  private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Item")
        {
            // Check which item was collided with and trigger a different response
            if (collision.gameObject == neededItems[0])
            {
                Debug.Log("Got Party Supplys");
            }
            else if (collision.gameObject == neededItems[1])
            {
                Debug.Log("Got Pizza");
            }
            else if (collision.gameObject == neededItems[2])
            {
                Debug.Log("Got Cake");
            }
            else if (collision.gameObject == neededItems[3])
            {
                Debug.Log("Got Games");
            }

        }
    }

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?


Yes neededItems are public GameObject[] neededItems = new GameObject[4];, The array is using prefabs but the player is colliding with Instantiations of them, is that the problem?

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.

1 Like


Great thanks for your help!