patterncsharpModerate
Moving to other game states with ScreenManager
Viewed 0 times
screenmanagerwithstatesgamemovingother
Problem
I'm creating a game in C#, and I've created a
to move to other game states. However, I feel that my method of creating an instance of the class is... not very optimal. See for yourself.
Does anyone know if there's a better way to create an instance of a certain class from a
ScreenManager so I can callScreenManager.MoveToScreen(typeof(ScreenClassHere))to move to other game states. However, I feel that my method of creating an instance of the class is... not very optimal. See for yourself.
public static void MoveToScreen(Type s)
{
if (currentscreen != null) currentscreen.Remove();
currentscreen = (Screen)s.GetConstructor(System.Type.EmptyTypes).Invoke(null);
currentscreen.Init();
}Does anyone know if there's a better way to create an instance of a certain class from a
Type?Solution
You could use generics
In this case, you'd have to call the method as
public static void MoveToScreen() where T : Screen, new()
{
if (currentscreen != null) currentscreen.Remove();
currentscreen = new T();
currentscreen.Init();
}In this case, you'd have to call the method as
ScreenManager.MoveToScreen();Code Snippets
public static void MoveToScreen<T>() where T : Screen, new()
{
if (currentscreen != null) currentscreen.Remove();
currentscreen = new T();
currentscreen.Init();
}ScreenManager.MoveToScreen<ScreenClassHere>();Context
StackExchange Code Review Q#1066, answer score: 19
Revisions (0)
No revisions yet.