Search code examples
c#unity-game-engineunity-components

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


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?


Solution

  • 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!