Question by 
               iSizz · Jul 11, 2019 at 02:17 PM · 
                c#scripting problemintif  
              
 
              How to combine up to 3 and perform an action
Hi, I need help, i hope you can understand by script what i want :D, but its not working, please help :(
{ int x = 0; public GameObject key1, key2, key3;
 void OnTriggerEnter2D (Collider2D other) 
 {
     if (other.gameObject.tag == "Player")
     {
         x = x + 1;
         // print ("Key Picked Up");
         print(x);
         Destroy(gameObject);
     }
 }
 void Update()
 {
     if(x == 3)
     {
         print ("Door opens..");
     }
 }
 
               }
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by Hellium · Jul 11, 2019 at 11:52 AM
 // 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);
          }
      }
 }
 
              Answer by BradyIrv · Jul 11, 2019 at 02:20 PM
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
Your answer