Question by
Rosebud098 · Mar 16 at 04:27 PM ·
scene-switchingdonotdestroyhealth
Player health keeps regenerating when moving to a new level
So im currently working on a 2d game for my level design class and i have figured out how to get the player to collide with a trigger to change scenes but my health bar for the character keeps resetting to max health at the beginning of a level. I know this has to do something with implementing a do not destroy method but im still new to unity so im not sure how to implement it with my health script for the player. Any advice is welcomed. below is my script for the players health.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class PlayerHealth : MonoBehaviour { [Header ("Health")] public float maxHealth = 10; public float currentHealth; public bool alive = true;
public Animator anim;
[Header("iFrames")]
[SerializeField] private float iFramesDuration;
[SerializeField] private int numberOfFlashes;
private SpriteRenderer spriteRend;
// Start is called before the first frame update
void Start()
{
alive = true;
currentHealth = maxHealth;
spriteRend = GetComponent<SpriteRenderer>();
}
public void TakeDamage(int amount)
{
currentHealth -= amount;
if (!alive)
{
return;
}
if (currentHealth > 0)
{
anim.SetTrigger("player damage");
StartCoroutine(Invuneralbility());
}
if(currentHealth <= 0)
{
// we are dead
anim.SetTrigger("player die");
alive = false;
GetComponent<PlayerController>().enabled = false;
// game.Object.SetActive (false); to destroy player
//SceneManager.LoadScene(7);
// load gameover screen^^^
}
else
{
}
}
public void Heal(int amount)
{
//Play sound here
currentHealth += amount;
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
}
private IEnumerator Invuneralbility()
{
Physics2D.IgnoreLayerCollision(10, 11, true);
for (int i = 0; i < numberOfFlashes; i++)
{
spriteRend.color = new Color(1, 0, 0, 0.5f);
yield return new WaitForSeconds(iFramesDuration/(numberOfFlashes * 2));
spriteRend.color = Color.white;
yield return new WaitForSeconds(iFramesDuration / (numberOfFlashes * 2));
}
Physics2D.IgnoreLayerCollision(10, 11, false);
}
}
Comment