Assign materials at runtime, that aren't in the objects materiallist


I'm trying to build a configurator in which you can choose and place some parts of a piece of furniture (say a couch) to build it according to your own taste.

When a user selects a type of material in the webbrowser I call a script in Unity to change the material using:

renderer.sharedMaterial = materials[index];

where materials is the (in the editor) filled array of materials on that object.

The problem with this approach is that I have to add all materials to every piece of the furniture in the editor (in the same order) before being able to assign them at runtime. This will be alot of work when the amount of materials and objects stack up.

I tried something like:

obj1 = GameObject.Find("ObjectName1");
obj1.renderer.sharedMaterial = materials[index];
obj2 = GameObject.Find("ObjectName2");
obj2.renderer.sharedMaterial = materials[index];


to assign materials to all needed objects from 1 object that has all materials in its material array, but this doesn't seem to work.

Is there a way to add all materials i want to use in runtime in the project and assign them to any object by name? Something like:

GameObject.Find("GameObject").renderer.material = Material.Find('Fabric1');

You are on the right track with

GameObject.Find("GameObject").renderer.material = newMaterial;

There are 3 ways to obtain the texture you want; the first is to use Resources.Load to get the texture. However, this is not recommended for web players and results in a performance hit.

The other method is to pre-attach the textures you want to a script's array, and attach that object, to create a material catalog. Something like this

public var textures_ : Texture2D[];

public var changeTexture(target:GameObject, index:int)
   target.renderer.material = textures_[index];

When you attach this script to a game object, you will be able to drag and drop textures into the array. To use it, just invoke the changeTexture function of that gameobject and pass in the object which material is to be changed.

If you wish to use strings, you have to change the array to a Hashtable, and manually add in the textures (or just use the Hashtable to store the index).

The third ways is to use the WWW class to read in the texture from the hard disk/url (just put file:// in front of a file path and WWW can read it just fine). If have access to Unity3D pro, you can also use an asset bundle.

I don't think some of the above code works. I'm using Unity3.0 and doing this:

var Textures : Texture2D[];

function SetTexture(iIndex : int)
    renderer.material = Textures[iIndex];

and it gives the console error - BCE0022: Cannot convert 'UnityEngine.Texture2D' to 'UnityEngine.Material'.