Reputation: 211
I want to re-spawn my player back to where he started at the beginning of the game without destroy any object and ending the game after impact with an object. My player has three hearts before he dies. When my player lose a heart (after collision with a tag object), I want to re-spawn my player back to where he started at the beginning of the game.
This is my player's health code:
public class PlayerHealth : MonoBehaviour {
//Stats
public int curHealth;
public int maxHealth = 3;
void Start ()
{
curHealth = maxHealth;
}
void Update ()
{
if (curHealth > maxHealth) {
curHealth = maxHealth;
}
if (curHealth <= 0) {
Die ();
}
}
void Die ()
{
//Restart
Application.LoadLevel (Application.loadedLevel);
}
public void Damage(int dmg)
{
curHealth -= dmg;
}
}
And this script is used on my object to damage him (take away he's heart)
public class Damage : MonoBehaviour {
private PlayerHealth player;
void Start ()
{
player = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerHealth> ();
}
void OnTriggerEnter2D (Collider2D other)
{
if (other.CompareTag ("Player"))
{
player.Damage(1);
}
}
}
Thank you, So in general I want to respawn my player back to where he started in the beginning of the game after collision with my object, I don't want the game to restart after losing a heart I want to continue until all hearts are lost, that's when the game restarts.
Upvotes: 0
Views: 3245
Reputation: 10720
You need to restore starting position of player at start and then reset it when ever it gets damage. Try something like this in your Player's Health script:
Vector3 startPosition;
void Start ()
{
curHealth = maxHealth;
startPosition = transform.position;
}
public void Damage(int dmg)
{
curHealth -= dmg;
Reset();
}
void Reset()
{
transform.position = startPosition;
}
I hope it helps
Upvotes: 1
Reputation: 991
The easiest way I can imagine at the moment is to create an empty GameObject and place it where you want your player to spawn. Then, when the player gets hit and you want him to respawn, you can do in a respawn() method :
player.transform = yourEmptyGameObject.transform;
That will assign the empty gameObject position to your player. Just be careful that the empty object isn't in the ground, or your player might get stuck.
Upvotes: 1