- Home /
C# Unity how to select only one item in an array and deselect other items
I have gameObject array that I'm looping through to animate the material with a delay for each gameObject. I am using a Coroutine in order to use WaitForSeconds and a for loop inside of it to add a delay for each object.
What ends up happening is all the objects in the array gets selected therefore the animation happens to all of them instead of just one object at a time
What I'm looking for, only the cube selected at the index to change color and to revert color once its not selected at index any more. Then after a delay of 0.3 seconds it selects the next one (so all the previous cubes to revert back the color)
How can I achieve that?
public GameObject[] laneMat;
float duration = 6f;
void Start()
{
StartCoroutine(matColorLerp( .3f));
}
IEnumerator matColorLerp( float delay)
{
;
for (int i = 0; i < laneMat.Length; i++)
{
laneMat[i].GetComponent<Renderer>().material.color = Color.Lerp(originalColor,
startColor, Mathf.PingPong(time, 0.5f));
yield return new WaitForSeconds(delay);
}
}
}
Answer by Hellium · Mar 25, 2021 at 04:08 PM
Code not tested:
IEnumerator matColorLerp(float delay)
{
for (int i = 0; i < laneMat.Length; i++)
{
Material material = laneMat[i].GetComponent<Renderer>().material;
Color startColor = material.color;
Color endColor = Color.red; // change for desired color
for(float t = 0 ; t < duration ; t += Time.deltaTime)
{
float progress = Mathf.PingPong(2 * t, duration) / duration;
material.color = Color.Lerp(startColor, endColor, progress);
yield return null;
}
yield return new WaitForSeconds(delay);
}
}
This works great! however it takes about 6 seconds to start animating the next cube when I need to make it a 0.3 seconds delay only. That's my bad I didn't include the duration in the post but I edited it now. Thanks for comment
I am not sure to understand sorry. I don't have Unity so I can't test, sorry.
What's happening with the code I gave you? You should see the objects' color changing over time (3 seconds to change for a given color, 3 seconds to come back to original) one after the other, with a delay of 0.3 seconds between each of them.
BTW, I've fixed the computation of progress
, I made a mistake which should be fixed now.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Help instantiating from a for loop. 0 Answers
How to play animation (C#) 3 Answers
Animation at the end of the level 1 Answer