So I have a mesh with 2 materials and I need it to change material every so often. Basically I need to do what is explained it this pic.
I wrote this code but i have some problems:
- Even thou I made a variable for the renderer called rend rend.Material isn’t working and I need to do the full getComponent
- This is changing the 1st material. What do I do to change the 2nd material???
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pin : MonoBehaviour {
public int timer;
public int CurrentMaterial = 0;
public Material[] Materials;
// Use this for initialization
void Start () {
Renderer rend = GetComponent<Renderer>();
}
// Update is called once per frame
void Update () {
timer++;
if (timer >= 100) {
timer = 0;
if (CurrentMaterial == Materials.Length) {
CurrentMaterial = 0;
}else{
CurrentMaterial++;
}
GetComponent<Renderer>().material = Materials[CurrentMaterial];
}
}
}
Not tested, but I think this should work.
Get the array of assigned materials from the renderer, change it, and assign the modified materials array back to the renderer. To get all materials you need to use GetComponent().materials, this will return the array with all the used materials. If you use GetComponent().material (without the s), you will only get the first material.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pin : MonoBehaviour {
public int timer;
public int CurrentMaterial = 0;
public Material[] Materials;
// Use this for initialization
void Start () {
Renderer rend = GetComponent<Renderer>();
}
// Update is called once per frame
void Update () {
timer++;
if (timer >= 100) {
timer = 0;
if (CurrentMaterial == Materials.Length) {
CurrentMaterial = 0;
}else{
CurrentMaterial++;
}
Material[] currentlyAssignedMaterials = GetComponent<Renderer>().materiasl;
currentlyAssignedMaterials[theIndexYouWantToChange] = Materials[CurrentMaterial];
GetComponent<Renderer>().materials = currentlyAssignedMaterials;
}
}
}
Im going to test it right now.
But Instead of GetComponent().material can’t you do rend.material … In theory that should work but it’s not working.
Yes, but you wrote yours incorrectly. You must moved the declaration outside of Start()
Renderer rend;
void Start() {
rend = GetComponent<Renderer>();
}
// now it's valid.
Tnx Methos
It’s still giving me THESE errors.
Edit: Ok fixed it:
turns out it was .materials not .material
Must have copied wrong