用标准颜色表示方式为 Unity3D 改变颜色
搞定 material 的颜色不容易,
Color(r,g,b,a) 接受的是 0-1 的 float 值, 用 color.r += 0.1f 来形成渐变, 一直没达到目的
查到 Color32(r,g,b,a) 可以用 0-255 的 BYTE 值来表达, 比较符合惯常用法
using UnityEngine; using System.Collections; public class ouyColorGamma : MonoBehaviour { private Renderer render; private Color32 color = new Color32(122, 1, 1, 1); void Start() { Example (); render = GetComponent<Renderer>(); render.material.color = color; } void Example () { //print (color.gamma); print (" r:" +color.r + " g:" +color.g + " b:"+color.b); } }
下面例程可以通过键盘 r, g, b, a 实现渐变色
using UnityEngine; using System.Collections; public class ouyChangeCubeColor32 : MonoBehaviour { private Color32 altColor; private Renderer rend; //I do not know why you need this? void Example() { altColor.g = 0; altColor.r = 0; altColor.b = 0; altColor.a = 255; } void Start () { //Call Example to set all color values to zero. Example(); //Get the renderer of the object so we can access the color rend = GetComponent<Renderer>(); //Set the initial color (0f,0f,0f,0f) rend.material.color = altColor; } void Update() { if (Input.GetKeyDown (KeyCode.G)){ //Alter the color altColor.g += 1; if(altColor.g > 255) altColor.g = 0; //Assign the changed color to the material. rend.material.color = altColor; } if (Input.GetKeyDown (KeyCode.R)){ //Alter the color altColor.r += 1; Debug.Log("Color.r = "+ altColor.r); if(altColor.r > 255) { altColor.r = 0; } //Assign the changed color to the material. rend.material.color = altColor; } if (Input.GetKeyDown (KeyCode.B)){ //Alter the color altColor.b += 1; if(altColor.b > 255) altColor.b = 0; //Assign the changed color to the material. rend.material.color = altColor; } if (Input.GetKeyDown (KeyCode.A)){ //Alter the color altColor.a += 1; if(altColor.a > 255) altColor.a = 0; //Assign the changed color to the material. rend.material.color = altColor; } } }
以下参考 《unity3d_颜色转换器》 实现 16进制转为 byte : rgb
using UnityEngine; using System.Collections; /** * <summary> * <para>作者:巨星电艺</para> * <para>编写日期:巨星电艺</para> **/ public class ouyChangObjColor : MonoBehaviour { private float weight = 0f; // Use this for initialization void Start () { Color c = HexToColor ("66ccff"); transform.GetComponent<MeshRenderer>().material.color = HexToColor ("ffcc00");// new Color(0, 0,1,1); } // Update is called once per frame void Update () { if (Input.GetKeyDown (KeyCode.F2)) { //Application.LoadLevel(0); // weight = Random.Range(0, 100); weight += 0.10f; if(weight > 1) weight = 0; transform.GetComponent<MeshRenderer>().material.color = new Color(weight, 1,0,1); Debug.LogFormat("Color = {0}", weight); } } public static Color HexToColor(string hex) { byte r = byte.Parse (hex.Substring (0, 2), System.Globalization.NumberStyles.HexNumber); byte g = byte.Parse (hex.Substring (2, 2), System.Globalization.NumberStyles.HexNumber); byte b = byte.Parse (hex.Substring (4, 2), System.Globalization.NumberStyles.HexNumber); return new Color32(r,g,b,255); } }
浙公网安备 33010602011771号