// create material Material newMaterial = new Material( Shader.Find("Diffuse")); // assign shader newMaterial.shader = sourceMaterial.shader; // copy properties from existing material newMaterial.CopyPropertiesFromMaterial(sourceMaterial); // create texture from asset(asset path) Texture texture = (Texture)AssetDatabase.LoadAssetAtPath( textureRelativePath, typeof(Texture)); // assign texture to material newMaterial.SetTexture("_MainTex", texture); // create material asset AssetDatabase.CreateAsset(newMaterial, newMaterialAssetRelativePath); // assign material to gameObject AssignMaterial( gameObject, newMaterial );
在建立texture時需注意,在editor部份可以使用AssetDatabase.LoadAssetAtPath,而runtime則需使用Resource.Load。