Game Development Community

dev|Pro Game Development Curriculum

allowInstanceMethods extension to SimObject namespace

by Orion Elenzil · 08/17/2006 (12:11 pm) · 0 comments

but first, more motivation.

PlayGui has many Instance Methods.
for example PlayGui::onWake().
this is handy.

PlayGui inherits from SimGroup which inherits from SimSet which inherits from SimObject.

However, none of those classes allow instance methods.

The following is a bit of code to grant the ability to use instance methods to any SimObject.

Note, use at your own risk, i'm not entirely sure of the implications of this.
If you don't know why you want it, you probably don't want it.
Basically it does the same thing w/r/t namespaces as GuiControl::onAdd().

See further discussion here.

simBase.h
additions are in bold.
Namespace* getNamespace() { return mNameSpace; }

   [b]bool       allowInstanceMethods();[/b]

simBase.cc
additions are in bold.
[b]ConsoleMethod(SimObject, allowInstanceMethods, bool, 2, 2, "obj.allowInstanceMethods()")
{
   return object->allowInstanceMethods();
}

bool SimObject::allowInstanceMethods()
{
   const char *name = getName();
   if(name && name[0] && getClassRep())
   {    
      Namespace *parent = getClassRep()->getNameSpace();
      if(Con::linkNamespaces(parent->mName, name))
      {
         mNameSpace = Con::lookupNamespace(name);
         return true;
      }
   }
   return false;
}[/b]


the following torquescript example illustrates the usage.
function testNamespace()
{
   new SimObject(mySimObject);
   new SimObject(mySimObject2);
   new GuiControl(myGuiControl);
   
   mySimObject2.allowInstanceMethods();
   
   mySimObject.func1();
   mySimObject2.func1();
   myGuiControl.func1();
}

function mySimObject::func1(%this)
{
   echo("mySimObject func1()");
}

function mySimObject2::func1(%this)
{
   echo("mySimObject2 func1()");
}

function myGuiControl::func1(%this)
{
   echo("myGuiControl func1()");
}

calling testNamespace() yields this output:
==>testNamespace();
dev/testNamespace.cs (9): Unknown command func1.
 Object mySimObject(5762) SimObject
mySimObject2 func1()
myGuiControl func1()