- Home /
How to randomly change a color on an object in C#
Hi Gurus
Can you please assist me, i want to change a color on an object during runtime. I have the code and its working but i have put it in the Update function which changes the color of the object quickly and i was hoping for it to take at least a second or so before changing to anther color. He is the code below:
// Update is called once per frame
void Update () {
// pick a random color
Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f );
// apply it on current object's material
renderer.material.color = newColor;
}
Answer by Waffle842 · Oct 18, 2013 at 06:04 PM
{
public float timer = 0.0f;
void Start ()
{
}
void Update ()
{
timer += Time.deltaTime;
if (timer >= 2.0f)//change the float value here to change how long it takes to switch.
{
// pick a random color
Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f );
// apply it on current object's material
renderer.material.color = newColor;
timer = 0;
}
}
}
or you could put in a timer. not the most elegant solution...but still.
Answer by Piflik · Sep 07, 2012 at 03:55 PM
Have a look at InvokeRepeating().
Hi Philipp
and where would i put the InvokeRepeating function inside Update?, cause when i put it there its not effective
Regards; V
Please don't post comments as answers.
You want to call InvokeRepeating() only once, so either put it in Start()/Awake(), if you want it to begin changing the color immediately, or use some other method to trigger it (for example OnCollision) and wrap it into an if statement, so you can prevent it from being called again while it is already running.
Hi Piflik
I have put it in the Awake method and it working fine...thanks :)
Regards; V
if you vote down and comment on the answer that shouldn't be an answer and if I come near by I will upvote your comment and convert answer in to a comment
I have downvoted the answer, ...
Your answer
