Deep Clone

Hello.

I want to make a copy of an object (the object include a Texture2D), I tried using serializing and deserializing , but as the Texture2D class not is serialisable, not work, then I tried using reflection, but as Texture2D have not a empty constructor, not work.

Any idea of how I can solve the problem? Thanks.

You cannot serialize and deserialize unmanaged resources, which is what the Texture2D object wraps. The first question is what are you wanting to achieve by making a copy of the Texture2D object? Once it is created, it is essentially an immutable object. The only thing you can change is set the pixel data on the unmanaged resource. So just copy the reference.

And serializing/deserializing just to make a copy makes the game programmer part of me shudder. That it is also what Unity does to copy objects doesn’t make it any better.

1 Like

Thanks, finally I used an alternative route to solve the problem, where not need make copy.

What was that alternative route that you found? I am having the same problem.

Haha, I joined your server about 2 weeks ago looking for your reasoning behind borderless instead of fullscreen.
I have seen that video, however, but it does not really work for me because I want to clone a Character that has lots of fieldsthat will definitely expand in the future, so I do not really want to do it through a constructor.
Thank you though.

You might consider making structs instead of classes then.
Fields get copied, constructor is needed only for class types.

Nah I need to be able to reference it in other parts of the code. It is the player character object, so I am pretty sure making it a struct will make things a lot harder elsewhere.
Thank you though.

You can always make a reference to the struct type, shouldn’t be a problem. It’s all guessing without the actual code and use cases :slight_smile:

I did not know you could do that. I managed to do it with Newtonsoft.Json serialisation, but it is possible that this will be too slow down the line when I am copying more objects in a frame. I have bookmarked this page in case it comes to that, thanks.

Best you can do is save or load the data for a image because once you load it its shared by the os the gpu and your application the question of ownership is at hand. That said serializing is essentially saving data i actually have class that makes spritefonts into a class then the class holds the data for the image which monogame then recreates the font and the texture td from calling load on the class itself aka the class holds all the data. But i would still be using references and object references to the 2d texture in game to it to pass it around for use.