Skip to content

Commit d5ce165

Browse files
committed
Made ClientKit a persistent singleton to avoid multiple instances when switching to a scene with a ClientKit.
1 parent b54e7d8 commit d5ce165

1 file changed

Lines changed: 26 additions & 6 deletions

File tree

OSVR-Unity/Assets/OSVRUnity/src/ClientKit.cs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ public class ClientKit : MonoBehaviour
3030
public string AppID;
3131

3232
private OSVR.ClientKit.ClientContext contextObject;
33+
private static ClientKit _instance;
3334

3435
/// <summary>
3536
/// Use to access the single instance of this object/script in your game.
@@ -39,13 +40,19 @@ public static ClientKit instance
3940
{
4041
get
4142
{
42-
ClientKit candidate = GameObject.FindObjectOfType<ClientKit>();
43-
if (null == candidate)
43+
if(_instance == null)
4444
{
45-
Debug.LogError("OSVR Error: You need the ClientKit prefab in your game!!");
45+
_instance = GameObject.FindObjectOfType<ClientKit>();
46+
if (_instance == null)
47+
{
48+
Debug.LogError("OSVR Error: You need the ClientKit prefab in your game!!");
49+
}
50+
else
51+
{
52+
DontDestroyOnLoad(_instance.gameObject);
53+
}
4654
}
47-
return candidate;
48-
55+
return _instance;
4956
}
5057
}
5158

@@ -78,7 +85,20 @@ private void EnsureStarted()
7885
void Awake()
7986
{
8087
DLLSearchPathFixer.fix();
81-
DontDestroyOnLoad(gameObject);
88+
//if an instance of this singleton does not exist, set the instance to this object and make it persist
89+
if(_instance == null)
90+
{
91+
_instance = this;
92+
DontDestroyOnLoad(this);
93+
}
94+
else
95+
{
96+
//if an instance of this singleton already exists, destroy this one
97+
if(_instance != this)
98+
{
99+
Destroy(this.gameObject);
100+
}
101+
}
82102
}
83103
void Start()
84104
{

0 commit comments

Comments
 (0)