How do I access a variable of a script from another script in C#?


I know that this question has been answered for JavaScript several times, but I dont find anything for C#.

A have a script ScriptA.cs and a script ScriptB.cs; Both scripts are located in the same project folder.

public class ScriptA : MonoBehaviour

    //player name
    public static string playername = "";



If I want to access playername from ScriptB like:

string name = ScriptA.playername;

I get the error: "The name 'ScriptA' does not exist in the current context"

What is missing or wrong?

Thanks in advance for any help, Vudu

That should work as you have it already. Because you're using a static variable, the `TypeName.staticVariableName` form should work as-is.

Just make sure you have the filenames set the same as the class name, and that you have this at the top of both scripts:

using UnityEngine;

Perhaps there's a problem with a typo somewhere, either in the filename or the script name reference?

Maybe you have ScriptB in a folder which designates an earlier compilation pass, so the compiler is unaware of ScriptA at that point?

Are you certain you aren't mixing C# and Javascript files?