I’ve run into a bit of a problem with a game I’m working on. GameObjects tend to have a large number of variables that are easily accessed via the object itself, from TAG to TRANSFORM. I have a series of objects to which I need to attach a series of variables that constantly change during gameplay. More importantly, I need to access these objects at any time during said gameplay, and I have noticed to my frustration that constantly having to use GetComponent() slows down the entire game. Is there any way I can create a variable or use some sort of natural component so that I can simply grab what I need via the game object alone instead of having to deal with GetComponent() all the time?
To further clarify, constantly using GetComponent() is the equivalent of doing this:
gameObject.GetComponent(Transform).position
What I want to do is this:
gameObject.transform.position
The simplest way I found to transfer variables from any script to any other script, without depending on compile order or any of that mess, are empty GameObjects (for Boole variables), which I think you are also doing here. For example (JS):
private var MyBooleEmptyGameObject : GameObject;
private var BoolInThisScript = false;
function Start ()
{
MyBooleEmptyGameObject = GameObject.Find ("/Variables/MyBooleEmptyGameObject");
if (MyBooleEmptyGameObject.transform.localPosition.y > 0.5)
{
BoolInThisScript = true;
}
else
{
BoolInThisScript = false;
}
}
Of course, you don’t have to use ANOTHER Boole in the script, but that is just for this examples sake. I usually keep all my Empty GameObject variables under another Empty GameObject called “Variables”, to keep things neat. I also use the 0.5 Y position as the threshold between true and false, as sometimes in Unity GameObjects MAY change their position by 0.000000001 So using > 0.5 or < 0.5 is the safe bet.
The same process can be done with string, int or float.