How to access variable from another c# script file?

Hi,

I am a unity newbie, know this is really quite a common question, and I have tried to look at some of the examples in the Unity scripting reference and unityAnswers, but I seem to be missing something in my understanding. Please note that I would prefer to use non static method.

I have a C# script named mycam.cs this is going to be attached to the Main Camera, on run mode, and initialized a variable, target which is a Transform type on load.

I have another file named mymap.cs, and within this file, I need to access the target Transform from the mycam.cs file, and use it within my mymap.cs script.

I have seen examples like Referencing non static variables from another script? C#, but it does not seems to work on my script.

Here's my script so far.

MyCam:

public class MyCam: MonoBehaviour {
    public Transform target;
    public float targetHeight = 2.0f;
    public float distance = 3.0f;

void LateUpdate ()
    {
    // Ignore if target is not defined
        if (!target)
            return;
    }
}

MyMap:

public class MyMap: MonoBehaviour {
    public Transform player;
    void Start()
    {
        GameObject target = GameObject.Find("target");
        MyCam myCam = target.GetComponent<MyCam>();
        Debug.Log("distance: " + myCam.distance);
        player = myCam.target;
    }
}

But when I tried to run, I received errors:

UnassignedReferenceException: The variable player of 'MyMap' has not been assigned. You probably need to assign the player variable of the MyMap script in the inspector.

I understand that somehow my player is not initialized for mymap script, but the target in mycam script is.

Kindly advise. Thanks.

If the MyCam script is attached to the main camera, instead of:

GameObject target = GameObject.Find("target");
MyCam myCam = target.GetComponent<MyCam>();

do:

MyCam myCam = Camera.main.gameObject.GetComponent<MyCam>();

Or, if you don't want to use Camera.main, set a reference to the camera in the inspector, e.g. in MyMap

public Transform theCamera;

And then it would be:

MyCam myCam = theCamera.gameObject.GetComponent<MyCam>();