[2D] problem with character persistence and respawn (dontdestroyonload singleton)
Hello everyone, I am a total beginner with Unity 3D so bear with me :)
I am trying to develop a small 2D platformer game. My problem is with my character's respawn. I have a killzone that reloads the level :
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class Restarter : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Application.LoadLevel(Application.loadedLevelName);
}
}
}
}
With this when my character died, the level would reload just fine. But when I added a level 2, of course my character didn't persist. After a few researches I added a JS script on the character with a singleton pattern to keep my character between levels and preventing it from duplicating when respawning Here is my DontDestroyOnLoad js :
static var created = false;
function Awake() {
if (!created) {
// this is the first instance - make it persist
DontDestroyOnLoad(transform.root.gameObject);
created = true;
} else {
// this must be a duplicate from a scene reload - DESTROY!
Destroy(transform.root.gameObject);
}
}
Now if I enter the killzone, in the hierarchy i can see characters objects being created then deleted so that there is only 1 left. That is good, but apparently the level is not reloading and my character keeps falling down.
Does anyone see what I did wrong?
Please tell me if my explanation wasn't clear enough. Any help would be appreciated. Thanks !
Your answer
Follow this Question
Related Questions
Stop Point objects respawning when reloading level 0 Answers
Singleton / DontDestroyOnLoad / Instantiation referencing 0 Answers
dontDestroyOnLoad doesn't work as expected with scene navigation 0 Answers
I am having problems with saving and loading when I go back and forth between scenes. 1 Answer
Player getting stuck when i respawn efter death in 2d 1 Answer