- Home /
Can someone help me with my player kill script?
I am trying to make a script for when i hit a spike my player gets killed and the level gets restarted. I have this for my script. Everything may be changed, it can be that everything is absolutely wrong. Sorry if that is the case...
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerColliderEX : MonoBehaviour { public int maxHealth = 100; public int currentHealth; public HealthBar healthBar; // Start is called before the first frame update void Start() { currentHealth = maxHealth; healthBar.SetMaxHealth(maxHealth); } // This function runs when we hit another object. // We get information about the collision and call it "collisionInfo". void OnCollisionEnter(Collision collisionInfo) { // We check if the object we collided with has a tag called "Obstacle". if (collisionInfo.collider.tag == "Spike") { TakeDamage(20); } } void TakeDamage(int damage) { currentHealth -= damage; healthBar.SetHealth(currentHealth); } }
Right now the script looks fine. Ensure that the Spike GameObjects have the tag "Spike" on them, and test your script. It should decrease your health by 20 when you collide with a spike.
void TakeDamage(int damage)
{
currentHealth -= damage;
if(currentHealth <= 0)
{
currentHealth = maxHealth;
// Restart game
transform.position = spawnPosition;
}
healthBar.SetHealth(currentHealth);
}
With this function, upon reaching 0 or negative currentHealth, the currentHealth variable will refill to maxHealth, and your character will be placed to spawnPosition. Be sure to include this before void Start:
public Vector3 spawnPosition;
and don't forget to give it a value in the Inspector. To restart your level, we would need to know how your character interacts with the level while playing.