Flashing GameObject in Unity

12,791

Solution 1

Use InvokeRepeating:

public GameObject flashing_Label;

public float interval;

void Start()
{
    InvokeRepeating("FlashLabel", 0, interval);
}

void FlashLabel()
{
   if(flashing_Label.activeSelf)
      flashing_Label.SetActive(false);
   else
      flashing_Label.SetActive(true);
}

Solution 2

Take a look on unity WaitForSeconds function.

By passing int param. (seconds), you can toggle your gameObject.

bool fadeIn = true;

IEnumerator Toggler()
{
    yield return new WaitForSeconds(1);
    fadeIn = !fadeIn;
}

then call this function by StartCoroutine(Toggler()).

Solution 3

You can use the Coroutines and new Unity 4.6 GUI to achieve this very easily. Check this article here which falsges a Text. YOu can modify it easily for gameobject easily

Blinking Text - TGC

If you just need the code, here you go

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class FlashingTextScript : MonoBehaviour {
Text flashingText;
void Start(){
//get the Text component
flashingText = GetComponent<Text>();
//Call coroutine BlinkText on Start
StartCoroutine(BlinkText());
}
//function to blink the text
public IEnumerator BlinkText(){
//blink it forever. You can set a terminating condition depending upon your requirement
while(true){
//set the Text's text to blank
flashingText.text= "";
//display blank text for 0.5 seconds
yield return new WaitForSeconds(.5f);
//display “I AM FLASHING TEXT” for the next 0.5 seconds
flashingText.text= "I AM FLASHING TEXT!";
yield return new WaitForSeconds(.5f);
}
}
}

P.S: Even though it seems to be an infinite loop which is generally considered as a bad programming practice, in this case it works quite well as the MonoBehaviour will be destroyed once the object is destroyed. Also, if you dont need it to flash forever, you can add a terminating condition based on your requirements.

Share:
12,791
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    Admin almost 2 years

    How can I create a flashing object in Unity using SetActiveRecursively (Moment = 1 second).

    My example (for changes):

    public GameObject flashing_Label;
    private float timer;
    
    void Update()
    {
        while(true)
        {
            flashing_Label.SetActiveRecursively(true);
            timer = Time.deltaTime;
    
            if(timer > 1)       
            {
                flashing_Label.SetActiveRecursively(false);
                timer = 0;        
            }   
        }
    }