How to create a Singleton with Flax Engine
While trying to code the tutorial for the Wolfenstein 3D, we have found ourselves with the need to create a Singleton as to allow a more easy access to certain instances of classes from anywhere in the code.
Based on our previous experience with Singletons we had the idea that it would be something as
public class Player
{
So, we put ourselves to work.
After reviewing the documentation we though that we would need to find the reference to an actor,
So we tried the option Actor.Parent.FindActor<Player>() to try to return a reference to the player type. But it would work and gave us an error, because in the end we wanted to access the Player Class and not the Actor or Object.
By looking into more references and documentation and help in the Discord Channel , we moved to try to use the Level Class https://docs.flaxengine.com/api/FlaxEngine.Level.html
instance = Level.Scenes[0].FindActor<Player>();
But, it didn´t worked, it was still giving us some problems. So, we moved on to
instance = Level.FindActor<Player>();
But unfortunately, we kept on receiving an error.
After another round of asking in the discord server, we ended up by understanding that in Flax a Class is not a Type, but a script, so we moved to try to find a reference to the Script Player.
instance = Level.FindScript<Player>();
And the system stopped reporting an error.
We tried then to access from any other script in the project to Player.MyInstance.Friction (which is a public float) and we were able to access it correctly
The final result to create a singleton in Flax can be
public class Player : Script { private static Player instance; public static Player MyInstance { get{ if (instance == null) { instance = Level.FindScript<Player>(); } return instance; } } }
Or
public class Player: Script
{
private static Player _instance;
public static Player MyInstance
{ get => _instance; }
public override void OnEnable()
{ _instance = this; }
public override void OnDisable()
{ _instance = null; } }
}
Or
public class Player: Script
{
private static Player _instance;
public static Player MyInstance
{ get => _instance ?? (_instance = Level.FindScript<Player>());
}
}