Change material with editor script

I try to change the material of a gameobject in the editor by a EditorScript. I use this code:

if(boolean == true)
{
   var newMat = AssetDatabase.LoadAssetAtPath("Assets/blue.mat", typeof(Material));
   if(newMat != null)
      Debug.Log("Asset loaded");
   else
      Debug.Log("cant find asset");

   target.renderer.material = newMat;
}

when i click the boolean in the EditorScript my debug log prints “Cant find asset”.

why u want to use LoadAsserAtPath anyway?? it is useless in standalone or web build so jus declare a var as material and link the material to the script in editor… it will work?!

var newMat:Material;

function changeMat()
{
if(newMat != null)
Debug.Log(“Asset loaded”);
else
Debug.Log(“cant find asset”);

target.renderer.material = newMat;
}

that will work indeed but then i have to assign the material everytime i attach the script to a object. It was much easier if i could just add the script to a object and change the material automatic.

If you have same objects meaning like you attach the material to the object and you need several of them. Just create a prefab out of that object and place the prefab in your scene instead. Or you could just duplicate the object that already attached your scripts to. :smile:

I want to set the material by script i don’t want to make a prefab.