Accessing a variable inside a class inside other script...

Hello everybody, i’ve seen a lot of questions related to that question. I’ll ask about access a variable inside a class from other script from other gameObject, such access a script from a enemy for a player, but how I do that? I’ve tried:

var motor: Character;
var playerDistance : Vector3;

function Start () {
	motor = GetComponent(Character);
	
	playerDistance = motor.playerPosition - transform.position;
	
}

As all of you can see, my playerPosition is a variable inside a class inside my script of the player. I cannot access it, this error appears:

NullReferenceException: Object reference not set to an instance of an object

So I tried this one:

var motor: Character;
var playerDistance : Vector3;
    
function Start () {
   motor = gameObject.GetComponent(Character);
    	
   playerDistance = motor.playerPosition - transform.position;
    	
}

I see in the inspector the motor variable, I’ve tried to put my player inside it, but when I execute the game, the variable clean itself and throw the error.

[17092-sem+título.png|17092]

I’ve seen this error in this question: http://answers.unity3d.com/questions/58075/access-variable-in-a-class-from-another-script.html

I’ve tried it, but didn’t work out too.

In most cases it just means you have to make your variables public. (protected also works in some cases, but than it has more restrictions)
If it still doesn’t work add a using [namespace of other class] at the top and it will see the class.

Furthermore it depends on the design pattern you implemented. (or that you just wrote some spaghetti code…)
More info on design patterns: http://www.oodesign.com/
With good design implementations you have the correct accessibility for the classes that need it.

I think your problem is that your class does not inherit MonoBehaviour. Then GetComponent cannot work on it. Hence it does not find the component and return null.

class CharacterInformation extends Monobehaviour{}