Hi !
I am newbie programmer and i am trying to respawn my player “quadrato” after it falls or hit a specific gameObject ! I started with the first problem: i created an empty sprite with a collider2d and so when the player falls it dies ! And it works ! But i want to respawn it in a specific point of the scene , in the simplest way ; this command "Application.LoadLevel(Application.loadedLevel);"it works but i can’t do some checkpoint like in supermario XD And i tried to use "transform.position=new Vector2 (1,1); but it doesn’t nothing.
Can you help me ? I hope the answer in complete and clear !
Here there is my code !
using UnityEngine;
using System.Collections;
public class borderPlayer : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll){
if(coll.gameObject.name=="Quadrato")
{
Destroy ( coll.gameObject);
Application.LoadLevel(Application.loadedLevel);
}
}
// Update is called once per frame
void Update () {
}
}
First Let’s get the concept right, then move to the code.
We want to hide the player 'sprite or renderer" from the scene view so it can’t be seen by the user.
We need to know Where we will want to “spawn” back the player object, let’s call it a SpawnPoint on the scene.
Move & Activate the player object to that SpawnPoint transform position.
Let’s get into the code.
using UnityEngine;
using System.Collections;
public class borderPlayer : MonoBehaviour {
//Create a GameObject on the scene, name it SpawnPoint and put it where do u want to re-spawn your character, then drag it to the "borderPlayer" component, then into the public "SpawnPoint" variable.
public Transform SpawnPoint;
void OnCollisionEnter2D(Collision2D coll){
if(coll.gameObject.name=="Quadrato")
{
//Assuming you are using a Sprite Renderer on your character, lets get it and disable it.
col.GetComponent<SpriteRenderer>().enabled = false;
//While the character is invisible, teleport it to the SpawnPoint position.
coll.gameObject.transform.position = SpawnPoint.position;
//You reload your level, i actually don't quite understand why you are using this.
Application.LoadLevel(Application.loadedLevel);
//Then Enable the Character Sprite right after
col.GetComponent<SpriteRenderer>().enabled = false;
}
}
// Update is called once per frame
void Update () {
}
}
I would recommend some improvements like making a function on a GameManager script that handles the spawn of the character / mobs… after asking for a loadlevel, and keep the “get components” calls minimal by catching them when possible , here i made the " respawn" go instantly, but you could listen for an input on the update and re-enable the character when pressed.