- Home /
Simple Singleton between Design, Play, and Scene Change?
For some reason when switching between design and play modes m_instance wiped. Each time I enter play mode a new DoubleLockingSingletonTest is created. I was hoping to use the singleton in both design and play modes and between scenes.
using UnityEngine;
public class DoubleLockingSingletonTest
{
private static volatile DoubleLockingSingletonTest m_instance;
private static readonly object m_lock = new object();
private DoubleLockingSingletonTest() { }
public static DoubleLockingSingletonTest instance
{
get
{
//double locking Singleton
if (m_instance == null)
{
lock (m_lock)
{
if (m_instance == null)
{
m_instance = new DoubleLockingSingletonTest();
Debug.Log("Test.instance");
}
}
}
return m_instance;
}
}
}
I see m_instance is defined with the volatile qualifier. This means that it is free to be deleted and recreated whenever the environment wishes.
"The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread." http://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.71).aspx
the double locking singleton is from http://msdn.microsoft.com/en-us/library/ff650316.aspx
Wouldn't it be very dangerous to have a singleton persisting between Editor and Game? I mean the real Game would never have the other Singleton created in the Editor. You would be better off serializing the data when you switch from Editor to Game view and recreating it.
$$anonymous$$y singleton is needed to manage native resources of which I need full control over all the time. However, you're trying to answer a question with a question =)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Code explanation - C# 1 Answer
Issues rotating around transform.up 2 Answers
Fixing screen resolution 1 Answer