I’m working on a script to create a new material that has a Diffuse and Bump map as a flattened form of the materials used to make it.
However, I seem to be having trouble actually using the textures in the materials to create the new layers.
I gave typecasting a shot, but it seems to not work. Anyone have a better suggestion?
Full code:
public static Material FlattenMaterials(List<Material> sourceMaterials, bool normalAlpha) {
//Combine a list of materials into one material, using "useShader" as the shader.
//If normalAlpha == true, the transparency will derive from the bump map rather than the diffuse.
Material firstMat = sourceMaterials[0];
Material newMat = new Material(firstMat.shader);
Texture2D newDiffuse = new Texture2D(firstMat.mainTexture.width,firstMat.mainTexture.height,TextureFormat.ARGB32,false);
newDiffuse = (Texture2D)firstMat.mainTexture(typeof(Texture2D));//SetPixels(firstMat.mainTexture.GetPixels(0),0);
Texture2D newNormal = null;
if(newMat.HasProperty("_BumpMap")) {
new Texture2D(firstMat.mainTexture.width,firstMat.mainTexture.height,TextureFormat.ARGB32,false);
newNormal.SetPixels(firstMat.GetTexture("_BumpMap").GetPixels(0),0);
}
Texture2D tempDiffuse = new Texture2D(0,0,TextureFormat.ARGB32,false);
Texture2D tempNormal = new Texture2D(0,0,TextureFormat.ARGB32,false);
Color newColor = Color.white;
int i = 0;
int l = sourceMaterials.Count;
int x = 0;
int y = 0;
int xx = 0;
int yy = 0;
while(i<l) {
//Set up new Diffuse.
if(sourceMaterials[i].mainTexture) {
Texture2D tempTex = sourceMaterials[i].mainTexture;
tempDiffuse.Resize(tempTex.width,tempTex.height,TextureFormat.ARGB32,false);
tempDiffuse.SetPixels(tempTex.GetPixels(0),0);
tempDiffuse.Resize(newMat.mainTexture.width,newMat.mainTexture.height,TextureFormat.ARGB32,false);
tempTex = sourceMaterials[i].GetTexture("_BumpMap");
tempNormal.Resize(tempTex.width,tempTex.height,TextureFormat.ARGB32,false);
tempNormal.SetPixels(tempTex.GetPixels(0),0);
tempNormal.Resize(newDiffuse.width,newDiffuse.height,TextureFormat.ARGB32,false);
y = 0;
x = 0;
xx = tempDiffuse.width;
yy = tempDiffuse.height;
while(y < yy) {
while(x < xx) {
Color colorChange = sourceMaterials[i].color;
Color mainPixel = newDiffuse.GetPixel(x,y);
Color newPixel = tempDiffuse.GetPixel(x,y);
Color alphaPixel = mainPixel;
if(normalAlpha) {
if(tempTex) {
alphaPixel = tempTex.GetPixel(x,y);
}
}
if(alphaPixel.a != 0.0f) {
mainPixel = Color.Lerp(mainPixel,newPixel*colorChange,alphaPixel.a);
newDiffuse.SetPixel(x,y,mainPixel);
}
++x;
}
++y;
}
++i;
}
Typecasting line:
newDiffuse = (Texture2D)firstMat.mainTexture(typeof(Texture2D));//SetPixels(firstMat.mainTexture.GetPixels(0),0);