Get value from another Script

Hello, I have a problem.

Normal you can get a value, like a bool, from another script that way:

public ScriptA script;

bool booleanb;

void Update(){
       booleanb = script.booleana;
}

But for me this doesn’t work…
And if I try it with PlayerPrefs and ints I get this: “(…)can only be called from the main thread”.

What can I do?

Is the bool public?

Yes it is.

Hello and good evening!

There are a few things I would try.
First thing is that to be able to call a variable from another script, I know that you have to have that instance “saved.”
To put it another way via example, you could have the following.

public ScriptA script;

void Start()
{
script = gameObject.GetComponent<ScriptA>();
}

Furthermore, you need to make sure to have an instance of ScriptA within ScriptA itself.
Via example, you could have the following.

public ScriptA instance;

public class ScriptA : MonoBehaviour
{
void Start()
{
instance = this;
}
}

And from there, you should be able to do the following and access your booleana.

void Update()
{
booleanb = script.instance.booleana;
}

Another way to do this is to use a static instance, and this negates having to get the component, but take note that this only works on objects that are “unique,” IE not on an enemy prefab that’s littered about in your scene. All you would have to do is modify “public class ScriptA” to “public static class ScriptA,” and do “instance = this;” in the Start() method of ScriptA.
Then it’s a simple matter of doing the following.

void Update()
{
booleanb = script.instance.booleana;
}

To answer some potential questions I can see arising, such as doing the GetComponent business if the script is on another object that ScriptB is not attached to. I know of a few ways to do this, but the easiest, in my opinion, if you’re not using a static instance is to do something like the following.

void Start()
{
script = GameObject.Find("Object name that ScriptA is attached to").GetComponent<ScriptA>();
}

However, if you’re dealing with a static instance of a script, then there is, again, no need to do the aforementioned.

I hope this helps, and good luck!
Any questions, just let me know! I’ll answer as soon as I have the time.
-Hypocrita

PS. If anyone sees any errors in my answer, do let me know! I’m still fairly new to Unity, and as such am prone to errors from time to time!