I am trying to get particles to stay alive instead of restarting between scenes, but this script is not working if anyone has any ideas I would really appreciate it.
This is my script:
void Awake()
{
bool created = false;
if (!created)
{
DontDestroyOnLoad(this.gameObject);
created = true; // which runs "else" statement exactly the next frame )))
}
else
{
Destroy(this.gameObject);
}
}
}
I figured it out. Instead of having it in every scene with different programming, I can just use this by default on the opening scene, or scene 0, and it runs it through everything which is what I needed for my game. Probably would not work for others though, because it stacks on top of itself for some reason.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestroy : MonoBehaviour
{
DontDestroy instance = null;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
GameObject.DontDestroyOnLoad(gameObject);
}
}
}
It’s stacking because you haven’t marked the instance field as static so every instance of the class has its own copy of the instance field rather than all of them sharing the same field. Here’s my singleton pattern for when I need to manually add it to the scene. Though I very rarely use this one now.
public class Singleton : MonoBehaviour
{
private static Singleton _Instance;
public static Singleton Instance => _Instance;
private void Awake()
{
if (_Instance != null)
{
DestroyImmediate(gameObject);
}
else
{
_Instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
Here are links to other variants made by @Kurt-Dekker . Both of these instantiate themselves the first time they are accessed. The first one creates a fresh copy while the second populates itself with a prefab.