In my game, I have text that appears (is set active) when a specific object is selected. I want the text to disappear after a few seconds. I was using the Destory.Gameobject function, but the issue is that I want the text to be able to reappear (and redisappear) multiple times, if the user selects it again.
Oh! Ok, I kind of got it working here (no errors).
using UnityEngine;
using System.Collections;
public class DestroyObj : MonoBehaviour {
public GameObject gameObject;
void Start (){
StartCoroutine(RemoveAfterSeconds(2, gameObject));
}
IEnumerator RemoveAfterSeconds (int seconds, GameObject obj){
yield return new WaitForSeconds(2);
obj.SetActive(false);
}
}
It works the first time the object is activated, but not if it is activated again. Any ideas why? And how to get the script to run every time the object is set to active?
Yes. Starting the Coroutine in the Start function will kick it off when the GameObject is first initialised. You could maybe try changing Start to Awake or OnEnable. Which would restart the coroutine every time the game object is awoken. Or alternatively, put it in a different, public method, which you can then call elsewhere to start the coroutine.
So for instance, you may have a GameObject called RemoveMe. You would attach your DestroyObj script to your RemoveMe gameObject in the editor. DestroyObj would then look like this:
using UnityEngine;
public class DestroyObj : MonoBehaviour {
public void ActivateMe (){
gameObject.SetActive (true);
}
public void DeactivateMe (){
StartCoroutine(RemoveAfterSeconds(2));
}
IEnumerator RemoveAfterSeconds (int seconds){
yield return new WaitForSeconds(seconds);
gameObject.SetActive(false);
}
}
Note how you do not need to store a reference to gameObject, because MonoBehaviour already has a gameObject reference stored for you.
Ok… so now, let’s say you have Instantiated this RemoveMe Object through code in some other script, like this…
using UnityEngine;
using System.Collections;
public class SomeOtherGameLogicScript : MonoBehaviour {
// You would drag your RemoveMe Object's prefab into this field in the editor
// So you can create an instance of it in code
public GameObject My_RemoveMe_Prefab;
// Store reference to the particular instance
GameObject removeMe;
void Start ()
{
removeMe = Instantiate (My_RemoveMe_Prefab, Vector3.zero, Quaternion.identity) as GameObject;
}
// ... A bunch of game logic could go here.
// then when you're ready to show/hide your RemoveMe object, you would call this method...
// Obviously you would only call either DeactivateMe OR ActivateMe below, not both
void someOtherMethod()
{
// Hide your removeMe Object
removeMe.DeactivateMe ();
// Show your removeMe Object
removeMe.ActivateMe ();
}
}
I’ve had a long day, so I hope this is making sense and you are following me