- Home /
Duplicate Question
Changing material during runtime
I want to change the material of some trees to add variation to my scene. By clicking the mouse, you instantiate a tree on the ground mesh. I have the following script attached to my trees, that should change the colour of them:
public class treeSettings : MonoBehaviour
{
public Material[] myMaterials;
void Start ()
{
gameObject.GetComponent<Renderer>().material = myMaterials[Random.Range(0,myMaterials.Length)];
}
}
In the inspector, the material changes, however in the game, it does not.
Thanks for any help you can give me.. im really stumped. :(
Answer by scarletshark · May 06, 2015 at 08:23 PM
Are you 100% you've set your materials in the inspector? I copy/pasted your code and it worked fine using my own instantiation script:
public GameObject cube;
private Vector3 clickPosition;
private Vector3 cubePosition;
private float zDistance;
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)){
zDistance = Random.Range(2.0f, 10.0f);
Vector3 clickPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, zDistance);
cubePosition = Camera.main.ScreenToWorldPoint(clickPosition);
Instantiate(cube, cubePosition, Quaternion.Euler(Vector3.zero));
}
}
well what I did was instantiate my object like the above, and then in a separate script, I had that code. I added a meshRenderer component to the object, and then that code to each. However, when I run the game, the material appears in the inspector, but isn't applied to the object. It stays pink... An screenshot of what happens:
Figured out what I was doing wrong, I had a prefab within a prefab, and it was instantiating both, with the child for some reason forcing the parent not to render... Anyway, solution found, thanks everyone that helped.