- Home /
Batch creating material files for png textures
I am trying to make a script that takes a folder of PNG textures and creates material files for them. The problem is that the created material files do not have any texture assigned after creation and I cant figure out why.
Here is my code:
string targetPath = Application.dataPath + "/" + materialPath;
string[] assetFiles = Directory.GetFiles(targetPath, "*.png");
if (assetFiles.Length > 0)
{
Debug.Log(assetFiles.Length + " .png files found in'" + targetPath + "'");
for (int i = 0; i < assetFiles.Length; i++)
{
Shader stdShader = Shader.Find("Standard");
if (stdShader == null) Debug.LogError("stdShader == null");
Material newMat = new Material(stdShader);
if (newMat == null) Debug.LogError("newMat == null");
if (!stdShader || !newMat) return;
byte[] texBytes = File.ReadAllBytes(assetFiles[i]);
Texture2D newTex = new Texture2D(2, 2);
newTex.LoadImage(texBytes);
newMat.mainTexture = newTex;
newMat.SetFloat("_Glossiness", 0);
string newAssetPath = "Assets/" + materialPath + "/" +
Path.GetFileNameWithoutExtension(assetFiles[i]) + ".mat";
AssetDatabase.CreateAsset(newMat, newAssetPath);
Debug.Log(AssetDatabase.GetAssetPath(newMat));
}
}
I tried using newMat.SetTexture("_MainTex", newTex) too but it did not work either.
You're creating a new Texture2D in memory. You need to reference the texture asset ins$$anonymous$$d.
How can I find the Texture asset? I thought about AssetDatabase.FindAssets but cant figure out how to use it properly in this case.
Well, if you want to use the specific path with the wildcard "*.png", and since you already have that, you can use AssetDatabase.AssetPathToGUID
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Casting Error C# between Object[] and Texture2D[] 2 Answers
Texturing custom 2d sprite 0 Answers