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.