unity3d鼠标经过物体时变颜色,离开时恢复
using UnityEngine; using System.Collections; public class MouseEvent_Color : MonoBehaviour { //物体初始颜色 private Color CubeColor; private Texture CubeTexture; private GameObject ObjCube; // Use this for initialization void Start () { ObjCube = GameObject.Find("Cube"); ObjCube.renderer.material.shader = Shader.Find("Diffuse"); CubeColor = ObjCube.renderer.material.GetColor("_Color"); Debug.LogError("材质球颜色:"+CubeColor); CubeTexture = renderer.material.GetTexture("Cube"); } // Update is called once per frame void Update () { } /// <summary> /// 鼠标经过 /// </summary> //void OnMouseOver() //{ // // cubeobj.renderer.material.color = Color.red; // renderer.material.color = Color.red; //} /// <summary> /// 鼠标进入 /// </summary> void OnMouseEnter() { renderer.material.color = Color.red; } //鼠标离开 void OnMouseExit() { // renderer.material.SetTexture("Cube",CubeTexture); renderer.material.color = CubeColor; } }
Shader:材质球-点击“Edit”-“OPen compiled shader”
Shader "Diffuse" { Properties { _Color ("Main Color", Color) = (1,1,1,1) _MainTex ("Base (RGB)", 2D) = "white" {} } SubShader { Tags { "RenderType"="Opaque" } LOD 200 Pass { Name "FORWARD" Tags { "LightMode" = "ForwardBase" } Program "vp" {
Color CubeColor = ObjCube.renderer.material.GetColor("Object名称"); //这样写无法获取物体真实颜色,得到的是(0,0,0,0) ,正确方法是,ObjCube.renderer.material.shader = Shader.Find("Diffuse"); CubeColor = ObjCube.renderer.material.GetColor("_Color");
参考:http://www.cnblogs.com/martianzone/p/3394092.html
http://www.cnblogs.com/Gnepner/archive/2013/04/10/3012705.html