- Home /
Is it possible to create a Material _asset_ from a script?
Hi,
I know how to create a temp material for a game object, but is it possible to create a new asset within a script?
I want to be able to do this as part of an editor script I'm writing.
Thanks
Steve
Answer by Mike 3 · Jul 04, 2010 at 11:46 AM
Check out AssetDatabase.CreateAsset - it'll turn an instance of a material into an Asset in the project
http://unity3d.com/support/documentation/ScriptReference/AssetDatabase.CreateAsset.html
(Even has a material example for you)
Thanks $$anonymous$$ike, ideal. I also modified it slightly to name the material after whatever is currently selected in the Hierarchy: (I put this in a separate answer because it didn't seem possible to format code in a comment)
Answer by Steve Edwards · Jul 04, 2010 at 01:10 PM
@MenuItem("GameObject/Create Material")
static function CreateMaterial () {
// Create a simple material asset
var material = new Material (Shader.Find("Diffuse"));
AssetDatabase.CreateAsset(material, "Assets/" + Selection.activeGameObject.name + ".mat");
}
I also wanted to then assign the new material to the currently selected object...
Selection.activeGameObject.renderer.shared$$anonymous$$aterials = material;
but get this error: "Cannot convert UnityEngine.$$anonymous$$aterial to (UnityEngine.$$anonymous$$aterial), which is quite funny as errors go.
(UnityEngine.$$anonymous$$aterial) means it's expecting an array of $$anonymous$$aterials. If you use shared$$anonymous$$aterial ins$$anonymous$$d of shared$$anonymous$$aterials it should work fine
Answer by lumeneo · Mar 13, 2019 at 04:43 PM
https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
using UnityEngine;
using UnityEditor;
public class CreateMaterialExample : MonoBehaviour
{
[MenuItem("GameObject/Create Material")]
static void CreateMaterial()
{
// Create a simple material asset
Material material = new Material(Shader.Find("Specular"));
AssetDatabase.CreateAsset(material, "Assets/MyMaterial.mat");
// Print the path of the created asset
Debug.Log(AssetDatabase.GetAssetPath(material));
}
}