Changing player color when hit

Hello everyone I had a quick question I was trying to make my character change colors when they take damage I figured it out however they don’t turn back to the original color I was hoping that someone could give me some pointers or tips on fixing it thank you.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    [SerializeField]
    private Stat health;




    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.

    // Use this for initialization
    void Start()


    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D>();

        health.Initialize();

    }

    // Update is called once per frame
    void FixedUpdate()
    {
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("EnemyH"))
        {
            //doing things
            health.CurrentVal -= 10;

            GetComponent<SpriteRenderer>().color = new Color(1f, 0.30196078f, 0.30196078f);

            GetComponent<SpriteRenderer>().color = new Color(0.388235229f, 0.3372549f, 1f);



        }
        if (health.CurrentVal <= 0) {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

        }
    }
}

GetComponent()- store link only once at start.

the changes only from the last line will be rendered, Unity at first calculates all scripts and then will render the frame.
GetComponent().color = new Color(1f, 0.30196078f, 0.30196078f);
GetComponent().color = new Color(0.388235229f, 0.3372549f, 1f);

try to switch color for some time, then switch it back to default.

bool isHitted = false;
    public float timeToColor;
    SpriteRenderer sr;
    Color defaultColor;

    void Start()
    {
        sr = GetComponent<SpriteRenderer>();
        defaultColor = sr.color;
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (!isHitted)
        {
            isHitted = true;
            StartCoroutine("SwitchColor");
        }
    }

    IEnumerator SwitchColor()
    {
        sr.color = new Color(1f, 0.30196078f, 0.30196078f);
        yield return new WaitForSeconds(timeToColor);
        sr.color = defaultColor;
        isHitted = false;
    }

I have used here a coroutine. The main script will work all time but the IEnumerator SwitchColor() will be paused for: yield return new WaitForSeconds(timeToColor);

4 Likes

Thank you for your help it was right under my nose the whole time you are a God among men.do you have a patreon or something that I can show my gratitude.

Lol :roll_eyes: I am just reading about Unity here too :smile: