get material from the library at runtime

i have several scenes with several objects that all have a script attached which changes the material of its object to one common material for highlighting.

how would i assign that material to the script programmatically? Currently i drag the script to the object and assign this material manually for each object, but there are hundreds more to come.

is there an equivalent for

Shader.Find("shader name")

that works with materials?


i now use one instance of a class MaterialStorage in each scene and get the material from there:

MaterialStorage storage = FindObjectOfType(typeof(MaterialStorage)) as MaterialStorage;
	if(storage != null) this.highlightMaterial = storage.getHighlightMaterial();

As Adrian said, read up first on resources, and make sure the Material is in the correct resources folder. Then you can do something like this in your code…

Material yourMaterial = (Material)Resources.Load("MaterialName", typeof(Material));

yourObject.renderer.sharedMaterial = yourMaterial;

The advantage of dragging any resource into a slot of a game object is that Unity is then able to figure out which resources your scene is using and can include only what’s needed in your build.

You already found a good solution in case a common resource is shared by lots of object: Create a super-object that contains the references and form which all other scripts will get it form.

There’s also the Resources class which defeats this system and allows you to load a resource by name from a Resources folder. In this case, everything in the Resources folder will be included in builds all the time, since Unity can’t figure out what is in use.

Thank you.