Skip to content

Instantly share code, notes, and snippets.

@belzecue
Created April 27, 2019 15:33
Show Gist options
  • Save belzecue/c30e50a9be2a1927e8867dda3c3c1b33 to your computer and use it in GitHub Desktop.
Save belzecue/c30e50a9be2a1927e8867dda3c3c1b33 to your computer and use it in GitHub Desktop.
Unity Tip #1: Color.HSVToRGB(h, s, v) produces smoother, more natural random colors than new Color(r, g, b)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorRotator : MonoBehaviour {
public GameObject objHSV, objPlainColor;
private Material objHSVMaterial, objPlainColorMaterial;
private float timeDelta;
private Rect rect = new Rect(10, 10, 0, 0);
private readonly GUIContent guiContent = new GUIContent("HSV coloring on the left, RGB on the right.");
private GUIStyleState guiStyleState;
private GUIStyle guiStyle;
// Use this for initialization
void Start () {
timeDelta = Random.value;
objHSV.GetComponent<Renderer>().sharedMaterial = objHSVMaterial = (new Material(Shader.Find("Standard")));
objPlainColor.GetComponent<Renderer>().sharedMaterial = objPlainColorMaterial = (new Material(Shader.Find("Standard")));
guiStyleState = new GUIStyleState() { textColor = Color.magenta };
guiStyle = new GUIStyle() { fontSize = 36, normal = guiStyleState };
}
private Color GetRandomHSVColor()
{
timeDelta += (Time.deltaTime / 100);
float h = Mathf.PerlinNoise(0.5f, 23.3f * timeDelta);
float s = Mathf.PerlinNoise(0.5f, 54.4f * timeDelta);
float v = Mathf.PerlinNoise(0.5f, 12.6f * timeDelta);
return Color.HSVToRGB(h, s, v);
}
private Color GetRandomColor()
{
float r = Mathf.PerlinNoise(0.5f, 23.3f * timeDelta);
float g = Mathf.PerlinNoise(0.5f, 54.4f * timeDelta);
float b = Mathf.PerlinNoise(0.5f, 12.6f * timeDelta);
return new Color(r, g, b);
}
// Update is called once per frame
void Update () {
timeDelta += (Time.deltaTime / 100);
objHSVMaterial.color = GetRandomHSVColor();
objPlainColorMaterial.color = GetRandomColor();
}
private void OnGUI()
{
GUI.Label(rect, guiContent, guiStyle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment