how can I add the value of the same variable from different instances of a GameObject?

Hello,

I am a begginner with Unity and I need to do the following things: (I’m using JavaScript)

I have a GameObject that is instantiated at runtime every some seconds using InvokeRepeating. Each of these objects will be destroyed at a different time, depending on the user’s actions.

I need to do the following: to calculate the average time at which the GameObjects are destroyed.

The GameObject has an script attached with a private float variable that is a timer; its value is 0.0 at the moment of being instanced and it counts forward until the object is destroyed.

So I imagine I need to create a new variable in an independent object in the scene, in which I will add the value of all timers, and that it won’t substract the value when the object is destroyed; and then I’ll divide it between the number of instances created, etc. But, how can I add these values? Is it necessary maybe to use arrays? As the GameObject doesn’t really exist in the hyerarchy until the game is built, I don’t know how to access its variables; and using the Find By Name function didn’t give me proper results.

I don’t really know how to attack this problem and I’ll be grateful for any help you might provide me; please let me know if you need more information.

Thank you very much!

Hey there!

So, there are two ways to get information from an instantiated gameobject. You can keep track of it in a list or an array when it’s instantiated. Then, even if all the objects have the same name, you can access them later by comparing the gameobjects themselves (and not the names of the gameobjects. This works because although gameobjects may have the same name, they have different internally assigned GUIDs. You can also go through all the gameobjects in the scene with a certain name, one by one, and check to see if they are the one you are looking for, Then you get the information from the correct object that way. Obviously, the first method is more efficient, since you don’t have to go hunting for all the objects with x in common every time you want to find some bit of information – they’re right there in your list.

Now then – to access another object in javascript, you just need a reference to the gameobject that that script is on. Then you use the code here:

http://docs.unity3d.com/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

Basically, though the concept is the same as when you use myObject.transform.position – position is really just a variable on a script on that object that you can’t open up using your script editor.

Get it? You’ll probably have to study some array examples…search around for them on here and you’ll find lots!

S