- Home /
Trigger GUI working wrong
Hello!
I have a script that should activates a trigger when you enter the collider. But if I start the scene the trigger is already true. What is wrong with the script?
using UnityEngine;
using System.Collections;
public class dialogue : MonoBehaviour {
public bool triggered = false;
public float WaitTime = 4;
public Collider collision;
public Texture2D textureToDisplay;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
triggered = true;
WaitTime -= Time.deltaTime;
if (WaitTime < 0)
{
triggered = false;
Destroy(this);
}
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI() {
if (triggered = true){
GUI.Label(new Rect(10, 10, 100, 20), "Hello World!");
GUI.Label(new Rect(10, 40, textureToDisplay.width-500, textureToDisplay.height-500), textureToDisplay);
}
}
}
Comment
Answer by aldonaletto · Dec 01, 2012 at 05:39 PM
You're actually setting triggered to true in this instruction:
if (triggered = true){
You should use the equality operator == instead:
if (triggered == true){
or, better yet, use just the boolean variable:
if (triggered){
Boolean variables are intended to be used this way, not to be compared to true or false - when you compare a boolean to true, the result is exactly the value of the boolean, thus this is redundant (and a magnet for errors like this one).
By the way, you should move the timing code that clears triggered to Update (it will not work fine inside OnTriggerEnter):
...
void Update(){
if (WaitTime > 0){
WaitTime -= Time.deltaTime;
if (WaitTime <= 0)
{
triggered = false;
Destroy(gameObject);
}
}
}