- Home /
 
 
               Question by 
               MsLuSomebody · Oct 23, 2020 at 04:31 PM · 
                playerrespawnhealth  
              
 
              Respawn Player after Health 0
Hi, I have a problem. I'm new in Unity and want my Player to respawn at the start after his health is 0 but i dont realy know how to do this. I hope u can help me.
My Script: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class Player : MonoBehaviour { public int maxHealth = 100; public int currentHealth; public HealthBar healthBar; public int Respawn;
 private void Start()
 {
     currentHealth = maxHealth;
     healthBar.SetMaxHealth(maxHealth);
 }
 private void OnTriggerEnter2D(Collider2D collision)
 {
     if (collision.gameObject.CompareTag("Spike"))
     {
         TakeDamage(20);
     }
 }
 void TakeDamage(int damage)
 {
     currentHealth -= damage;
     healthBar.SetHealth(currentHealth);
 }
 
               }
and my Script for the HealthBar:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class HealthBar : MonoBehaviour { public Slider slider; public Gradient gradient; public Image fill;
 public int fillAmount { get; internal set; }
 public void SetMaxHealth(int health)
 {
     slider.maxValue = health;
     slider.value = health;
     fill.color = gradient.Evaluate(1f);
 }
 public void SetHealth(int health)
 {
     slider.value = health;
     fill.color = gradient.Evaluate(slider.normalizedValue);
 }
 
               }
               Comment
              
 
               
              Answer by andzq · Oct 23, 2020 at 09:02 PM
  void TakeDamage(int damage)
  {
      currentHealth -= damage;
      healthBar.SetHealth(currentHealth);
      if(currentHealth <= 0)
      {
        Respawn();
      }
  }
  void Respawn()
  {
      // reload scene
      // or other respawn mechanic
  }
 
              Your answer