'Why Unity script is overwriting other game objects data 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 above image is for 'Page 1'
The above image is for 'Page 2'
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); //shows 'Test Panel' in Log, even when 'Image panel' is selected in the inspector for Page 1
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 is much appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


