I’ve set up a key-door system in my game. To open a door, you need to collect a key somewhere in the level and open it with that key. I have several of these in a single level. The system works perfectly, but I have a little issue: when collecting the key, a “Key Collected” GUI text is supposed to appear, but it only appears rarely. How can I solve this? Note that every level has several keys.
Key script:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
[System.Serializable]
public class DoorKey : MonoBehaviour
{
public bool inTrigger;
void Start()
{
DoorScript.doorKey = false;
}
void OnTriggerEnter(Collider Player)
{
inTrigger = true;
}
void OnTriggerExit(Collider Player)
{
inTrigger = false;
}
void Update()
{
if (inTrigger && DoorScript.doorKey == false)
{
DoorScript.doorKey = true;
Destroy(this.gameObject);
}
}
void OnGUI()
{
if (inTrigger)
{
GUI.Box(new Rect(0, 90, 200, 25), "Press E to take key");
}
if (inTrigger && DoorScript.doorKey)
{
GUI.Box(new Rect(0, 90, 200, 25), "You have already collected a key!");
}
if (DoorScript.doorKey)
{
GUI.Label(new Rect(10, 80, 100, 20), "Key Collected");
}
}
}
Door script:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class DoorScript : MonoBehaviour
{
public static bool doorKey;
public bool open;
public bool close;
public bool inTrigger;
void OnTriggerEnter(Collider other)
{
inTrigger = true;
}
void OnTriggerExit(Collider other)
{
inTrigger = false;
}
void Update()
{
if (inTrigger)
{
if (close)
{
if (doorKey)
{
if (Input.GetKeyDown(KeyCode.E))
{
open = true;
close = false;
DoorScript.doorKey = false;
}
}
}
else
{
if (Input.GetKeyDown(KeyCode.E))
{
close = true;
open = false;
}
}
}
if (open)
{
Destroy(this.gameObject);
}
else
{
}
}
void OnGUI()
{
if (inTrigger)
{
if (open)
{
GUI.Box(new Rect(0, 90, 200, 25), "Press E to close");
}
else
{
if (doorKey)
{
GUI.Box(new Rect(0, 90, 200, 25), "Press E to open");
}
else
{
GUI.Box(new Rect(0, 90, 200, 25), "Need a key!");
}
}
}
}
}