- Home /
Question by
TheEmeraldRuby · May 15, 2018 at 04:52 PM ·
timercountdowndeactivate
GameObjects being deactivated before time runs out for no apparent reason?
Hello, everyone. I have written (copied and modified) a script that tells a GameObject to deactivate itself when the time (defined also in the script) runs out. However, after applying this script to a prefab object and dragging that prefab into the "Coin" slot of the script component, the thing spawns in when I press play, and disappears 2 seconds later. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinCfg : MonoBehaviour {
public int timeLeft = 120;
public GameObject Coin;
void Update () {
transform.Rotate(new Vector3(0, 180, 0) * Time.deltaTime);
StartCoroutine("LoseTime");
if (timeLeft <= 0)
{
StopCoroutine("LoseTime");
Coin.SetActive(false);
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds(1);
timeLeft--;
}
}
}
If anyone could figure out why this happens, I would bee very thankful. Thanks!
Comment
Answer by Captain_Pineapple · May 15, 2018 at 05:11 PM
Hey there,
at first glance i also can't find a problem in your code. A workaround might be to use Invoke("DisableAfterTime",timeLeft);
with the function
public void DisableAfterTime()
{
Coin.setActive(false);
}