I'm trying to write a checkpoint script, which requires use of a singleton, forcing me to work in C# instead of javascript. I know next to nothing about coding in C#, and the Unity documentation for it is frankly awful, so I'm having a hell of a time getting anything to work.
What I want to do is to save a float called checkpoint into the singleton, which can then be accessed and changed by outside javascript scripts. However, I can't get any of it working. Here's the C# code I currently have:
using UnityEngine;
public class MySingleton: MonoBehaviour
{
private static MySingleton instance;
public MySingleton ()
{
if (instance != null)
{
//Debug.Log("Cannot have two instances of singleton. Self destruction in 3...");
return;
}
instance = this;
}
public static MySingleton Instance
{
get
{
if (instance == null)
{
new MySingleton ();
}
return instance;
}
}
public float checkpoint = 0;
void Update(){
Debug.Log(checkpoint);
}
}
However, when it's I die and the level resets, I get the following error:
ArgumentException: CompareBaseObjects can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
If i remove the : Monobehaviour from the 2nd line, I don't get that error, but the Debug.Log line fails to work. No matter which way I have it though, on resetting the level, checkpoint resets to 0, defeating the point of the thing in the first place.
Please help, it's only a few days to my deadline, and I wasn't expecting to have to learn C# all of a sudden >_<.
Thanks