c# help please

i am trying to code a function in a game where the player gets jumped scared by an enemy and the heart rate is raised. what i have so far is just them being close to the enemy and it raises and when they get away from the enemy it decreases. I need a jump in heart rate when the player gets scared. also, this has to be realistic, where the player starts at 80 bpm, and then they get scared and it jumps to maybe 95 bpm. The other thing i want to have some help with is a death function when the players health gets to 250 bpm. or maybe 300 bpm, where they have a heart attack and die from getting scared too much. and finally, i would like to display the heart rate on the screen, i was thinking of using a UI element, but i’m not sure if that’s what i should be using.

here is the code i have so far with comments

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

public class HeartRate : MonoBehaviour {

    public GameObject Player;
    public GameObject Enemy;
    float heartRateBase = 80; // 80 BPM
    float heartRate = 100;

    float safeDistance = 5; // distance away form the enemy where heart rate goes down

    float relaxRate = 0.005f; //  how fast the player recovers
    float stressRate = 0.05f;// The closer the plauer is to the enemy the more it will increase

    void FixedUpdate()
    {
        // Find distance from enemy
        float dist = Vector3.Distance (Player.transform.position, Enemy.transform.position);
       
        // Check to see if player is safe
        if (dist > safeDistance)
        {
            // Decrease player heart Rate
            if (heartRate > heartRateBase)
                heartRate -= relaxRate;
        }
        else
        {
            // Increase the players heart rate depending on how close they are
            float rate = 1 - dist / safeDistance;
            heartRate += stressRate * rate;
        }

    }
}

any help is very much welcomed.

thank you so much,

best,

To add UI, add a game object with a Canvas component, and have it render in the screen space of the camera. You can then add UI components to game objects that are children of that canvas object. You would want a Text object for this purpose, maybe with a Panel behind it as a background.

In your scripts, you can edit the text of the Text component with a reference.

using UnityEngine.UI; 
Text bpmText;

From here you can edit the text display. I’d set the text every tick in Update.

void Update(){
    bpmText.text = "Heart Rate: " + heartRate;
}

For death, I’d make a game over scene that you can switch to.

if(heartRate > 300) SceneManager.LoadScene("DeathScene");

On a separate note, it’s good practice to use distance squared for simple distance comparisons. It is a less expensive calculation to carry out.

float sqrDist = (Enemy.transform.position - Player.transform.position).sqrMagnitude;
if(sqrDist > safeDistance * safeDistance) //...