1
\$\begingroup\$

For some reason, the update function is only running once. Why does this happen?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LightFlicker : MonoBehaviour
{
    float timer;
    float timetowait;
    // Use this for initialization
    void Start()
    {
        timer = 0;
        timetowait = Random.Range(0.01f, 0.8f);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("Updating");
        timer += Time.deltaTime;
        if(timer >= timetowait)
        {

            if (gameObject.activeInHierarchy == true)
            {
                gameObject.SetActive(false);
            }
            else
            {
               gameObject.SetActive(true);
            }
            timetowait = Random.Range(0.01f, 0.8f);
            timer = 0;
        }
    }
}

The debug.log statement only fires 9 times. The timetowait changes, but the timer stays the same.

\$\endgroup\$
  • \$\begingroup\$ You deactivating your gameObject, so it stop updating. \$\endgroup\$ – Woltus Jun 24 '17 at 13:01
  • \$\begingroup\$ @Woltus so instead of deactivating the gameobject, I deactivate the components? \$\endgroup\$ – DubGamer87 Jun 24 '17 at 13:03
2
\$\begingroup\$

Once the gameobject is no longer active the code will no longer run in the update. You can also simplify the flicker by removing the timer and stuff from the update and replace with a coroutine. Get a reference to the Light and call it like so.

Light _light;
void Start()
{
    _light = GetComponent<Light>();
    StartCoroutine("Flicker");
}
IEnumerator Flicker()
{
    while (true)
    {
        _light.enabled = _light.enabled ? false : true;
        yield return new WaitForSeconds(Random.Range(0.01f, 0.9f));
    }
}

Another option would be to set the light up with a flickering animation loop that you can set whenever needed

\$\endgroup\$
3
\$\begingroup\$

When timer >= timetowait is true, since the game object IS active, you disable it with SetActive(false). And from this point on, Update will never be executed, so you need to re-activate the game object from somewhere else. Or change your code based on what you want to accomplish.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.