Trouble with OnTriggerEnter and GetComponent

UPDATE

Well I am still lost. I added a few more debug statements:

	void OnTriggerEnter(Collider col)
	{
		playerIsNearDeadMob = true;
		myGuiScript = col.gameObject.GetComponent<myGUI>();
		Debug.Log("You have entered dead corpse");
		if(myGuiScript == null)
		{Debug.Log ("Gui script is null...");}
		else
		{Debug.Log("guiscript is not null");}
	}

Now when I enter the trigger, here is the debug that prints:

You have entered dead corpse
GUI Script is null…
Guiscript is not null
you have exited corpse

So even though I never leave the trigger it seems to think I have left the trigger. Doesnt make any sense. I tried making the trigger bigger to no avail :confused:

Hello,

I have a script which is on a (dead) mob and uses OnCollisionEnter to detect that the player is near via a sphere collider, and once the player has entered it, it uses GetCompenent to access the a script on the player called myGUI. It then it turn runs a script which opens a loot window for the player to loot items.

The problem I am having is that the sphere collider detects the player, but I am getting a null reference from the GetCompenent. When I try to access the variable myGuiScript, its null.

Would you mind taking a look and seeing if you can find why myGuiScript would be null?

Here are the pertinent parts of the script:

private myGUI myGuiScript;
public bool playerIsNearDeadMob = false;

public void OnMouseUp()
	{
		if(myGuiScript == null)
			Debug.Log ("Player is not close enough to the loot");
		
		else if(playerIsNearDeadMob)
		{
			switch(state)
			{
			case State.open:
				state = MobLoot.State.inBetween;
				StartCoroutine("Close");
				break;
			case State.closed:
				state = MobLoot.State.inBetween;
				StartCoroutine("Open");
				break;
			}
		}
		
	}

	void OnTriggerEnter(Collider col)
	{
		playerIsNearDeadMob = true;
		myGuiScript = col.transform.GetComponent<myGUI>();
		Debug.Log("You have entered dead corpse");
	}
	
	void OnTriggerExit()
	{
		StartCoroutine("Close");
	}	

OnMouseUp, it tells me I am not near enough to the mob, basically saying that myGuiScript is null, even though per my other debug.log, I AM inside the collider. Then I also get a null reference for one of the myguiscript.whatever in the coroutines.

Try adding ‘gameObject’ after ‘transform’:

myGuiScript = col.transform.gameObject.GetComponent<myGUI>();

(This is related to the component null problem.)

won’t help :wink:

but I think I found a solution :wink: - according to the API for OnTriggerEnter :

Note that trigger events are only sent if one of the colliders also has a rigidbody attached. !

if that is what you need. I tried it and my objects can now access the script.

Ended up getting this working. It was another “mob” walking around screwing up my trigger, DOH! :slight_smile: