- Home /
The question is answered, right answer was accepted
instantiate a texture2d so changes don't affect clones
What I'm doing:
Exposing a public variable for a Texture2D
Using Get/SetPixels to create a new Texture2D by 'cropping' from the source
Why (the heck) I'm doing this:
Projectors can't use sprite sheets, so I'm providing a sprite sheet to a script on the projector and using code to create a new Texture2D representing a single cell of the spritesheet.
Works just fine... until I have more than one of these in the scene, created with GameObject.Instantiate(); In that case, each new clone changes the textures used by every other clone. Quite confused by why this is happening. Advice would be awesome.
Code, stripped of nonessential info...
public Texture2D spriteMap; // sheet with rows/columns of individual sprites
public int rows; // how many rows/ colums represented on the sheet
public int columns;
private Projector proj; // projector component of this object
void Start()
{
proj = GetComponent(); // UnityAnswers won't let me use gt, lt signs...
Material myCustomMaterial = Instantiate(proj.material) as Material;
// -----------------------------------
// info I need to randomly grab a cell of the spritesheet...
int x = CHelp.GetRandomInt(0, columns);
int y = CHelp.GetRandomInt(0, rows);
int sourceSizeX = spriteMap.width;
int sourceSizeY = spriteMap.height;
int cellSizeX = sourceSizeX / columns;
int cellSizeY = sourceSizeY / rows;
//Trying to copy the texture rather than reference it...??
Texture2D mySourceTexture = Instantiate(spriteMap) as Texture2D;
Color[] cropping =
mySourceTexture.GetPixels(
x * cellSizeX,
y * cellSizeY,
cellSizeX,
cellSizeY);
mySourceTexture = new Texture2D(cellSizeX, cellSizeY);
mySourceTexture.SetPixels(cropping);
mySourceTexture.wrapMode = TextureWrapMode.Clamp;
mySourceTexture.Apply();
// -----------------------------------
proj.material = myCustomMaterial;
proj.material.color = tint;
proj.material.SetTexture("_ShadowTex", mySourceTexture);
}
Answer by AlwaysSunny · Aug 13, 2012 at 07:57 AM
Duh. Wasn't cloning the material, so all clones shared it. For anyone who wants this script in the future, it's now been edited.
i am facing the same issue. can you please help me ? thanks
Follow this Question
Related Questions
rotate an image by modifying Texture2D.GetPixels32() array 2 Answers
getPixel/setPixels or stencil eraser brush 2 Answers
How to get ARGB values from Texture object? 1 Answer
How to change origin of GetPixels 0 Answers
Baking decals into a texture 3 Answers