- Home /
How to merge two textures of different size?
I'm developing 2d Tower Defense game and I want to be able to modify background texture(draw textures of dead units on it). I don't want to use separate objects to put on top of the background because I assume this will significantly slow down my game (number of units suppose to be VERY large).
I've found a code that allow to merge textures of the same size:
var tex1 : Texture2D;
var tex2 : Texture2D;
function Start (){
var pix1 = tex1.GetPixels32();
var pix2 = tex2.GetPixels32();
if (pix1.Length != pix2.Length) {
Debug.Log("Images need to be the same size");
return;
}
for (var i = 0; i < pix1.Length; i++) {
if (pix2[i].a != 0) {
pix1[i] = pix2[i];
}
}
tex1.SetPixels32(pix1);
tex1.Apply();
renderer.material.mainTexture = tex1;
}
How can I modify this code to be able to merge background texture with small textures (of dead units) at specific position?
Possibly you could deter$$anonymous$$e the combined size and then set the canvass in both textures to it, supllementing the textures withtransparent pixels.
yes, it's possible but how then I could place small texture in specific position? Let's say I want to place it at the center of bigger texture.
Answer by qvatra · Apr 12, 2014 at 09:51 PM
The solution is here:
#pragma strict
var texToDraw : Texture2D;
var x: int;
var y: int;
function Start (){
var background : Texture2D = Instantiate(renderer.material.mainTexture);
var pix1 = background.GetPixels32();
var pix2 = texToDraw.GetPixels32();
for (var j = 0; j < texToDraw.height; j++){
for (var i = 0; i < texToDraw.width; i++) {
pix1[background.width/2 - texToDraw.width/2 + x + i + background.width*(background.height/2-texToDraw.height/2+j+y)] = pix2[i + j*texToDraw.width];
}
}
background.SetPixels32(pix1);
background.Apply();
renderer.material.mainTexture = background;
}
Your answer
Follow this Question
Related Questions
Correct way to draw on screen for 2D game 1 Answer
Replacing Gui.DrawTexture or gui textures in C#? 0 Answers
How to not see white background on texture 1 Answer
Unity changes pixel colors 2 Answers