1
Basically with this code I’m trying to make the color and emission color of the object change systematically at a predetermined time, but whenever the totalTimer
comes around the value of 300 colors basically stop changing. I am using the 2019.2.5f1 version of Unity for this project. So someone knows what’s going on?
P.S.: One thing I noticed was that every time I change the value of frameTimer
for higher values the value at which the totalTimer
changes too, but how I’m using the frameTimer
as a frame counter, it would not be beneficial to have a value above 60.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorChanger : MonoBehaviour
{
#region State Variables
//state variables
private int frameTimer;
private int totalTimer = 0;
private int newSpeed;
private int colorChanger;
#endregion
#region Properties
public int NewSpeed
{
get => newSpeed;
}
#endregion
Renderer rend;
public Color[] colors;
private Color newColor, oldColor;
// Start is called before the first frame update
void Start()
{
rend = GetComponent<Renderer>();
newSpeed = 40;
#region Color instantion
colors = new Color[9];
colors[0] = (new Color(0.5098f, 0.3254f, 0.1882f)); //brown
colors[1] = (new Color(0.8941f, 0.9137f, 0.0392f)); //yellow
colors[2] = (new Color(0.1607f, 0.8705f, 0.9568f)); //light blue
colors[3] = (new Color(1f, 0.5215f, 0.0745f)); //orange
colors[4] = (new Color(0.7607f, 0.2274f, 0.8588f)); //lightish purple
colors[5] = (new Color(0.3254f, 0.8588f, 0.2274f)); //green
colors[6] = (new Color(0.9568f, 0.2470f, 0.1607f)); //red
colors[7] = (new Color(0.7294f, 0.1490f, 0.1450f)); //crimson
colors[8] = (new Color(0.0705f, 0.3960f, 0.9019f)); //blue
#endregion
}
// Update is called once per frame
void Update()
{
frameTimer++;
colorChanger++;
if (frameTimer == 30)
{
SpeedChanger(totalTimer++); frameTimer = 0;
Debug.Log($"The Total Timer is {totalTimer}");
}
#region Color Update
if(colorChanger == newSpeed)
{
newColor = colors[Random.Range(0, colors.Length - 1)];
if(newColor == oldColor)
{
while(newColor == oldColor)
newColor = colors[Random.Range(0, colors.Length - 1)];
}
oldColor = newColor;
rend.material.SetColor("_Color", newColor);
rend.material.SetColor("_EmissionColor", newColor);
rend.material.EnableKeyword("_EMISSION");
colorChanger = 0;
//Debug.Log( $"\n {newColor} this is the frame color");
}
#endregion
}
private int SpeedChanger(int totalTimer)
{
switch(totalTimer)
{
case 85:
newSpeed = 30;
break;
case 165:
newSpeed = 25;
break;
case 200:
newSpeed = 20;
break;
case 300:
newSpeed = 15;
break;
}
return newSpeed;
}
}