Blink GameObject in Unity

In this article, I am going to share a utility method that will help you to Blink GameObject in Unity 3d or 2d. In this method, it’s supposed that the SpriteRenderer component is attached to your game object. Just copy and paste the following method in your class. Its usage is explained later.

Utility Method to Blink GameObject in Unity C#

public IEnumerator BlinkGameObject(GameObject gameObject, int numBlinks, float seconds)
    {
        // In this method it is assumed that your game object has a SpriteRenderer component attached to it
        SpriteRenderer renderer = gameObject.GetComponent<SpriteRenderer>();
        // disable animation if any animation is attached to the game object
  //      Animator animator = gameObject.GetComponent<Animator>();
  //      animator.enabled = false; // stop animation for a while
        for (int i = 0; i < numBlinks * 2; i++)
        {
            //toggle renderer
            renderer.enabled = !renderer.enabled;
            //wait for a bit
            yield return new WaitForSeconds(seconds);
        }
        //make sure renderer is enabled when we exit
        renderer.enabled = true;
    //    animator.enabled = true; // enable animation again, if it was disabled before
    }

How to Call This Method?

In Your script which is attached to GameObject and the class is extended by MonoBehaviour Class, you can blink the game object by calling the above method in the following way.

StartCoroutine(BlinkGameObject(YOUR_GAMEOBJECT, 5, 10));

Explanation

The above utility method takes 3 parameters. The first parameter is the reference of the GameObject you want to blink. The second parameter is the total number of blinks you want to perform. And the third parameter is the times in seconds for how long you want this game object to blink. As mentioned before, I have supposed that your GameObject already has the SpriteRenderer component.

If your GameObject also has the Animator component, then you need to uncomment the lines in the method related to it. That just disables the animations and after performing blinking operation it enables it again.

That’s it. Enjoy 🙂

Don’t forget to add your questions and opinions in the comments section following below.

Next:

1. UI Object Random Movement in Unity 3D

2. Game Object Zigzag Movement from Top to bottom in Unity

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: