I’m generating several game objects at runtime by instantiating a prefab. To complicate things, the prefab has 3 materials on it. I would like to change one specifically on each, the body paint material, with one I choose at runtime. Unity apparently keeps the materials in an Array, but I can easily see which one I would like to change with a quick
Debug.Log(this.gameObject.GetComponent<MeshRenderer>().materials[1]);
and this does confirm that .materials[1] is the one I want to change. But nothing happens. The material remains the default one with no errors given.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TruckColor : MonoBehaviour
{
public Material black;
public Material blue;
public Material green;
public Material orange;
public Material red;
public Material white;
public List<Material> truckColors;
int randomInt;
void Start()
{
truckColors.Add(black);
truckColors.Add(blue);
truckColors.Add(green);
truckColors.Add(orange);
truckColors.Add(red);
truckColors.Add(white);
randomInt = Random.Range(0, 5);
//Verifying I'm trying to change the right material
Debug.Log(this.gameObject.GetComponent<MeshRenderer>().materials[1]);
this.gameObject.GetComponent<MeshRenderer>().materials[1] = truckColors[randomInt];
}
void Update()
{
}
}
I can change the COLOR just fine with <MeshRenderer>().materials[1].color = Color.white but I would prefer to swap the materials for their smoothness and metallic properties all at once.
