Cloning a Sprite

Hi All,

I have a gameobject with a SpriteRender and game script with two SerializeField Sprites called defaultSprite and currentSprite.

The first method, named ClearSprite, takes the defaultSprite and creates a clone of it and then sets the currentSprite to this cloned sprite.

The second method, named AlterSprite, takes the defaultSprite and creates a clone of it, adds a black line, and then sets the currentSprite to this cloned sprite.

My problem is that after calling the AlterSprite, the ClearSprite no longer resets the image back to the defaultSprite. It seems to remember the Altered sprite from this point onward.

Can anyone help?

The following is the code:

public void ClearSprite()
{
if (spriteRenderer == null)
{
spriteRenderer = gameObject.GetComponent();
}

currentSprite = CloneSprite(defaultSprite);

spriteRenderer.sprite = currentSprite;
}

public void AlterSprite()
{
// Create a copy of the texture by reading and applying the raw texture data.
Texture2D newTexture = CloneTexture(defaultSprite.texture);

// Alter the cloned texture
// ---------------------------------------------------------
var newData = newTexture.GetRawTextureData();

// Overwrite sections
for (int x = 0; x < 32; x++)
{
var index = x;
newData[index] = new Color(0, 0, 0, 1.0f);
}

// Finalise the new texture
newTexture.LoadRawTextureData(newData);
newTexture.Apply();

// Final product
currentSprite = Sprite.Create(newTexture, new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0.5f, 0.5f), defaultSprite.pixelsPerUnit);

// Send to the sprite render
spriteRenderer.sprite = currentSprite;
}

private Sprite CloneSprite(Sprite source)
{
// Create a copy of the texture by reading and applying the raw texture data.
Texture2D textureCloned = CloneTexture(source.texture);
return Sprite.Create(textureCloned, new Rect(0,0, textureCloned.width, textureCloned.height), new Vector2(0.5f, 0.5f), source.pixelsPerUnit);
}

private Texture2D CloneTexture(Texture2D source)
{
// Create a copy of the texture by reading and applying the raw texture data.
Texture2D texCopy = new Texture2D(source.width, source.height, source.format, source.mipmapCount > 1);
var newData = defaultSprite.texture.GetRawTextureData();
// Load the original texture data
texCopy.LoadRawTextureData(newData);
texCopy.Apply();
return texCopy;
}

Format your code with code tags: Using code tags properly

At first glance, I’m wondering why your “CloneTexture” function is always outputting a copy of “defaultSprite.texture” data. Should it not be using the “source” parameter?

1 Like