and attached it to enemy. But when Player collides with enemy, enemy gets created
twice with one in his current pos and the other in his starting pos which exits Playmode.
So my question is can someone please help me create a script the contains all these?
Thanks in advance!
There are probably other ways to reset your level than to reload the whole thing, but if you want to do that and keep dynamic elements from the previous instance:
Call OnDestroyOnLoad() on the objects you want to keep, like you are already doing. This is working as intended, because it just tells the engine to keep this object when a new scene is loaded. That way you end up with another enemy on each load.
To avoid the enemies to multiply, you need to discard additional instances. Normally you would do that by using a singleton pattern in which you assign your instance to a static member variable and immediately destroy any additional object in the awake method if it is not the first one (instance variable already set) or otherwise assign this instance to the variable.
In this case this does not seem like a good way, because you will probably have many objects with the same script, so you should instead create a global variable in one of your singleton scripts that tells the game objects that the current scene is a reload and not a fresh level. In the following example I just added it to the enemy script, because I don’t know what other scripts you have.
public class EnemyScript : MonoBehaviour {
public static bool sceneReloaded;
void Awake() { // in every dynamic object that you want to keep
if (sceneReloaded) {
DestroyObject(gameObject);
return;
}
DontDestroyOnLoad(gamObject);
}
}
// your collision reset thingy
void OnTriggerEnter2D(Collider2D other) {
EnemyScript.sceneReloaded = true;
Application.LoadLevel("level_x");
}
And finally, wherever you switch to the new level or restart the game:
EnemyScript.sceneReloaded = false;
// restart game/load new level here