NullReferenceException-Error when trying to GetComponent

Hi guys!

I got multiple planes (lakes) in my scene and if my player moves to a lower y-value than the plane-positions, an underwater-look is activated!

Every single lake has a script attached to it and calls a function in the script “Overseer” (which is located on a “manager-object”), whenever the player starts diving…
Now the problem is, that when the Overseer-script tries to get the component “CharacterMotor” on the main camera to deactivate it, it doesn’t work.

In fact, Unity gives me a NullReferenceException-Error.
It seems like my script is not capable to/doesn’t find the “CharacterMotor”-script!?

Anyway, here are the lines, on which it gives me the error:

...
var normalmotor : CharacterMotor = FirstPersonController.GetComponent.<CharacterMotor>();
  if(normalmotor.enabled == false){
  	normalmotor.enabled = true;
  	}
...

I really don’t know what I did wrong so I’m grateful for any kind of help!

Thanks

You have a typo. It should be:

var normalmotor : CharacterMotor = FirstPersonController.GetComponent<CharacterMotor>();

You had an extra period between the function and the type directive.

You might know some of the things I am about to say but for others sake I am going to state them. First you need a script called exactly “CharacterMotor” for this is case-sensitive. Then one must put the “CharacterMotor” script on the FirstPersonController object. Then one way to call the script is:

var normalmotor:CharacterMotor = (CharacterMotor)FirstPersonController.GetComponent(“CharacterMotor”);

I did something similar like this, this is in C#:

public GameObject thisObject;//could be any object I want
Monologue mono1 = (Monologue)thisObject.GetComponent("Monologue");//the object I pick must have this script on it or it will be null

Thank you all for your answers!

I solved the problem by just adding the CharacterController-, the CharacterMotor- and the FSPInputController-Components/Scripts in the Start Function of my “Overseer” and saving it as a variable:

function Start (){
    charactercontroller = FirstPersonController.AddComponent(CharacterController);
    charactermotor = FirstPersonController.AddComponent(CharacterMotor);
    FirstPersonController.AddComponent(FPSInputController);
}

Like that, I was able to disable and enable the different scripts/components:

...
charactercontroller.enabled = false;
charactermotor.enabled = false;
...