Hey All,
I am working on a personal project and one of my concepts I am working with is an object with x number of materials assigned to this. I am trying to create a simple program that at the push of a button iterates over the materials assigned to the object one at a time. This part works.
What I am struggling with is I am trying to have it loop back around to its [0] index and the material in game is not updating.
Any help would be appreciated, thanks!
using UnityEngine;
public class Placeholder : MonoBehaviour
{
public GameObject prefab;
private MeshRenderer meshRenderer;
private int currentMaterialIndex = 0;
void Start()
{
// Check if the prefab is assigned
// Get the MeshRenderer component from the prefab
meshRenderer = prefab.GetComponent<MeshRenderer>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
NextMaterial();
}
}
public void NextMaterial()
{
Material[] materials = meshRenderer.sharedMaterials;
if (materials.Length > 0)
{
// Increment the index
currentMaterialIndex++;
// Wrap around to the first material if the index exceeds the length
if (currentMaterialIndex >= materials.Length)
{
currentMaterialIndex = 0;
}
// Assign the material at current index to the first element
materials[0] = meshRenderer.sharedMaterials[currentMaterialIndex];
// Reassign the modified material array back to the MeshRenderer
meshRenderer.sharedMaterials = materials;
Debug.Log("Current Material Index: " + currentMaterialIndex);
}
}
}