TX/Tutorials and Guides/TX UserGuide/Object Cloning and Pooling

From TDN

This page is a Work In Progress.


Return To Contents Page

Object Cloning and Pooling

Torque X provides a framework for cloning objects and pooling objects for later re-use. These two functions are very intertwined. In fact, if you don't create your objects via cloning then the object pooling will not work (in fact, it will create pools of objects but never tap into them). But this shouldn't matter because you should always use clone to create new objects.

Object cloning requires you to implement the CopyTo method on all your objects and components. The CopyTo method must copy all public properties not marked with the TorqueCloneIgnore attribute. If you fail to do this you will get an assert in debug mode which will tell you exactly what lines of code need to be added. You might be wondering why you have to implement the code if the program can tell you what lines of code to add. The reason has to do with missing reflection methods in the compact framework on the 360. For this same reason, the assert will not occur if you are running in debug on the 360.

If you choose to use object pooling then you have to be sure to implement the IResetable interface on all your objects and components so that all your data is properly initialized between uses of an object (or you can make sure that your objects are properly reset in OnRemove and your components in _ResetComponent). Assuming you do this, all it takes to turn on object pooling is to set the Pool flag or the PoolWithComponents flag on your object. You can set the flag on some objects and not others to get fine grain control over what objects are pooled. The difference between Pool and PoolWithComponents is that if Pool is set then your object and components are stored in separate pools. When creating a new object the object and components are retrieved from their respective pools and assembled like the object they are being cloned from. The problem with this is that objects and components can end up on opposite ends of memory, potentially causing poor CPU caching. If PoolWithComponents is set then objects and components are pooled together (the pool is on a per template basis rather than a per object type or per component type basis). We suspect that PoolWithComponents is usually the better choice, but it may be worth it to you to test.

The standard way to create new objects in your game is to define a template object in your xml file (this object should have the IsTemplate flag set) and to clone that whenever you want a new one of those. If one of the pool flags is set on that object, then object pooling will happen automatically.


Return To Contents Page

This is Community Maintained, you may, and probably will, find out of date material. Feel free to update any of these articles yourself.