Triggerexit, behaviour issue

Hello, I have a problem with disabling a GUIText, in the scene “OnTriggerExit”. The code at the very bottom doesn’t throw and error until I have exited the collider and shows “Not set to an instance of an object”. I’m not really sure how to disable this GUIText.

using UnityEngine;
using System.Collections;

public class MyController : MonoBehaviour 

{
	public GameObject Door;
	bool Mission01 = false;
	public GUIText XPtext;
	

	void OnTriggerEnter (Collider Collided)
	{
		if (Collided.gameObject.tag == "MerchantCollider")
		{
			XPtext.text = "Go collect item";
			//GetComponent.<XPtext>().enabled = true;
		}
		
		else if (Collided.gameObject.tag == "Door")
		{
			//Debug.Log ("Door");
			if (Mission01)
			Door.gameObject.animation.Play ("Open");
		}
		
		else if (Collided.gameObject.tag == "Cube")
		{
			Mission01 = true;
			Destroy (Collided.gameObject);
		}	
	}	
	
	void OnTriggerExit (Collider Collided)
	{
		if (Collided.gameObject.tag == "MerchantCollider")
		{
			
			var guiComponent = GetComponent("XPtext").guiText;
			guiComponent.enabled = false;
		}
	}
}

Thanks!

var guiComponent = GetComponent(“XPtext”).guiText;
guiComponent.enabled = false;

That. Ok so the way I see it you got this code from another Unity Answers thread, which is perfectly fine, but you should always check to see if the code you’re implementing fits in your own code.

In this case the main problem is that you’re mixing between Javascript and C# (“var” is used strictly in Javascript). Also I see that the GUIText XPtext has already been defined in your code at line 6, so you don’t have to use GetComponent().

This should work just fine:

void OnTriggerExit (Collider collided)
{
   if(collided.gameObject.tag == "MerchantCollider") {
      XPtext.enabled = false;
   }
}

Also, just a small remark I have to mention - try to avoid naming your variables with an uppercase letter in the beginning, this might help avoid problems further down along the road.

Hope this helps :slight_smile: