- Home /
How can I efficiently access a particular game object's script's member variables from within another script?
I know this question sounds like a duplicate but I really have looked around already, and if you read on you'll see I'm aware of at least one method but want to know of others.
What is the best way to manipulate a variable within a specific game object’s script? I’ve learned that the problem with setting the variable to ‘public static’ and accessing the variable using ‘exampleScript.desiredVariable’ is that a static member acts as a universal member for the class, whereas I need to access a unique value for a given instance of that script.
The one method I am aware of is creating a new variable of the type ‘exampleScript’ within the script that would like to access ‘desiredVariable,’ because I can then assign a particular game object’s script to this variable and access and modify the members of the particular script by modifying members of the variable.
But what else is there? I am a little concerned that this is going to use up unnecessary space. Why create a new variable which contains all the data of MonoBehaviour plus whatever variables and methods I have written in the script, when that data (presumably) exists somewhere on the RAM already? Is there no way to access it without creating a duplicate instance? Is this as unnecessarily wasteful as I’m thinking it is, or I overestimating the overhead involved here? Please help, and thanks in advance.
Answer by DanSuperGP · Jan 07, 2015 at 09:39 PM
It doesn't make a copy.
It's just a reference to the other Monobehavior. It just points to the memory location of the script that you have assigned to the variable.
This is correct. Script components are passed by reference, not by value. Dragging a script into a public variable of a gameobject, or storing a reference via GetComponent does nothing other than create a pointer to the existing copy of that component.
Answer by Graham-Dunnett · Jan 07, 2015 at 09:31 PM
This was also very helpful, thanks. I'm actually mostly excited that it led me to the page on coroutines. Coroutines! So cool!
Your answer
![](https://koobas.hobune.stream/wayback/20220613175838im_/https://answers.unity.com/themes/thub/images/avi.jpg)