// Following script must be attached on an empty gameObject in your scene
public class KeyRing : MonoBehaviour
{
private int gatheredKeys = 0;
public void AddKey()
{
++gatheredKeys;
if( gatheredKeys == 3 )
{
Debug.Log("Open door");
}
}
}
// Following script on your keys
public class Key : MonoBehaviour
{
// Drag & drop the gameObject holding the `KeyRing` script in the inspector
// for each of your keys
public KeyRing KeyRing;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Player")
{
KeyRing.AddKey();
print ("Key Picked Up");
Destroy(gameObject);
}
}
}
I’m not sure exactly what you want to do, but if I assume you want to pick up 3 keys and then perform an action then you can’t have a local variable “x” on the key to track that. Since you destroy the key, every key will have a value of 0 at start, 1 on collision and then get destroyed.
What you could do instead is keep track on the player… other.Getcomponent<>().x += 1;
Or you could track the collision from the player:
TriggerEnter, if tag==key, x+=1, Destroy other.gameObject