I’m trying to make a 2D side-scrolling space shooter and I made a Player which has 3 lives and is supposed to respawn when it dies until lives = 0.
Here’s my script written in C#, but it’s not working correctly… I’m new to this, can anyone help?
using UnityEngine;
using System.Collections;
public class Death : MonoBehaviour {
public int lives = 3;
public GameObject Player = GameObject.FindGameObjectWithTag("Player");
void OnTriggerEnter2D ( Collider2D col ){
lives--;
if (col.gameObject.tag == "Enemy") {
Destroy(gameObject);
if(lives > 0){
GameObject PlayerClone = (GameObject)Instantiate(Player, new Vector2(0,0), Quaternion.identity);
}
//else RESTART/MENU (i'll write this later)
}
}
}
I assume that this script is added to the player, yes? If so, your issue lies in this part:
if (col.gameObject.tag == "Enemy") {
Destroy(gameObject);
In this line, you’ve destroyed the gameobject that the Death script is attached to. Most likely, what you’d want to do instead is to move [gameobject.transform.position] back to the starting position.
If you’re looking for just a simple way to restart the level altogether, you can call:
You really don’t need to destroy the gameObject when your character is “killed” just use renderer.enabled = false, then renderer.enabled = true to respawn it.
With that said, the way you have it set up, you won’t even see it disappear. Try this:
void OnTriggerEnter2D ( Collider2D col ){
lives--;
if (col.gameObject.tag == "Enemy") {
if (lives > 0) {
StartCoroutine (Dead ());
}
}
IEnumerator Dead() {
Debug.Log ("dead");
renderer.enabled = false;
yield return new WaitForSeconds(5);
Debug.Log ("respawn");
renderer.enabled = true;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D collision){
if (collision.gameObject.name "End") {
Destroy(gameObject);
}
}
//player respawn
if (gameObject Destroy){
current.transformation.position new vector3(10, 0, 300);
}
But now it doesn’t seem to work. It tells me there is a parsing error on line 24, and that “End” is an unknown entity. Can anyone help me?