I cannot access a component from its own gameobject (unity3d)

1.5k Views Asked by At

I want to access the HorizontalAxis variable from the CarAgent component (of the Taxi gameobject). It works fine when I try to access it from another gameobject, but when I try to access it in CarUserControl, which is also a Taxi component, it says that CarAgent doesn't exist.

This is the other gameobject's script and it works fine:

private float HorizontalAxis;

public void Start() {

     HorizontalAxis = GameObject.Find("Taxi").GetComponent<CarAgent>().HorizontalAxis;
}

// Update is called once per frame
public void Update()
{

    transform.rotation = new Quaternion(0, 0, HorizontalAxis, 360);

}

and this is the CarUserControl script:

 private void Start()
    {
        HorizontalAxis = GameObject.Find("Taxi").GetComponent<CarAgent>().HorizontalAxis;
}

How can I access the HorizontalAxis variable in CarUserControl ?

EDIT: I tried to access other classes in this script and it doesn't work neither. I got this script from the UnityStandardAssets/Vehicules/Car, so at the beginning, it is written:

namespace UnityStandardAssets.Vehicles.Car
{
[RequireComponent(typeof (CarController))]
public class CarUserControl : MonoBehaviour
{

I am new to unity and c# so does it change something. And if yes, how can I fix it?

3

There are 3 best solutions below

0
On BEST ANSWER

Finally, the problem was that the CarUserControl was in the standard assets folder and that the CarAgent script was not in that folder. Apparently, the standard assets folder does not compilate at the same time as other folders. See more here!

1
On

It's mainly because there are inconsistencies between the Update() (every frame) and the FixedUpdate() (every physics frame). Indeed a FixedUpdate can be called more than once for the same Update() frame, or not at all.

Unity's doc about Order of Execution explains it more.

Also, querying GetComponent<T> in loops is quite heavy. It is wiser to "cache" the reference in an Init method like Start() or Awake().

private HorizontalAxis hAxis;

public void Start(){
    GameObject taxi = GameObject.Find("Taxi");
    if(taxi != null){ 
        hAxis = taxi.GetComponent<CarAgent>().HorizontalAxis;
    }
}

public void Update(){
   if(hAxis != null)
     transform.rotation = new Quaternion(0, 0, hAxis, 360);
}

public void FixedUpdate(){
    if(hAxis != null){
        // Do only Physics related stuff: rigidbodies, raycast
        // inputs and transform operations should stay in the Update()
    }
}
10
On

Its likely that you are too low or too high in the gameobject chain.

Try

car = GetComponent<CarAgent>(this.parent);

OR

car = GetComponent<CarAgent>(this.child);
h = car.HorizontalAxis;