x


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

more ▼

asked Jul 04 '10 at 11:15 AM

Steve Edwards gravatar image

Steve Edwards
164 30 31 39

(comments are locked)
10|3000 characters needed characters left

2 answers: sort newest

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)

more ▼

answered Jul 04 '10 at 11:46 AM

Mike 3 gravatar image

Mike 3
30.7k 10 67 255

Thanks Mike, 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)

Jul 04 '10 at 01:02 PM Steve Edwards
(comments are locked)
10|3000 characters needed characters left
 @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");
}
more ▼

answered Jul 04 '10 at 01:10 PM

Steve Edwards gravatar image

Steve Edwards
164 30 31 39

I also wanted to then assign the new material to the currently selected object...

Selection.activeGameObject.renderer.sharedMaterials = material;

but get this error: "Cannot convert UnityEngine.Material to (UnityEngine.Material), which is quite funny as errors go.

Jul 04 '10 at 01:16 PM Steve Edwards

(UnityEngine.Material) means it's expecting an array of Materials. If you use sharedMaterial instead of sharedMaterials it should work fine

Jul 04 '10 at 02:21 PM Mike 3

Thanks, that got it.

Jul 04 '10 at 02:45 PM Steve Edwards
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3418
x841
x427
x146

asked: Jul 04 '10 at 11:15 AM

Seen: 4447 times

Last Updated: Jul 04 '10 at 11:15 AM