|
Hi, I've got a few GameObjects with the same script in my scene. I'm trying to get the values from variables in that script and add them together. I don't really know how to accomplish this. Any suggestions?
(comments are locked)
|
|
Well there are two methods. In the first your script adds a reference to itself to a static list of scripts in OnEnable and removes itself in OnDisable. Then you have an list of all of the scripts so its easy to work through them. The other method involves using GameObject.FindObjectsOfType(typeof(GameObject)) - (C#) and then working through them getting the component from each if it exists. This method is slow. Here's method 1 in C# I don't really understand the first method. I'm in constant need of those variables, it's a number constantly displayed on the screen. What do the Enable and Disable functions do here?
May 26 '12 at 12:51 PM
Danzou
Well OnEnable is called when the game object is activated and disable when it is deactivated or destroyed. E.g. When a new level is loaded or the object is drstroyed So with method 1 you have an easy way of accessing every instance of your script from anywhere. You also ensure that you are only accessing living objects.
May 26 '12 at 02:42 PM
whydoidoit
Think of OnEnable like Start but called each time the object is activated. It is obviously activated when it is instantiated or the game starts. After that it will only be called when the object is disabled (using active=false on the game object or enabled on the script) and the reenabled (active=true on game object or enabled on the script)
May 26 '12 at 02:50 PM
whydoidoit
You could also use Start and OnDestroy if you prefer.
May 26 '12 at 02:52 PM
whydoidoit
If you mean there is a variable on the script called myVariable, that it is public and you want something else to add them up then, also presuming that variable is a float, where you want to add it up you do this:
May 26 '12 at 06:43 PM
whydoidoit
(comments are locked)
|
|
I found a method that, may be is not the most elegant, but it saves my day: On the main script I created a variable, lets say "flag" and I set it to false. When I want to change the variables from all objects, I just change the value of flag to true. In the object script, I just add a line to the Update function... if(OtherScript.flag == true) { ... } and that's it. Heh if it works for you then fine. This kind of code can prove to be fragile however and hard to debug. I'd prefer a method of directly affecting the other scripts. For instance what sets that flag false and when? Is it possible that it will become false before all of the scripts have updated or perhaps some of the will update many times.
May 26 '12 at 02:45 PM
whydoidoit
(comments are locked)
|
