Duplicated Reycast hit script problem

Hello I make an escape room game and there are “keys” that you must to take to the right place. You can pick up the keys if you click on it and place when you click to the right place. with one key and one keyhole it works, but when I duplicate the Game Objects and I click on one of the keys you got every single key and if you click on the keyhole every “door open”.

Here are the scripts:
Key script:
public class key : MonoBehaviour
{

    Keyhole hole;
    public GameObject keyhole;
    public GameObject destroy;


    private void Start()
    {
        hole = keyhole.GetComponent<Keyhole>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit))
            {
                BoxCollider bc = hit.collider as BoxCollider;
                if(bc!= null)
                {
                    hole.gotKey = true;
                    Destroy(this.gameObject);
                    Debug.Log("keyok");
                    
                    
                }
            }
        }
    }

    
}

Keyhole script:

public class Keyhole : MonoBehaviour
{
    
    public bool gotKey;

    private void Start()
    {
        
    }

    void Update()
    {
        
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                MeshCollider me = hit.collider as MeshCollider;
                if (me != null && gotKey == true)
                {
                    Destroy(this.gameObject);
                    Debug.Log("gotKey");
                }
            }
        }
    }

 

}

It’s basically because of your main cache declaration here:

private void Start()
     {
         hole = keyhole.GetComponent<Keyhole>();
     }

You offer no difference from Key1 to Key2, nor any difference from KeyHole1 to KeyHole2. The best way to handle this is to make a parent class Keys.cs and another KeyHoles.cs, and then create children classes that start like this:

public class Key : Keys

// and

public class KeyHole : KeyHoles

And then in the parent class make a static List of said children:

public static List<Key> allKeys = new List<Key>();
// keyhole etc...

And in the Awake function of the children:

// class Key

void Awake()
{
    allKeys.Add(this);
}

// class Keyhole
//etc...

So this way each new instance of a key you make, or keyhole, will be separated with it’s own identity. And all you would need for correct checks would be something like:

if (allkeys[index] == allKeyHoles[index])
     // unlock door

Very roughly said, but hopefully you get the idea. You will have to play around with this idea in order to get proper results, but it is the way I would handle it :slight_smile: