[.net] c# using generics

Started by
4 comments, last by Iarus 15 years, 3 months ago
Hi, I'm coding in C# for XNA. I'm creating a "scene manager", as in frontend menu / gameplay / post match / ..., not a scene manager like a quad tree. (probably not a good name...) I'd like to do have classes like GamePlayScene and FrontEndScene that inherits from a base Scene class. And when I want to load the next scene:
...
SceneManager.SetScene<GamePlayScene>();
...
Where the SetScene method would create and load a new scene in a loading thread.
void SetScene<SceneType>()
{
	//unload current scene
	currentScene.UnloadScene();
	currentScene = null;

	//load the new scene
	currentScene = new SceneType(...params...);
	currentScene.LoadScene();
}
I think generics could be used for this, but I don't know how or even if it's possible. I'd like to pass the class name of the new scene instead of an instance. Because the scene manager holds the scene, not the calling function, and also because of parameters in the construtor, but thats not a problem, I could use an init method. I could create an enum
enum SceneType{GamePlay, FrontEnd,...}

void SetScene(SceneType sceneType)
{
	//unload current scene
	...

	//load the new scene
	switch( sceneType )
	{
		case SceneType.GamePlay:
			currentScene = new GamePlayScene(...params...);
			break;
		case SceneType.FrontEnd:
			...
	}
	currentScene.LoadScene();

But then when I'll create a new scene class, I'll have too change the enum, the switch and a lot of stuff everywhere. maybe generics are a bad idea? I don't know.
Advertisement
You could, but why don't you just pass a new-created Scene object in?

void SetScene(Scene newScene){  currentScene.UnloadScene();  currentScene = newScene;  currentScene.LoadScene();}
yeah, I know and that's probably what I'll do, but I wanted to try something else.
I'm not sure I understand what's your goal, but if you want to use

SetScene<T>() where T : class, IScene, new()

you can create a T instance with the Activator.CreateInstance methods, passing in typeof(T) as the type param. Does this help?
Rainweaver Framework (working title)

IronLua (looking for a DLR expert)



Have you looked at the gamestate management sample on the Creators Club site?

Former Microsoft XNA and Xbox MVP | Check out my blog for random ramblings on game development

@Rainweaver: Wow! that's exactly what I want. (well, probably, I'll need to test it this evening.) I'll have to see if this is actually useful :)
When I tried yesterday, I had an error about the new, and I didn't know what was missing.
Thanks

@Machaira: yes I've seen it, I'm doing something very similar

This topic is closed to new replies.

Advertisement