HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Moving to other game states with ScreenManager

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
screenmanagerwithstatesgamemovingother

Problem

I'm creating a game in C#, and I've created a ScreenManager so I can call

ScreenManager.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

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.