Torque对对象的复制提供了一个方法,叫做clone.
ConsoleMethod(SimObject, clone, S32, 2, 3, "([bool copyDynamicFields? = false]) - Clones the object.\n"
"@param copyDynamicFields Whether the dynamic fields should be copied to the cloned object or not. Optional: Defaults to false.\n"
"@return (newObjectID) The newly cloned object's id if successful, otherwise a 0.")
需要注意的是这个复制是潜复制(shallow copy),具体可以参考:http://en.wikipedia.org/wiki/Object_copy.
用一个例子来解释:
%template = new SimObject()
{
NewName = "TestName";
Record = new SimSet();
};
echo( "template record id:" @ %template.Record.getId() );
for( %index = 0; %index < 10; %index++ )
{
%object = %template.clone( true );
echo( "clone object " @ %index + 1 @ " record id:" @ %object.Record );
}
输出的结果为:
template record id:1245
clone object 1 record id:1245
clone object 2 record id:1245
clone object 3 record id:1245
clone object 4 record id:1245
clone object 5 record id:1245
clone object 6 record id:1245
clone object 7 record id:1245
clone object 8 record id:1245
clone object 9 record id:1245
clone object 10 record id:1245
可以看出,所有的对象共享了Record变量,这不是我想要的结果.
按照作者的回复:
Clone is a shallow copy, not a deep copy. See here for more info about the difference.
Also, the field "Record" is a dynamic-field which is completely custom and Torque doesn't know the meaning of its contents so it can only copy the fields value which in this case would contain the Id of the object (SimSet) and not the object itself. In other words, a dynamic-field has no type, it's just a string so a string is what is copied.
所以针对那些New出来的对象不能识别类型,拷贝类似地址的句柄.要解决上面的问题有两种方法:
1: 等待作者提供一个叫做 Class::onClone的方法(最近几天会更新出来)
2: 自己写一个方法,潜复制的同时对这些New出来的类型创建实例.
下面 用第二种方法举例:
function deepClone( %this )
{
%object = %this.clone( true );
%object.Record = new SimSet();
return %object;
}
.......
%template = new SimObject()
{
class = "TestTemplate";
NewName = "TestName";
ValueNum = 1;
Record = new SimSet();
};
echo( "template record id:" @ %template.Record.getId() );
LaunchStage.add( %template );
for( %index = 0; %index < 10; %index++ )
{
%object = deepClone(%template);
%object.ValueNum = %index;
echo( "clone object " @ %index + 1 @ " record id:" @ %object.Record @ " value: " @ %object.getId() );
}
.......
输出的结果:
template record id:1324
clone object 1 record id:1326 value: 1325
clone object 2 record id:1328 value: 1327
clone object 3 record id:1330 value: 1329
clone object 4 record id:1332 value: 1331
clone object 5 record id:1334 value: 1333
clone object 6 record id:1336 value: 1335
clone object 7 record id:1338 value: 1337
clone object 8 record id:1340 value: 1339
clone object 9 record id:1342 value: 1341
clone object 10 record id:1344 value: 1343
扩展
如果是Behavior的复杂类型呢?嘿嘿,省略~~~