Created
July 5, 2021 15:38
-
-
Save kurtdekker/2da840e87e7ff8aa380a8c5680df1395 to your computer and use it in GitHub Desktop.
Delayed activation of GameObjects in Unity3D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using UnityEngine; | |
// @kurtdekker - delayed-activates things in your scene: | |
// To use: | |
// 1. put this script on fresh blank GameObject | |
// - NOT the same one that you are delayed-activating | |
// - NOT a child of the one(s) you are delayed-activating! | |
// - MAY be above other child GameObjects you activate (eg at top of hierarchy) | |
// 2. set the amount of delay in TimeToDelay field | |
// 3. drag the GameObject(s) you want to delay-activate into the TargetsToActivate slot | |
// 4. be sure to disable the GameObject(s) you want to activate later!! | |
// | |
// WARNING: make sure scripts on your target GameObject(s) are happy to be | |
// turned off and then turned back on; this script cannot know that. | |
public class DelayedActivation : MonoBehaviour | |
{ | |
[Header( "How long to wait before delay?")] | |
public float TimeToDelay; | |
[Header( "If you have one thing to activate")] | |
public GameObject TargetToActivate; | |
[Header( "If you have many things to activate")] | |
public GameObject[] TargetsToActivate; | |
void Reset() | |
{ | |
TimeToDelay = 2.0f; // handy default | |
} | |
IEnumerator Start () | |
{ | |
yield return new WaitForSeconds( TimeToDelay); | |
SetActiveHelper( true); | |
} | |
void SetActiveHelper( bool active) | |
{ | |
if (TargetToActivate) | |
{ | |
TargetToActivate.SetActive( active); | |
} | |
if (TargetsToActivate != null) | |
{ | |
foreach( var target in TargetsToActivate) | |
{ | |
if (target) | |
{ | |
target.SetActive( active); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment