my c# variable can't be assigned

I have a script on a prefab, on that script I have a variable. That variable is assigned in the update function,

public GameObject MyVar;

void Update() {
    MyVar = GameObject.FindObjectWithTag("MyTag");

But every time I try to use this, it puts up an error: “The variable MyVar of MyScript has not been assigned.
You probably need to assign the MyVar variable of the MyScript script in the inspector.”
Does anyone have a clue why this is happening?

This is because the variable is being assigned when you run your script. So essentially the variable will appear empty until your script is compiled and run.

The reason it doesn’t stay is that after the code finish’s running the variable is reset to its original state of ‘null’ or ‘empty’.

Its because you need to assign it in the inspector. Not declare it in the code then drag and drop the gamobject into the script to assign it

I haven’t figured it out, but I have a solution, that did work.
Instead of having a variable, then doing something with that,
I used GameObject.FindObjectWithTag(“MyTag”);
Yes I know this is very inefficient, but it wouldn’t let me assign my variable,
no matter what I did.