Skip to main content
GameDev.net gamedev.net
🔒 Locked

[XNA] Dynamically Assign a Data Type ?

Started by ZaQ Jan 13, 2013 at 7:51 AM 2 replies 1.8k views
Original Post
ZaQ
ZaQ

I am trying to brush up on my C# / XNA and I cannot figure out how to assign a data type at runtime.

I want to refer to all characters by creating a new Character.cs

Then inside of the Character.cs I instantiate a character type and choose a sub-.cs

Here is a representation of what I am used to doing in AS3:


Game1.cs

public Character Char = new Character();
 
CharType(Char, "Ninja");

public void CharType(Character Char, String chartype)
{
  if(chartype == "Ninja")
     Char.GameChar = new Ninja();
  else if(chartype == "Soldier")
     Char.GameChar = new Soldier();
}

Character.cs
 
var GameChar;

Is this possible in XNA / C#?

To be more clear, I am having trouble have the "var GameChar" in the Character.cs. I cannot find a way to program the variable into the class without first assigning a data type to it. I tried using an 'Object' and 'dynamic' but they wouldn't allow me to access variables within the GameChar variable.

If not, can anyone give me some pointers?

DpakoH
DpakoH
use an interface (ofc only properties and methods described in the interface will be accessible and if you want something more specific from soldier class you will have to cast CharacterType to Soldier with a check if the cast is succcesfsul)
public class Soldier : IFighter {} //interfacepublic class Ninja : IFighter {} //interface public class Character { public IFighter CharacterType { get; set; }  public Character(string type) {    if (type == "Ninja") {      CharacterType = new Ninja();    }    // etc }}
ZaQ
ZaQ

Thank you both, I'll read up on it.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.