Re-creating a run-time created texture

I’ve got a simple actor which contains 2 static mesh components and 1 scene capture component 2d for components. It also has a Texture2D property and an array of FColors (which I’m using for pixel data, will get to this).

The Texture2D is being generated at runtime from the scene capture component 2d.

I’m trying to serialize the Texture2D, but it seems to only serialize the location, which doesn’t exist if that generated texture is no longer in the second playthrough.

So, I’m going through the texture and grabbing pixel data via

TArray<FColor> PixelColor;

	const FColor* FormatedImageData = static_cast<const FColor*>(MyTexture->PlatformData->Mips[0].BulkData.LockReadOnly());

	for (int32 X = 0; X < MyTexture->GetSizeX(); X++)
	{
		for (int32 Y = 0; Y < MyTexture->GetSizeY(); Y++)
		{
			PixelColor.Add(FormatedImageData[Y * MyTexture->GetSizeX() + X]);
		}
	}

Now I’ve got my array of pixels that I can serialize, but when I try to re-construct the texture using that pixel array, I’m getting artifacts instead of proper texture. This is the re-creating process:

UProperty* PixelProperty = ActorWithTexture->GetClass()->FindPropertyByName(PixelsPropertyName);
MyArr = PixelProperty->ContainerPtrToValuePtr<TArray<FColor>>(ActorWithTexture);
Texture = UTexture2D::CreateTransient(width, height, PF_B8G8R8A8);


#if WITH_EDITORONLY_DATA
	Texture->MipGenSettings = TMGS_NoMipmaps;
#endif
	Texture->NeverStream = true;

	Texture->SRGB = 0;

	FTexture2DMipMap& Mip = Texture->PlatformData->Mips[0];
	void* Data = Mip.BulkData.Lock(LOCK_READ_WRITE);

	FMemory::Memcpy(Data, MyArr, width * height * 4);
	Mip.BulkData.Unlock();
	Texture->UpdateResource();

What am I doing wrong?

Turns out it was a simple error on my side, easy to fix, annoying to locate.

FMemory::Memcpy(Data, MyArr->GetData(), width * height * 4);

Works like a charm now.

This plugin perfectly solves this problem, perhaps help you:
Screenshot as Texture2D in Code Plugins - UE Marketplace (unrealengine.com)