Can you flicker a game object with SetActive?

Hi, i am able to create a coroutine that flickers a component using a script like this:

using UnityEngine;
using System.Collections;

public class Lumiereflash : MonoBehaviour
{

    Light lumiere;
    public float tempsmin;
    public float tempsmax;

    void Start()
    {
        lumiere = GetComponent<Light>();
        StartCoroutine(Flashing());
    }

    IEnumerator Flashing()
    {
        while (true)
        {
            yield return new WaitForSeconds(Random.Range(tempsmin, tempsmax));
            lumiere.enabled = !lumiere.enabled;
        }
    }
}

My question is: can you do the same thing with a game object?

Should i use something like gameobject.SetActive(true)=gameobject.SetActive(false) ?? My first tries do not work?

Thanks in advance for your help

Steps to success:

  • keep track of your own boolean
  • toggle it when you want it to change
  • use it to call .SetActive(myOwnBoolean);

Otherwise the closest analogy to a readable active might be .activeSelf or .activeInHierarchy, but neither is a precise 1-to-1 match, which is why I suggest your own boolean.

Notice that this flag is what keeps track of the state.
Replace this flag with a flag of your own (thus a boolean variable as Kurt said).
Pass this value to SetActive.

Also watch out for disabling the object that the coroutine is running on. That stops the coroutine.

1 Like

Recommend not to use SetActive, that turns everything on and off. Just enable/disable the renderer, which makes it visible/invisible. You can do this to the collider too if needed. If there’s a Rigidbody the parallel command (sort of) is isKinematic, there’s no direct enabled/disabled for these afaik.

It does make sense to do this, but I’d warn against the idea that this somehow is preferred over the other more general solution, because toggling the renderer on and off is very specific and situational.

That’s like saying “To turn your engine off, you don’t have to turn the key at all, the recommended way is to open the hood and unplug the electric cables. This will prevent the spark plugs from firing off, and the engine will cease to function.”

This is true. But not really a recommended way.

True, I was mainly cautioning against the possible issues with the GO itself being inactive (like script functionality). Different situations will call for different solutions for sure.