- Home /
Material.mainTexture not working outside of runtime?
I work on an editor script which should automatically create a material and add a texture to it during the import of a texture, using OnPostprocessTexture.
Now as far as I understand it, textures are added to materials through Material.mainTexture or Material.setTexture. But while things like SetColor are applied without problem during the import, the texture won't get connected to the material.
Is it possible that Material.mainTexture can not be used outside of runtime? How should I apply the texture in this case?
I mainly used the code from here: AssetPostprocessor reference to asset being processed?
using UnityEngine;
using System.Collections;
using UnityEditor;
public class UITextureImport : AssetPostprocessor
{
void OnPostprocessTexture(Texture2D texture)
{
if (assetPath.Contains("Assets/Textures/UI/") && assetPath.Contains(".png"))
{
// Create a matching material if one doesn't exist.
string materialPath = assetPath.Replace("Assets/Textures/UI/","Assets/Materials/UI/");
materialPath = materialPath.Substring(0,assetPath.LastIndexOf("/") + 1);
if (!Directory.Exists(materialPath))
{
Directory.CreateDirectory(materialPath);
}
materialPath += "/" + Path.GetFileNameWithoutExtension(assetPath) + ".mat";
Material material = (Material)AssetDatabase.LoadAssetAtPath(materialPath,typeof(Material));
if (material == null)
{
// Material doesn't exist, so create it now.
material = new Material(Shader.Find("UnlitAlphaImage"));
material.mainTexture = texture;
AssetDatabase.CreateAsset(material, materialPath);
}
else
{
// Material exists, so only assign the new texture to it.
material.mainTexture = texture;
}
}
}
}
Answer by RaL · Sep 24, 2014 at 10:12 AM
You need to change material.mainTexture = texture
to:
material.mainTexture = Resources.LoadAssetAtPath<Texture> (assetPath);
You will need to call that via
EditorApplication.delayCall to make sure Unity has finished importing the texture before you try loading it.
Your answer
Follow this Question
Related Questions
Setting an object's material causes strange behavior in custom editor 0 Answers
Why won't this (very simple) editor script compile? CS1041 1 Answer
Missing textures & materials in asset bundle 1 Answer
How can I change the default max size of a texture from an editor script (in import settings)? 1 Answer
Normal map not rendered until the material asset is selected in the inspector 1 Answer