Clone
Introduction
The Clone method is a generic method which can be used to create new instances of objects which inherit from PositionedObjects. Since it is generic, the Clone method can be used on types that inherit from the PositionedObject class, like Entities.
Code Example
The following creates a custom PositionedObject class called WeightedObject. It manually creates one WeightedObject, then creates a clone of it. The output Text shows that the WeightedObject has been properly cloned. Add the following using statement:
Define your WeightedObject class:
Add the following to Initialize after initializing FlatRedBall
What does Clone actually copy?
The Clone method clones your PositionedObject, but there are a few details to keep in mind. First, the Clone method calls the MemberwiseClone method, which is a method that exists for all objects in .NET. This method performs a "shallow" copy. What that means is that if your object has a member that is a reference (for example, to another Sprite), then the newly-cloned object will share the exact same reference. It will not create a new Sprite instance for it to reference as a member. All value members (such as float or int) will be copied and each object will have its own value data. There are a few exceptions. The PositionedObject will create new instances for:
ListsBelongingTo
Children
Instructions
The new clone will have new lists for the properties mentioned above, and they will be empty.
Cloning Reference Objects
If you are creating an object which includes other referenced objects (such as Sprites, Texts, or any collision Shapes), then you will need to manually clone the objects and re-attach these objects. We recommend encapsulating this logic in a Clone method as follow:
FlatRedBall objects like Sprites and collision Shapes provide Clone methods which can be used to simplify cloning. If your object contains other reference objects then you will either:
Need to add a Clone method to those objects if you have written them yourself.
Manually instantiate a new object for the new PositionedObject instance in the Clone method and set any variables that should be set.
Last updated