Generic Class Questions

Started by
1 comment, last by BlueSin 10 years, 9 months ago

So I am reading the check marked reply on this post: http://gamedev.stackexchange.com/questions/30296/loading-class-instance-from-xml-with-texture2d

I have never used generic classes before and am absolutely confused on what he is talking about. I read up on them and understand how they should be used, but the respondent's answer doesn't sound like it makes sense in a generic class.

What exactly is he saying I should be passing into the generic class' constructor? Is he saying pass the Weapon instance into it, or the Texture instance? Because if I pass a Weapon instance into it as T t, I cannot call t.TextureId because the Type is unknown.

Advertisement

I think what he means is that you'll have a class (say RenderObject) that can handle rendering of different types of objects - weapons, monsters or Armor etc. The RenderObject class's DrawObject function (for example) will be able to extract texture information from your weapon/monster/armor xml, load said texture and draw it on-screen.

In c# a generic class or function performs certain operations regardless of the type it's operating on. An excellent example of this is the C# List<T>; List is a generic class, it stores an arbitrary number of elements of type T, regardless of whether T is an integer, a floating point number or some other custom class.

I'm not sure if the post you linked to actually meant that you should use generics in your implementation, I would be inclined to go with an interface or inheritance. So you'll have an object structure like this (the object initialisation should take care of loading in the relevant data from xml, you probably won't be able to directly load a texture, but you can load a path to a texture) :


enum ObjectType
{
 OT_Weapon,
 OT_Monster
 OT_Armor,
 ...
 OT_Max
};

class BasicObject
{
 BasicObject( ObjectType anObjectType )
 {
  myObjectType = anObjectType;
 }

 ObjectType myObjectType;
}

class Weapon : BasicObject
{
 Weapon : base( ObjectType.OT_Weapon )
 {
  ...
 }
}

Then in your texture loading/drawing class you'll look at the object data, extract the texture information, load said texture and render your object:


class ObjectRenderer
{
 public void DrawObject( BasicObject anObject )
 {
  // Here you can switch on the type of the object to cast to a specific object instance

  // Get the texture information out of the anObject instance

  // Load the texture (if it isn't already loaded)

  // Draw the texture
 }
}

Hope that helps!

Thanks that helped me understand it a bit better. Appreciate the help!

This topic is closed to new replies.

Advertisement