The code after WaitForSeconds isn't working!
I am making a script where an object should disappear after 2 seconds and when it does it sets a bool named "canDraw" to false and then after 1 second it should set the bool back to true but for some reason it never sets it back to true! I have been trying to figure out what i've been doing wrong for a while now and still can't figure it out :( Please help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dissapear : MonoBehaviour {
public static bool canDraw = true;
public GameObject objectToActivate;
private void Start()
{
StartCoroutine(ActivationRoutine());
}
private IEnumerator ActivationRoutine()
{
yield return new WaitForSeconds(2);
objectToActivate.SetActive(false);
canDraw = false;
yield return new WaitForSeconds(1);
canDraw = true;
}
public void Update()
{
if (canDraw == false)
{
objectToActivate.SetActive(false);
}else
{
objectToActivate.SetActive(true);
}
}
}
Are you sure objectToActivate
isn't the object holding the script? Disabling the gameobject will stop the coroutine.
The the script is on the "objectToActivate" script. How did I not think of that! Thank you! Also how would I go about changing it so that I can do this while having it on a separate game object?
You should put this script on an empty gameobject and drag & drop the initial object in the objectToActivate
field.
Answer by ActiveTech · Jan 20, 2018 at 08:54 PM
Try
void Start()
{
StartCoroutine(ActivationRoutine());
}
And
IEnumerator ActivationRoutine()
{
yield return new WaitForSeconds(2);
objectToActivate.SetActive(false);
canDraw = false;
yield return new WaitForSeconds(1);
canDraw = true;
}
Hmmm... I tried this and I still got the same result. I also tested it to make sure that it was something wrong with the IEnumerator and not, for example, the if statement and I found that that is the case. I have gone over this many times and I am still stumped. If you have any other ideas please help!
*Just to clarify it is something wrong with the IEnumerator.