Sprite Renderer won't render.

Hi, I’ve recently started learning how to use Unity. I already very familiar with the C# language and have no problems with it.

I’ve created a Script for an Enemy that follows the Player around in a very simple manner and every time it collides with the player, it does a flashing effect that plays for half a second. This flashing effect is nothing more than a object with a white sprite that is connected right above the enemy, and the “animation” is just me messing with the sprite color. The problem is, this “animation” only renders on the scene view; inside the game it simply does not appear.

This is the Script that I’ve created:

using UnityEngine;

public class Enemy : MonoBehaviour
{
    public GameObject target;
    private Vector3 direction;

    public GameObject hitfx;
    private bool isHitfxActive = false;
    private int hitfxCooldownTimer = 0;

    private void HitFX()
    {
        SpriteRenderer renderer = hitfx.GetComponent<SpriteRenderer>();

        if (isHitfxActive)
        {
            hitfxCooldownTimer++;
            if (hitfxCooldownTimer >= 0 && hitfxCooldownTimer < 16)
            {
                float pulse = hitfxCooldownTimer / 15f;
                renderer.color = new Color(1, 1, 1, pulse);
            }
         
            if (hitfxCooldownTimer >= 16)
            {
                float pulse = (30 - hitfxCooldownTimer) / 15f;
                renderer.color = new Color(1, 1, 1, pulse);
            }
         
            if (hitfxCooldownTimer == 30)
            {
                isHitfxActive = false;
                hitfxCooldownTimer = 0;
            }
        }
    }

    void Update()
    {
        HitFX();

        direction = (target.transform.position - transform.position).normalized;
        transform.Translate(direction * 4 / 60);
    }


    public void OnCollisionEnter2D(Collision2D collision)
    {
        isHitfxActive = true;
    }
}

Can someone explain what I’m doing wrong?

Check that your white sprite is explicitly sorted above the regular sprite.

Yes, I’ve checked it. The camera is at z = -10, the player and the enemy at z = 0, and the effect at z = -1.

EDIT: I’ve also noticed that any new game object with a sprite renderer isn’t showing up.

EDIT: Well, it seems to be a problem with the z coordinate but the same time doesn’t …

Keep in mind Z coordinate is ignored with sprites. It pays attention to sorting order and sorting layer.

You can see this by putting two different sprites in scene, one Z-closer than the other, and set the close one to render sorting layer-wise below the upper one, then pan the camera around.

The reason it looks different game vs scene wise is that those are different rendering paths and when the sorting order/layer is the same, the outcome is undefined.