Unity 3D: Flash an Object

3/4/2020 5:12:43 PM

Flash a Unity object.


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

public class Flash_Object : MonoBehaviour
{    
    public bool Flash = true;
    public float Flashes_Per_Second = 2;

    float Fixed_Update_Counter = 0f;

    //used fixed update since this function is called on a standard interval
    //.02 is default fixed update time
    void FixedUpdate()
    {
        //Debug.Log("Flash_Object: FixedUpdate");

        if (this.Flash == false)
        {
            this.Fixed_Update_Counter = 0;
            return;
        }


        //how many times has this function been called
        this.Fixed_Update_Counter++;


        //fixed update defaults to being called every .02 seconds
        //how many functions calls are needed to flash this object based on the Flashes_Per_Second value        
        var function_calls_needed = (1f / this.Flashes_Per_Second) / Time.fixedDeltaTime;


        //if the function has been called enough times, flash the object
        if (this.Fixed_Update_Counter >= function_calls_needed)
        {
            //get the renderer
            var renderer = this.GetComponent();            
            if (renderer == null)
            {
                renderer = this.GetComponentInChildren();                
            }
            if (renderer == null)
            {                
                return;
            }


            //flip the renderers enabled value
            renderer.enabled = !renderer.enabled;


            //reset the counter
            this.Fixed_Update_Counter = 0;
        }        
    }
}