Both images change after I set the second to the first, but only change the first

I am writing a bit of code that processes an image of the user’s choice such as it’s size.
However when I call the code, the variable of the original image, I keep if things such as reverting need to be done, is changed as well.
This is a short example of the code that I have for this

private void ProcessInputImage()
{
Image processImage = new Image();
processImage = originImage;
processImage .Resize(588, 816);
}

This code also changes the size of originImage, but I don’t want this.
How do I make it so that I can set processImage to originImage every time the method is called, but originImage never changes with the functions of this method?

I have other code running that does change originImage when the user chooses a different image from their drive so I can’t make it read-only.

Also, I am porting this to android so using

processImage.Load(path);

won’t work, since the plugin retrieves an image, not it’s path
(Besides it’s less optimized that way)

This is because Image is a reference type (as opposed to value types such as int ), so the = assignment only copies the reference to the object, but not the object itself.
Since both processImage and originImage reference the same Image, you resize the underlying image for both of them.

To actually copy the object, you can use the following statement:

processImage = originImage.Duplicate()

Duplicate() is available for all Resource classes such as Image.

This works.
only one small correction needed as I needed to cast it as an image

processImage = (Image)originImage.Duplicate()

oh, sorry forgot about the casting.
My head is currently in gdscript mode :sweat_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.