Why is my Unity script overwriting other game objects on which it is attached to?

I’m trying to show different documents to the player when it comes near the pages. I have two pages, both of them are colliders which have triggers, they are using the same script, but with different game objects in the inspector (for showing different documents). A text box would pop up beforehand, which tells the player to enter space key in order to view the document. If the player comes near the Page 1, the ‘Image panel’ should pop up. If the player comes near the Page 2, the ‘Test panel’ should pop up. After viewing the document, that page should be destroyed.

The below image is for ‘Page 1’
193835-page1.png

The below image is for ‘Page 2’
193836-image2.png

However when the player comes near the Page 1, ‘TEST panel’ always pop up instead of ‘Image Panel’ and BOTH of the pages get destroyed afterwards. ‘TEST panel’ is showing because Page 2’s script has overwritten the Page 1’s script in a sense, I believe. I am really confused in this matter, I am a beginner at Unity, here is the script:

using UnityEngine;
public class ViewDocument : MonoBehaviour
{
    public GameObject theText;
    public GameObject theDocument;
    public static bool viewDocument;
    public static bool documentOpened;
private void OnTriggerEnter(Collider other)
{
    if (other.tag == "Player")
    {
        theText.SetActive(true);
        viewDocument = true;
    }
}
private void OnTriggerExit(Collider other)
{
    theText.SetActive(false);
}
private void showDocument()
{
    theText.SetActive(false);
    Debug.Log("Now showing " + theDocument.name);
    theDocument.SetActive(true);
    documentOpened = true;
    Time.timeScale = 0f;
}
private void closeDocument()
{
    Time.timeScale = 1f;
    theDocument.SetActive(false);
    Destroy(gameObject);
}
private void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) && viewDocument == true)
    {
        Debug.Log("Before show doc :" + documentOpened.ToString());
        showDocument();
        viewDocument = false;
        Debug.Log("After show doc :"+ documentOpened.ToString());
    }
    else if (Input.GetKeyDown(KeyCode.Space) && documentOpened == true)
    {
        closeDocument();
        Debug.Log("Document closed!");
    }
}

Your help would be much appreciated!

Your variables “viewDocument” and “documentOpened” are static which means that every instance of the class ViewDocument share those variables basically. So if you go near Panel1, viewDocument will be true for every ViewDocument class. Panel 2 will think that you are close to that one aswell, when you then press space, both panels will open up at the same time. I don’t see why you would want those variables to be static in this case so by removing the static keyword your problem should go away :slight_smile: