Common way to check flags of different scripts.

It is just a common question. I have some scripts attached to GameObjects. Such scripts have specials flags like “isMoving = true/false”. Well, when I want to get access to flag, I run search of GameObject, then GetComponent(script). And then get value of script.isMoving. Are there some other ways to get value of such flags?

Thanks.

What you call flags are basically variables of type boolean (bool in C#).

Find methods such as GameObject.Find(), Transform.Find() or FindObjectOfType() are costly. You should cache references to your script for better performance.

For instance, let’s say I have a game manager (script named GameManager). This manager could have an array of managed object that is set in the editor or set once during Start() method of the manager. During Update(), you won’t need to find the objects but rather use the cached references directly.

So basically, if all of your managed objects shared the same script (which I call Managed here):

public class GameManager : MonoBehaviour
{
    public Managed[] managedObjects;

    void Start()
    {
        // Find them if not set already in the editor
        this.managedObjects = FindObjectsOfType(typeof(Managed)) as Managed[];
    }

    void Update()
    {
        foreach( Managed managed in this.managedObjects )
        {
            if( managed )
            {
                // do something
            }
        }
    }
}

If not, just keep a reference to the GameObject and use GetComponent:

public class GameManager : MonoBehaviour
{
    public GameObject[] managedObjects;

    void Update()
    {
        foreach( GameObject go in this.managedObjects )
        {
            Managed managed = go.GetComponent<Managed>();
            if( managed )
            {
                // do something
            }
        }
    }
}