Update function returns NullReferenceException ,if(!motor.canControl) returns a NullReferenceException

Hello, I’m very new to scripting and I’m trying to modify the bootcamp SoldierController script to work with my own soldier. I’ve aproached this by opening a new controller script and copying accross individual lines of code and trying to understand what they are doing as I go.

Currently I’m getting an error “NullReferenceException: Object reference not set to an instance of an object” from the Update function [from the line “if(!motor.canControl)”].

I understand that this error generally means that the script references something that doesnt exist, but:

  1. I’ve included the following line in the code:
    private var motor : CharacterMotor;
  2. I’ve included the following line in the “Start” function (which I don’t fully understand btw).
    motor = gameObject.GetComponent(“CharacterMotor”);
  3. I have the CharacterMotor.js script added to my character.

I would have thought this would allow the line to find the “canControl” boolean variable in the CharacterMotor script.

Here is the Update function. Please say if I should provide the entire script.
I’d really appreciate any answers on this, I’ve been trying to figure it out for a few hours and havent got anywhere.

function Update() 
{

	if(GameManager.pause || GameManager.scores)
	{
		moveDir = Vector3.zero;
		motor.canControl = false;
	}
	else
	{
		GetUserInputs();
		
		if(!motor.canControl)
		{
			motor.canControl = true;
		}
		
		if(!dead)
		{
			moveDir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
		}
		else
		{
			moveDir = Vector3.zero;
			motor.canControl = false;
		}
	}
}

Instead of if(!motor.canControl) try if(!motor.enabled), worked for me when I needed to switch of my CharacterMotor.

@ysefkerr

From your updated error, it looks like we’re making progress. The error means that we’re trying to stick a value into a variable that was defined differently, like trying to stick a string into an integer or a square peg into a round hole. I don’t see where you’ve defined the motor variable. Take a look at the example page (http://unity3d.com/support/documentation/ScriptReference/GameObject.GetComponent.html) and note where they define var [varname] : ScriptName. You’ll need something like that, and it needs to be outside the Start() and Update() functions (e.g. a global variable) or else it will only be defined for those functions and disappear when they complete. You may also want to set #pragma strict (see this page: http://unity3d.com/support/documentation/ScriptReference/index.Performance_Optimization.html) which will force you to explicitly define all variables and avoid these types of problems in the future.