I keep getting the error “object reference not set to an instance of an object” whenever I try to call anything anywhere from another GameObject or Script. I am simply trying to call the function moveRight() from within another script.
Here is one example:
GetComponent<playerTank>().moveRight();
Inside of playerTank.cs:
public void moveRight() {
transform.position = new Vector3 (transform.position.x + 1, transform.position.y, transform.position.z);
}
I’m fairly new to unity as a whole, so if I am missing some key concept, any help would be much appreciated.
If you have two different GameObjects, e.g. one called Tank and one called Movement, then they need to be connected to talk to each other.
By the sounds of it, you have the Tank GameObject, which has a PlayerTank script on it, and you want to call its “moveRight” function from another game object (e.g. “Movement”).
What you are doing in your first sample of:
GetComponent<playerTank>().moveRight();
is trying to get the component “PlayerTank” on the Movement game object - which it doesnt exist on.
That would find the object called “Tank”, grab its playerTank component, and then call the moveRight function.
Or, better yet, have a public variable in your script like so:
public playerTank m_Tank;
void MoveTankRight()
{
m_Tank.moveRight();
}
Then, in the inspector, you can hook up the reference to playerTank and call its functions (this will be much quicker than using GameObject.Find every frame, which you will need to do for handling movement).
This worked wonderfully! I always knew that it had something to do with a missing declaration of some kind, so indeed I do need to state it as GameObject.Component.Function.
+1 my fellow developer!