- Home /
Script works for NPCs, but not Player
I'm developing a racing game, and as the cars pass through the finishline trigger it activates the script Finishline.js, each racer also has the script Stats.js attached to it. When the NPCs run through the trigger it activates Finishline.js which then changes the value inside Stats.js. It works fine for the NPCs but not for the player. There is nothing that I can see differs in this circumstance between the player and the NPC. Please help!
//Finishline.js function OnTriggerEnter (other : Collider) { var currentplayer : Stats; currentplayer = other.gameObject.GetComponent(Stats);
if(currentplayer.currentlap==1 && currentplayer.valid)
{
//does action blah blah
}
}
//Stats.js public var currentlap : int = 1; public var valid : boolean = false;
Thanks in advance! =]
Edit: The actual collider triggering works. I get an Object reference not set to an instance of an object error.
What line is that error on? Does your player object have a collider on it?
Yeah, it collides and triggers fine. The error is on the line with the if statement. Another weird thing is that I have another object that is supposed to disable the renderer onCollision and it only disables it when the player hits it and not the NPCs. I can't win! haha
Answer by Molix · Jan 25, 2011 at 03:23 AM
If you are getting "Object reference not set to an instance of an object", then that means that the "currentplayer" object is null, i.e. it was not found in the "other" game object.
First off, add a check after GetComponent, e.g.:
if( currentplayer == null ) { // uncomment the logging line below for debugging only // Debug.Log("No Stats component found in " + other.gameObject.name );
return; }
If you're sure there is a Stats component in the player (and not just the NPCs), then it could be that there are multiple colliders/gameobjects that make up the player. So you might, for example, be looking for the Stats component in the wheel gameobject rather than the body. Assuming you put the Stats component in the root object, you could instead do:
currentplayer = other.transform.root.GetComponent(Stats);
That would check the root/topmost object in the other object's hierarchy for the Stats component. I hope that helps.
Stupid me! It needed to be in the root object. Thanks, man. You rock!