GetComponent of this object

I don’understand well how GetComponent works. Let’s say that I attach a script to an object and inside the script I want a reference to some THAT object value (like Nav Mesh Agent speed, for example). So I do:

var agent : NavMeshAgent;

function Start () {
	agent = GetComponent(NavMeshAgent);
}

Now I can access agent.speed but only after i pointed the NavMeshAgent in the inspector. How can I tell the script that the NavMeshAgent I’m referring to is the one of the Object that it is attached to directly from the script?

GetComponent gives you the component of type “T” attached to the object you called this funtion from.
Where are you attaching the Component from script? You will add component either from script or from inspector. In both cases this will work because there is no point in attaching the same component twice on the gameobject. So whenever you will write this:

  agent = GetComponent(NavMeshAgent);

It will give you the attached component of type “NavMeshAgent” regardless of how it was attached to the gameobject i.e. from inspector or from script.

If you are talking about the field appearing in inspector then yes that is because it is public variable, but it does not matter whether you assign the reference from inspector or from script. If you want to assign reference from script then there is no need to make it public.

@Eradan here is the answer.

What do you mean by directly attached?

Is it a child? Then try GetComponentInChildren<NavMeshAgent>();

Otherwise try to put GetComponent in the OnAwake method, not Start.

Or try to directly get the component when you declare the variable in the beginning (I just woke up, dunno if that’s a good approach)

@Eradan You wrote GetComponent in start method

I think you are calling GetComponent() before you attach T to gameobject from script.

Try it

agent = gameObject.AddComponent<NavMeshAgent>();

Maybe try using gameObject, e.g.

 function Start () {
     agent = gameObject.GetComponent(NavMeshAgent);
 }