script A reads the data from Script B

Hi
I have a doubt that I don’t know if it’s possible to help me

I have a script A and a script B.
Script A is on Object A and script B is on Object B.
Script B simply does true or false.
Is there a way for me to access script B and read what it is returning?

example.
I want object A to make X when Object B’s Script is and return true.

You need a reference to the component you want to work with. Since you did not provide code, let’s say your ScriptB (from now on its official name) is basically empty, except for a public bool myBool = true;

To access that you need a reference to that specific instance of ScriptB inside your ScriptA.

// In ScriptA, we add a public variable for a ScriptB object
public ScriptB scriptB;

After compiling, you will notice a field with the corresponding name show up in the inspector of any object with ScriptA attached. Since there could be a lot of different ScriptB’s in your scene, you now need to clarify which one you want to work with here. To do so, simply drag your object containing the ScriptB you want to work with into that field.

Afterwards you can access any public members of that ScriptB instance inside ScriptA by writing, for example:

scriptB.myBool = false;

If you are waiting for a change or a specific state (like true) to happen, you can just check the value each Update() cycle.

// Inside Update of ScriptA
if(scriptB.myBool){
    // Do X
}

Depending on how exactly the connection between these two objects is handled, you could also use a property for myBool, which listens to a change, and then executed something in ScriptA instead. This way you would not have to check every frame.

1 Like