Before I post my code, I want to explain what my goal is.
Currently learning, so I hope some good tips and ideas will help me make this work.
An Object should have its colour changed for a certain period of time.
Suppose I have 10 objects and I want to control which kind of colour each object should have,
and also for how long time before it will change to another Color.
I tried it myself, but failed.
As a result, I tried ChatGPT.
I will post the code here.
For whatever reason, I am unable to see my GameObject.
using UnityEngine;
public class ColorChangeController : MonoBehaviour
{
[System.Serializable]
public struct ColorDuration
{
public Color color;
public float duration;
}
public ColorDuration[] colorDurations;
private SpriteRenderer spriteRenderer;
private int currentIndex = 0;
private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
// Start color changing process
ChangeColor(currentIndex);
}
private void ChangeColor(int index)
{
ColorDuration currentColorDuration = colorDurations[index];
// Change color and duration
spriteRenderer.color = currentColorDuration.color;
float duration = currentColorDuration.duration;
// Call ChangeColor method again after the specified duration
Invoke("NextColor", duration);
}
private void NextColor()
{
// Move to the next color index
currentIndex++;
// Reset index if it exceeds array length
if (currentIndex >= colorDurations.Length)
{
currentIndex = 0;
}
// Change color again
ChangeColor(currentIndex);
}
}