Assign Material at run time

I have a problem for assign the material to object. In that object there are 2 materials.

I tried, renderer.material = material;

and renderer.materials[1] = material;

The first one modify the first material and second one does nothing. Pls help me to change the 2nd material…

What is the exact configuration of your materials and renderers?

I am doing a slingshot type game.The slingshot has two material. First material is only color.The second one is texture of the slingshot. I need to change the second one. var Sling : GameObject; var Material1 : Material; function OnMouseDown() { if(condition) { Sling.renderer.materials[1] = Material1; } } Also i tried the Sling.renderer.material = Material1; This only change the first material of Sling. Thanks..

same problem here :) is anybody solved it?

Bunny83 already posted the correct answer.

2 Answers

2

The problem is that .materials is a property which returns a copy of the material array. All you can do is assign a new array to this property. To change the second material you would do something like:

var Sling : GameObject;
var Material1 : Material;

function OnMouseDown()
{
    if(condition)
    {
        var mats = Sling.renderer.materials;
        mats[1] = Material1;
        Sling.renderer.materials = mats;
    }
}

But be careful, this only works if there are two materials attached, otherwise you can’t just set another material. You would have to create a new, bigger array.

its working!

GameObject.renderer is deprecated. What's the new way to do this?

Hi there, try this:

var material0 : Material;
var material1 : Material;
-
function Update () {
    if (some input) {
        renderer.sharedMaterials[1] = material0;
    }
    if (other input) {
        renderer.sharedMaterials[1] = material1;
    }
}

Hope this help. :wink:

thanks 3D-Magic-VR, I tried this but nothing change

Pls anybody help with this