Forum C# Instantiate class from string name

Instantiate class from string name

Postby AniMoney » August 30th, 2013, 8:49 pm

I'm making a turn based game using as3 and c#. When the player selects their character at the beginning of the game (ex: Wolverine) I want to send their choice to the server and have the server instantiate the Wolverine class (which extends from a Character base class), and then send Wolverine's data (health, attacks, etc) back to the client.

So far I can get the character choice to the server, but I don't know how to take that string ("Wolverine") and instantiate the Wolverine class from it. I tried using System.Activator.CreateInstance, but it says it is a non-allowed method.

The reason I'm storing the data for the characters on the server is for security reasons. Players could theoretically cheat by giving their characters a billion health or something if they were stored on the client. If I can't solve this problem I will store them on the client, but it'd be great if someone could help me out.
AniMoney
 
Posts: 13
Joined: November 26th, 2012, 9:21 am

Re: Instantiate class from string name

Postby Henrik » September 1st, 2013, 6:26 am

I assume you keep an instance of the object server-side representing the state of the player?

Since you know all the valid character classes, you don't need to use reflection to make instances, just do a simple switch statement:
Code: Select all
switch (class) {
    case "wolverine":
        return new Wolverine();
    case "otherclass":
        return new OtherClass();
}
Henrik
.IO
 
Posts: 1880
Joined: January 4th, 2010, 1:53 pm

Re: Instantiate class from string name

Postby AniMoney » September 2nd, 2013, 12:01 am

Henrik wrote:I assume you keep an instance of the object server-side representing the state of the player?


Thanks for the reply, I do have a Player class, with instances for both clients (player1 and player2). I started working off the TicTacToe example. Could you go into more detail as to what you mean by the state of the player? Just like having the server know whether a player is in a menu, in a game, waiting, or making a decision, etc?

Since you know all the valid character classes, you don't need to use reflection to make instances, just do a simple switch statement:
Code: Select all
switch (class) {
    case "wolverine":
        return new Wolverine();
    case "otherclass":
        return new OtherClass();
}


I was trying to avoid this because I may end up having lots of characters, but I guess it is a better solution that storing the character classes in the client (flash).

EDIT: I had a follow up question, but I was being silly and figured it out...I think. Thanks for the help, I'm sure I'll have more questions coming soon :)
AniMoney
 
Posts: 13
Joined: November 26th, 2012, 9:21 am


Return to C#