Assigning a different material to different objects
Hey,
I want to be able to change the material of a gameObject dependent on the value of starclass. I have 7 materials which have been placed into the Inspection slots for element[0-6].
I've established that I have to essentially create a new material of size 1 and re-assign the the appropriate element back into the inspector but I just can't seem to do it. Any ideas?
Code below....
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class StarInfo : MonoBehaviour {
public float starID;
public string starclass;
private string starcolor;
public int startemp;
private float randomintfloat;
public GameObject star;
public Material[] materials;
public Renderer rend;
public void Start()
{
rend = gameObject.GetComponent<Renderer> ();
rend.enabled = true;
Invoke("Classify", 0f);
}
public void Classify()
{
switch (starclass)
{
case "O":
Debug.Log ("Should change color to O");
rend.materials = new Material[1];
rend.material = classmaterial[1];
//star.GetComponent<Renderer>().material.color = new Color(155, 176, 255);
break;
case "B":
Debug.Log ("Should change color to B");
rend.materials = new Material[1];
rend.material = classmaterial[2];
//star.GetComponent<Renderer>().material.color = new Color(170, 191, 255);
break;
case "A":
Debug.Log ("Should change color to A");
rend.materials = new Material[1];
rend.material = classmaterial[3];
//star.GetComponent<Renderer>().material.color = new Color(202, 215, 255);
break;
case "F":
Debug.Log ("Should change color to F");
rend.materials = new Material[1];
rend.material = classmaterial[4];
//star.GetComponent<Renderer>().material.color = new Color(248, 247, 255);
break;
case "G":
Debug.Log ("Should change color to G");
rend.materials = new Material[1];
rend.material = classmaterial[5];
//star.GetComponent<Renderer>().material.color = new Color(255, 244, 234);
break;
case "K":
Debug.Log ("Should change color to K");
rend.materials = new Material[1];
rend.material = classmaterial[6];
//star.GetComponent<Renderer>().material.color = new Color(255, 210, 161);
break;
case "M":
Debug.Log ("Should change color to M");
rend.materials = new Material[1];
rend.material = classmaterial[6];
//star.GetComponent<Renderer> ().material.color = new Color (255, 204, 111);
break;
}
Debug.Log ("The clones have been classified and colored.");
}
}
Answer by cleonmocika · Apr 19, 2017 at 08:26 AM
Instead of rend.material = classmaterial[index]
, try using rend.sharedMaterial = classmaterial[index]
. You also don't need the line that says rend.materials = new Material[1]
, there is no need to create a new material cause you're just using the ones you already created in the editor.
Answer by Valkarth · Apr 19, 2017 at 12:27 PM
Thanks for the response, I tried what you said but nothing changed. I'm still trying to find a solution.