- Home /
Access and pass variables between multiple scripts
Hi,
this may be a noobish question, but I have tried searching for this problem for 2 days now and Google isn't my friend. Here's my setup:
I'm trying to make a game, where I use a gameobject that go across multiple scenes, that contains variables (both float, bool's, ints etc.)such as lives, coins and so on. I also have gameobject for each scene that holds variables for specific for only the current scene. All set to be public/static.
My problem is, I can't send or receive data from these scripts and use in scripts in my scenes. Etc. I have a script for money, and when the coin collides with player, it won't send either coins +=1; or coins ++; to the main script with coins;
Also I can't fetch bools or floats from the main script either to check and use to alter gameplay.
Please help me. I'm not a programmer by trade, but I have some insight of coding afterall. I use c++ in Unity 4.6
C# maybe!
However, if the gameobjects that you carry from other scenes are single instances, you may write a SINGLETON pattern
http://unitypatterns.com/singletons/
for example, from player script, when collides:
CoinHelper.instance.AddCoins(player)
Answer by hexagonius · Feb 11, 2015 at 05:01 PM
First, you need to make your GameObject that needs to stay alive across scenes persistent. Check this out: Object.DontDestroyOnLoad
Then, you'll need to grab this from the scripts you have in each scene. Since it is a GameObject not known by them since it is coming from another scene, you should search for it:
YourScript reference;
void Start(){
reference = GameObject.Find("TheLivingObject").GetComponent<YourScript>();
}
From this point on you can call methods as you know it on reference.
Answer by Sisco1980 · Feb 11, 2015 at 07:57 PM
I'd swear I've tested this out before, perhaps some similar lines. But 2 days of struggle rectified in 10 minutes of testing. Received and sended an int variable (coins) with succes. Thanks a lot. :)
I'm tired so I'm going to ask anyway - this goes for all variables right? E.g. setting bools to true/false etc. ?
Think of it as the alternative to saving the object from a constructor. Since Unity is usually instantiating GameObjects preset in the scenes for you, you have no other choice than looking for them. But after doing so everything is accessible according to C# accessibility conventions.
Your answer
![](https://koobas.hobune.stream/wayback/20220613183048im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Developing for IOS 1 Answer
Perlin Noise. 1 Answer
Steps to create service tool with unity api 1 Answer
Converting c++ to c# and procedural galaxy generation. 1 Answer
unity3d import c++ dll for pass by reference method 0 Answers