How to assign existing material to an object ?
I know how to access object's material list:
obj.GetComponent<MeshRenderer>().material = ???
However, what should go in ??? The material already exists in my Assets folder as .mat file. I run this script in editor NOT at runtime. The result should be equivalent to manually (with mouse clicks) assigning material in Inspector->MeshRenderer. Resources.Load
is the weirdest function I have seen so far and I don't want to use it. AssetDatabase.LoadAssetAtPath
doesn't work.
Answer by TBruce · Apr 05, 2016 at 03:31 AM
@szpaq234 The method below will load the material named "MyMaterial" which is located in your "Assets/Resources/Materials/" folder.
void LoadMaterial ()
{
private string materialName = "MyMaterial";
Material m = Resources.Load<Material>("Materials/" + materialName) as Material;
Material[] materials = GetComponent<MeshRenderer>().materials;
if (materials.Length > 0)
{
materials[0] = m;
GetComponent<MeshRenderer>().materials = materials;
}
}
Is there a way to bypass this "Resource" thingy ? The project is big and distributed and this would totally mess up everything.
If you do not want to assign $$anonymous$$eshRenderer.materials[0] in the editor you can create a public variable and assign it at run time.
public $$anonymous$$aterial my$$anonymous$$aterial;
void Load$$anonymous$$aterial () { if (my$$anonymous$$aterial != null) { material = my$$anonymous$$aterial; GetComponent<$$anonymous$$eshRenderer>().material = material; } }
Your answer
Follow this Question
Related Questions
ScriptedImporter in Android build 0 Answers
Materials I downloaded with my assets are all white. 0 Answers
InitializeOnLoadMethod loading assets doesn't load main asset 0 Answers
script to replace material on object with timer or button press not working 2 Answers
Changing a Prefab's Text component seems to be broken. 1 Answer