- Home /
Retrieving a variable from ALL scripts on a Game Object
Hello,
I'm attaching one generic script to several Game Objects - all of which have to retrieve a variable from a script that's not generic and unique only to them. Manually listing each script that I'm going to be using through GetComponent is pretty janky - is there a way that I can, for example, list all Scripts that are attached on a Game Object in an array, and then use a for loop to try to pull out a var? Other methods are welcome as well.
Answer by whydoidoit · Jun 26, 2012 at 12:57 AM
I can think of two ways:
Define a base class that inherits from MonoBehaviour and has your variable in it, then you can get all of those instances quickly. I could give you an example if I knew what language you were writing in. You then derive your non-generic scripts from this base class. You can then also do GetComponents(YourBaseClass) to get the list.
Use Reflection to find the variable and then get the value. This method is slower and should only be used in initialization code.
As an alternative to creating a base class, you can declare an interface and make your script implement it.
Note that in this case, you cannot declare a variable but must use C# property mechanism.
An example (written freehand, but should compile) -
[Triggerable.js]
class Triggerable extends $$anonymous$$onoBehaviour {
var on : boolean;
function Trigger() { return; } // I forget if return is necessary...
}
[Lamp.js] - Overrides the base class (triggerable), and has access to its variables
class Lamp extends Triggerable {
var light : Light;
function Trigger() { on = !on; light.enabled = on; }
}
[Other thing] - Looks for triggerables; extending classes can choose what they want 'trigger' to mean, and they all have 'on' available to see
var trigs : Triggerable[];
...
for ( var t : Triggerable in trigs ) {
if ( t.on ) t.Trigger();
}
var obs : GameObject[];
...
for ( var o : GameObject in obs ) {
var t : Triggerable = o.GetComponent(Triggerable);
if ( t && t.on ) t.Trigger();
}
I see what you mean - keeping it all within one class and then extending it in other scripts assigned to the Game Object. However that would mean that all of my scripts would have to be within a class - currently the code is procedural and does not use classes. To avoid having to backtrack, is it advisable to write everything within classes?
Yeah, you'd have to put class wrappers in all those scripts, but that's not a bad idea. This is (one reason) why object-oriented program$$anonymous$$g was invented. If you get in the habit, it makes things easier as you go.