system
1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorCube : MonoBehaviour
{
private int x = 0;
void Update()
{
}
void FixedUpdate()
{
while (x < 100)
{
Debug.Log("Color" + x);
GetComponent<Renderer>().material.color = Color.black;
GetComponent<Renderer>().material.color = Color.red;
GetComponent<Renderer>().material.color = Color.blue;
GetComponent<Renderer>().material.color = Color.yellow;
x++;
}
}
}
Hello, my color changes very quickly, which I don’t have time to see. I want to make the color change every second.
Ok, so your code has absolutely nothing to do with what you want to achieve.
-
Use GetComponent once in Awake and store the reference in a field in your class. It’s basic optimization thing, you should always do. Never call GetComponent in Update if you can avoid it.
-
Use Update instead of FixedUpdate because you are not doing any physics calculations
-
What is that “while” loop? Currently you are changing the color 400 times in first fixed update and then your code does absolutely nothing.
-
Changing a color 4 times like that will only display the last color, first three assignments can be thrown away
-
Below is a code that should do what you need
private Renderer renderer;
private void Awake()
{
renderer = GetComponent();
}
private float timer = 0;
private const float timeInterval = 1;
private void Update()
{
if(timer >= timeInterval)
{
ChangeColor();
timer = 0;
}
else
{
timer += Time.DeltaTime;
}
}
Edit: for some reason I can’t format the code correctly here, sorry.
You need to change the “while” to “if” because your’e on the FixedUpdate function.
Hope it helps
system
4
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
public class ColorChange : MonoBehaviour
{
private Renderer renderer;
private void Awake()
{
renderer = GetComponent<Renderer>();
}
private float timer = 0;
private const float timeInterval = 1;
private void Update()
{
if (timer >= timeInterval)
{
GetComponent<Renderer>().material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
timer = 0;
}
else
{
timer += Time.deltaTime;
}
}
}
This code is working.
Thanks @Casiell!!