Question about OnControllerColliderHit

I have a question about OnControllerColliderHit…

In my scene, I have a player rigged with a character controller. When the player hits another (enemy) character controller, I want to teleport the player controller to another location.

Sounds simple enough, and I was able to get this to work but not in the way I expected and I don’t exactly understand why.

This code did NOT work, but I expected it to:

function OnControllerColliderHit (hit : ControllerColliderHit)
{
	if (hit.gameObject.name == "Cube")
	{
		Debug.Log (hit.gameObject.name);
		TeleportPlayer();
	}
}

function TeleportPlayer ()
{
	transform.position = Vector3 (0,0,0);
}

For some reason the TeleportPlayer function would never work, although the hit detections were definitely being registered by Debug.Log.

When a put a boolean check in my Update Loop everything worked fine:

function Update 
{

    if (teleport)
    TeleportPlayer ();
 
}

function OnControllerColliderHit (hit : ControllerColliderHit)
{
	if (hit.gameObject.name == "Cube")
	{
		teleport = true;
	}
}

function TeleportPlayer ()
{
	transform.position = Vector3 (0,0,0);
	teleport = false;
}

Being new to scripting, I’m curious as to why this is the case as I feel like there is something I do not fundamentally understand about OnControllerColliderHit event.

I can only assume, that in the first example, the hit was always true and was overriding the teleport position.

Can somebody shed some light on this?

Well, the only reason I can see for this would be if something was overwriting your position for some reason. If Debug.Log is playing, then that means the event is triggered properly. The difference is that Update will set the position to Vector3.zero once a frame, which would overwrite any other movement code.

To test this, could you put Debug.Log in TeleportPlayer() to test the first one? If Debug.Log is playing inside the function itself, then something is overriding your transform.position.

I think you’re right because the function was definitely getting called. I guess the locomotion code in my Update Loop was obliterating everything else. Thanks GS.