Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- // @kurtdekkker
- //
- // A generic way to set up a checker in Unity3D that will live
- // on another GameObject and periodically check a condition.
- //
- // When that condition returns true, this does an action and
- // destroys itself.
- //
- // A prime use of this is to reactivate an inactive GameObject.
- // Inactive GameObjects will not have scripts run, so this must
- // live on another GameObject entirely, and the Create() method
- // takes care of this.
- //
- // Example use, to resurrect a fallen enemy:
- //
- // // when you kill the enemy:
- // EnemyGameObject.SetActive(false);
- // // to make the enemy reappear:
- // CheckConditionAndPerformAction.Create(
- // () => { return TimeToResurrectThisEnemyYet( EnemyGameObject); },
- // () => { EnemyGameObject.SetActive(true); }
- // );
- // // in the above example you must provide a TimeToResurrectThisEnemyYet(GameObject)
- // // method that knows when this enemy is due to reappear.
- //
- // Example use, to give a one-time extra life when you reach 1000 points:
- //
- // CheckConditionAndPerformAction.Create(
- // () => { return UserScore >= 1000; }, // condition to check
- // () => { PlayerLifeCounter++; }, // what we do when condition is true
- // 0.1f); // how often we check (seconds interval)
- public class CheckConditionAndPerformAction : MonoBehaviour
- {
- System.Func<bool> ConditionToCheck;
- System.Action ActionToPerform;
- float CheckingInterval;
- public static CheckConditionAndPerformAction Create(
- System.Func<bool> ConditionToCheck,
- System.Action ActionToPerform,
- float CheckingInterval = 0)
- {
- var go = new GameObject("CheckConditionAndPerformAction.Create();");
- var checker = go.AddComponent<CheckConditionAndPerformAction>();
- checker.ConditionToCheck = ConditionToCheck;
- checker.ActionToPerform = ActionToPerform;
- checker.CheckingInterval = CheckingInterval;
- return checker;
- }
- float age;
- private void Update()
- {
- age += Time.deltaTime;
- if (age >= CheckingInterval)
- {
- age -= CheckingInterval;
- if (ConditionToCheck())
- {
- ActionToPerform();
- Destroy(gameObject);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement