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!?!?
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.
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
}
}
}