- Home /
Why doesn't this work? Comparing gameobjects in OnTriggerEnter
I cannot understand why this code does not work:
var playerObject : GameObject;
function OnTriggerEnter ( other : Collider) {
if ( other.gameObject == playerObject ){
print( "Player triggered the trigger." );
}
}
playerObject is defined (in the inspector) as the player.
When I take out the conditional and replace it with
print( other.gameObject + " triggered and should be compared to " + playerObject );
the output is "Player triggered and should be compared to Player" (when the player enters the trigger collider)
So why isn't the conditional true???
Do you have multiple gameObjects named 'Player'?
Just curious - what happens if you print out the positions of the two objects? Are they at the same point in space?
Debug.Log("Other: " + other.gameObject.transform.position + ", playerObj: " + playerObject.transform.position);
Answer by buscommando · Mar 01, 2013 at 03:09 AM
Apparently when I set the gameObject with the inspector, I clicked on the dot and chose the gameObject from the list that shows up. I can't explain why this is wrong, but it is.
I got it to work by dragging the gameObject from the scene hierarchy into the script's inspector pane.
I can only assume that the gameObject that I chose originally was the prefab from my assets folder and not actually an existing object in the scene.
Your answer
![](https://koobas.hobune.stream/wayback/20220613093528im_/https://answers.unity.com/themes/thub/images/avi.jpg)