Hey all I am new to coding and I am working on a new level I have used this code to show on screen the players health. Is there a way where when the health hits no Health that I respawn at a set location?
any help would be great thanks all in advance
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour
{
GameObject box; //variable collectable box
public float health = 100; // variable for score floated to the screen/publically
//use this for initialization
void start()
{
box = GameObject.FindWithTag("Health");
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Health")
{
health -= 5;
Destroy(other.gameObject);
}
}
void OnGUI()
{
GUI.Label(new Rect(150, 160, 300, 300), "Health : " + (int)health);
}
void Update()
{
}
}
Yes, you can do something like this:
GameObject box; //variable collectable box
//Add a transform for your spawn position
Transform spawn;
//Add height you want to spawn at
public float spawnHeight;
public float health = 100; // variable for score floated to the screen/publically
//Add variable to save the initial health
float savedHealth;
//use this for initialization
void start()
{
//Assign health to saveHealth
saveHealth = health;
//Find the spawn object
spawn = GameObject.Find("Spawn").GetCompnent<Transform>();
box = GameObject.FindWithTag("Health");
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Health")
{
health -= 5;
Destroy(other.gameObject);
}
}
void OnGUI()
{
GUI.Label(new Rect(150, 160, 300, 300), "Health : " + (int)health);
}
void Update()
{
//Check if health is zero
if(health<=0){
Vector3 pos = new Vector3(spawn.position.x,spawn.position.y,spawn.position.z);
pos.y = spawn.position.y + spawnHeight;
transform.position = pos;
//Reset Health
heath = saveHealth;
}
}
}
Tell me if this works. I am not at my computer so I can’t test it myself.
Note: Make a gameObject in the editor and name it Spawn or whatever you say it is in, spawn = GameObject.Find(“[insert your gameobject name]”).GetComponent();
Sorry for the slow reply been busy with College work