NoviKorisnikk
NoviKorisnikk

Reputation: 313

How to change material on second position?

I want to change material on position 2 , when i change material in my code it get changed on position 0 not on position 1.

I don't know how i can change material on position 1 .. This is code that changes material on position [0]

 public Material[] materials;
public Renderer rend;

// Start is called before the first frame update
void Start()
{
    rend= GetComponent<Renderer>();   
}
// Update is called once per frame
void Update()
{
 rend.material = materials[1];  
}

I want to change material on this picture with name New Material 2 To material which i define in code.

enter image description here

Thank you community very much :)

Upvotes: 2

Views: 108

Answers (1)

VPavliashvili
VPavliashvili

Reputation: 655

It changes on index 0 and not index 1 because you are using rend.material instead of rend.materials

public class MaterialChanger : MonoBehaviour {

public Material[] Materials;
public MeshRenderer MeshRenderer;

void Start() {
    MeshRenderer = gameObject.GetComponent<MeshRenderer>();        
}

void Update() {
    int requredMaterialIndex = 1; //this is just test value
    MeshRenderer.materials[1] = Materials[requredMaterialIndex];   
}

And I suggest you to always use Meshrenderer instead of Renderer just for efficiency

Upvotes: 1

Related Questions