Can access to a Transform variable in another script?

I’m trying to access to a static Transform variable in script B from script A.

But it’s not working. The error msg is like this.

MissingReferenceException: The object of type ‘Transform’ has been destroyed but you are still trying to access it.

Is it normal or I miss something? My code is …

script A>

Transform a = B.b; <=== Error!!

script B>

public static Transform b;

GameObject ga = Instantiate(Resources.Load(“Prefabs/item”)) as GameObject;

b = ga.transform;

Thanks for any advice…

You should Check variable b before use it:
if(b != null || b.gameObject.activeInHierarchy == true)
a = b;

You are trying to access the Transform in ‘b’ after you have destroyed it from somewhere in your script. You might be destroying the ‘ga’ gameobject whose transform is stored in the ‘b’.

So before you access the transform check if it is null or not like:

if(B.b != null)
    Transform a = B.b;


it is very easy to access transforms of other scripts. Let’s say you have script A and script B and you want to access the transform of script B variable then you have to do the following

Script A

  1. Assign a variable of the script that you are trying to access that is
    ScriptB scriptB;
    Note that the first “ScriptB” refers to the actual scriptB that you have previously created so it must be written exactly the same. The “scriptB” is a variable to hold that script you can name it as you like
    This has to be written on the variable definition area
  2. Now that you have declared a variable you have to get its reference. If the script it is attached to the same GameObject then you should write
    scriptB = GetComponent();
    If the script is attached to other gameObject you have first to get reference of the gameobject and then the component . That is
    scriptB = GameObject.Find(“Gameobject name”).GetComponent(); This must be written inside the Start function. Avoid to write this code inside the Update function cause it costs in matter of performance. Always use it on Start where it will be stored in the memory before runtime.
  3. to access a variable inside the script B then you have to do the following
    scriptB.transformVariable assuming that the variable transformVariable exists in scriptB.
    Also note that most probably you have to declare the transformVariable located on the script B as public in order to access it the script A.

I hope it helps.