1

I have an enemy and I want it to have a blinking effect (when it gets hit) by changing the alpha.

I'm not doing this using animation due to some other animation already being there. So, I'm changing the alpha of the sprite using a script, but it's not working.

Here's the script:

 private void OnTriggerEnter2D(Collider2D col)
 {
     if (col.gameObject.tag == "Bullet")
     {
         StartCoroutine("Blinker");
     }
 }

 IEnumerator Blinker()
 {
     GameObject This = this.gameObject;

     Color tmp = This.GetComponent<SpriteRenderer>().color;
     Color tmp2 = This.GetComponent<SpriteRenderer>().color;

     tmp.a = 0f;
     tmp2.a = 1;
     This.GetComponent<SpriteRenderer>().color = tmp;
     yield return new WaitForSeconds(sec);
     This.GetComponent<SpriteRenderer>().color = tmp2;
 }

Here's the inspector of the object I'm changing:

enter image description here

11
  • Can you show a screenshot of the inspector properties for the sprite you're changing? Commented Oct 14, 2018 at 15:38
  • What do you mean by "it is not working"? Do the code execute and the effect is not the expected, or it doesn't reach the coroutine? Commented Oct 14, 2018 at 15:43
  • I've added Debug logs and every function is called. The code is meant to fade out the sprite for the duration of the variable 'sec' and then become normal again to give it a blinking look when the player is hit with a bullet. It doesn't happen. There's no blinking even though the courotine is called. It's as if the code changing the alpha doesn't work. Commented Oct 14, 2018 at 15:56
  • 2
    I copy pasted your code into my project and it works fine. I know you have already assured us that the animator is not affecting the color, but please try disabling the Animator component anyways and see if the blinking effect works. Commented Oct 14, 2018 at 16:46
  • 1
    My first guess was that the sprite shader being used didn't support an alpha (that sort of issue is pretty common), but didn't get around to checking it. Good job on Alex checking the animator. Commented Oct 14, 2018 at 17:40

1 Answer 1

2

I copy pasted your code into my project and verified it works as written. The problem must be related to a conflict with one of your animations.

Go through every animation in your enemy animator and ensure SpriteRenderer.color is not present in any of them.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! There was an animation that I wasn't using but was attached to the animator that used color. Thank you so much for this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.