- Home /
NullReferenceException: Object reference not set to an instance of an object
The code is to pick up an object which increases the players speed. maxForwardSpeed is a variable of class characterMotorMovement which is in CharacterMotor. I get nullReferenceException when i run this code and try to pick up the object.
function OnTriggerEnter(other:Collider) {
var fpc = other.gameObject;
var fpcComponent = fpc.GetComponent("CharacterMotor");
fpcComponent.CharacterMotorMovement.maxForwardSpeed = newSpeed;
Destroy(gameObject);
}
Answer by cupsster · Feb 15, 2012 at 12:13 PM
function OnTriggerEnter(other:Collider) {
var fpcComponent:CharacterMotor = other.gameObject.GetComponent("CharacterMotor") as CharacterMotor;
fpcComponent.CharacterMotorMovement.maxForwardSpeed = newSpeed;
Destroy (gameObject, 0.0f);
}
Un-tested!
Answer by aldonaletto · Feb 15, 2012 at 12:15 PM
1- CharacterMotorMovement is the type, not the actual variable; the CharacterMotorMovement variable created in CharacterMotor.js is movement.
2- You can use other.GetComponent(...) directly.
3- GetComponent("CharacterMotor") returns type Component, and you need the type CharacterMotor to access the movement variable - pass CharacterMotor without quotes and GetComponent will return the correct type.
4- To avoid runtime errors case other object enters the trigger, check if fpcComponent isn't null (what happens when the object doesn't have a CharacterMotor script):
// you can get a component using the 'other' collider directly:
var fpcComponent = other.GetComponent(CharacterMotor); // use the type without quotes
if (fpcComponent){ // check if fpcComponent isn't null
fpcComponent.movement.maxForwardSpeed = newSpeed;
}
Your answer
Follow this Question
Related Questions
NullReferenceException question. 2 Answers
Object not responding to OnTriggerEnter() 2 Answers
Help with light Switch Script 1 Answer
can you use onmouseover without a collider on object 1 Answer
Best practice for checking which object has collided. 2 Answers