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;
			}
		}
	}
}

You need to change material.mainTexture = texture to:

`material.mainTexture = Resources.LoadAssetAtPath (assetPath);`

You will need to call that via EditorApplication.delayCall to make sure Unity has finished importing the texture before you try loading it.