namespace Zinnia.Extension { using System; using UnityEngine; /// /// Extended methods for . /// public static class BehaviourExtensions { /// /// The active state of a GameObject. /// public enum GameObjectActivity { /// /// The GameObject active state is of no interest. /// None, /// /// The GameObject itself needs to be active, the state of parent GameObjects is ignored. /// Self, /// /// The GameObject is active in the scene because it is active itself and all parent GameObjects are, too. /// InHierarchy } /// /// Executes the given when the becomes active and enabled or immediately runs if the is already active and enabled. /// /// The to check against. /// The to execute. public static void RunWhenActiveAndEnabled(this Behaviour behaviour, Action action) { void OnBeforeRender() { if (behaviour == null) { Application.onBeforeRender -= OnBeforeRender; return; } if (!behaviour.CheckIsActiveAndEnabled()) { return; } Application.onBeforeRender -= OnBeforeRender; action(); } if (behaviour.CheckIsActiveAndEnabled()) { action(); return; } Application.onBeforeRender += OnBeforeRender; } /// /// Indicates if the is considered valid if the active scene state of the containing and the component enabled state are matched. /// /// The to check against. /// The required active state of the that the component the method is on is added to. /// The required state of the . /// Whether the state is valid. public static bool IsValidState(this Behaviour behaviour, GameObjectActivity gameObjectActivity = GameObjectActivity.InHierarchy, bool behaviourNeedsToBeEnabled = true) { return (!behaviourNeedsToBeEnabled || behaviour.enabled) && ((gameObjectActivity & GameObjectActivity.None) != 0 || ((gameObjectActivity & GameObjectActivity.Self) != 0 && behaviour.gameObject.activeSelf) || ((gameObjectActivity & GameObjectActivity.InHierarchy) != 0 && behaviour.gameObject.activeInHierarchy)); } /// /// Whether the property member state methods are allowed to run. /// /// The to check against. /// Whether the member change method is allowed to run. public static bool IsMemberChangeAllowed(this Behaviour behaviour) { return Application.isPlaying && behaviour.CheckIsActiveAndEnabled(); } /// /// Checks to see if the behaviour is active in the hierarchy and whether it's enabled. /// /// /// This is a replacement for as that does not always return the expected result. /// /// The to check against. /// Whether the gameobject is active and the behaviour is enabled. public static bool CheckIsActiveAndEnabled(this Behaviour behaviour) { #if ZINNIA_USE_ISACTIVEANDENABLED return behaviour.isActiveAndEnabled; #else return behaviour.gameObject.activeInHierarchy && behaviour.enabled; #endif } } }