首页 > 代码库 > unity3d鼠标经过物体时变颜色,离开时恢复

unity3d鼠标经过物体时变颜色,离开时恢复

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 onm ouseOver()
    //{
 
    //    // 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”

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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