How to access non static C# variable from another C# script
Hey there,
I have two scripts, Script1 and Script2. I want to access and edit a float variable from Script1 in Script2, but I'm not sure how. I haven't found any up-to-date ways to do it online, and I'm rather new to scripting.
Thanks so much.
Answer by Glurth · Feb 11, 2017 at 07:36 PM
The simplest way to do this is to add a reference to script1, as a public member variable in script2. Then, in the editor, simply drag the object with script1 attached, over this field on script2. Now, you can refernce the other script, via this member variable.
e.g. (uncomplied or tested, example only)
public class Script1:Monobehavior
{
public int anInt;
}
public class Script2:Monobehavior
{
public Script1 aScriptReference;
public string aString;
public void Update()
{
if(aScriptReference==null)
Debug.Log("you need to specify the Script1 object to use in the inspector.");
else
Debug.Log("Scripts interger:" + aScriptReference.anInt); //this is where we reference the member of the other script.
}
}
Your answer
Follow this Question
Related Questions
C# - Cannnot access variable in another script unless I get the component everytime. 1 Answer
Custom inspector. Pick one bool from a list. 1 Answer
Set a variable from another script 1 Answer
Interchangeable animations in a script? 0 Answers
Change in Editor via Script Values of another Script 2 Answers