- Home /
Cannot access a variable in another Script.
How can I access a variable(bool) in script B from script A, if script A is in a prefab, and script B is not. I just need a general example.
//This is Script A attached to a prefab
void Update(){
if (whatever == true) {
//Blabla
}
}
//This is Script B attached to a gameObject in Scene
public bool whatever;
public void OnGUI(){
if(Gui.Button(new Rect(1,3,3,7))){
whatever=true;
}
}
I have tried using the inspector but it isnt possible because A is attached to a prefab. So I go like:
//This is Script A attached to a prefab
void Update(){
if (ScriptB.whatever == true) {
//Blabla
}
}
//This is Script B attached to a gameObject in Scene
public bool whatever;
public void OnGUI(){
if(Gui.Button(new Rect(1,3,3,7))){
whatever=true;
}
}
But then the compiler yells: "An object reference is required for the non-static field, method, or property ScriptB.whatever" and I try to change it to static bool whatever
;
and the compiler goes: "Bro, I cannot access that variable due to its protection level"
I have tried a lot of different things but none of them have worked, What do!?!?
Answer by robertbu · Feb 03, 2014 at 03:23 AM
Your question is backwards. Since 'whatever' is declared in ScriptB, you are trying to have Script A access 'whatever' in Script B. So assuming ScriptA is the prefab, you can do this. At the top of the file put:
private ScriptB scriptB; // Change to whatever the script is named
Then in Start():
void Start() {
scriptB = GameObject.Find("GONameForScriptB").GetComponent<ScriptB>();
// The Find() uses the name of the game object with ScriptB.
}
Then in Update() you would do:
if (scriptB.whatever) {
//Do something
}
As the code stands now, you need to be sure the named game object with ScriptB exists since you will get a null reference exception from this code if it does not.
Answer by JotaRata · Feb 03, 2014 at 03:57 AM
or you may declare that bool, at begining of the class
//Your Class ScriptA
public class Script : MonoBehaviour{
// declare variables
public bool Whatever;
public int NumberOfTheBeast=666;
void Start(){}
void Update(){
//do Something
}
}
and then...
//script B
public class blabla: monobehaviour{
public/private bool scriptABool;
public/private Gameobject/Object scriptAObject;
void Start(){
scriptABool=scriptAObject.GetComponent<scriptA>().whatever;
if (scriptABool==true)
{
/Do Stuff:D
}
}
}
@JotaRata - this won't work. According to the OP, ScriptA is on a prefab, and therefore it won't exist when the app starts...plus you will not be able to initialize 'scriptAObject' in the Inspector. The result is that line 10 in the second script will fail with a null reference exception..
robertbu
ooh you're right, only will work if ScriptA is on a GameObject, well thanks for your comment i've learned a new thing about unity:)