unity材质切换,主要运用射线选择物体,通过获取组建来替换材质,还有UI的调用函数。
操作:进入工程,点击物体,然后点击点击UI“yellow”“blue”“red”,点击的物体就可以切换材质
using UnityEngine;
using System.Collections;
public class ControlMaterial : MonoBehaviour {
private GameObject objRayHit;
private Material matRayHit;
private Camera myCamera;
public Material matRed;
public Material matBlue;
public Material matYellow;
// Use this for initialization
void Start () {
myCamera = Camera.main;
}
// Update is called once per frame
void Update () {
//定义射线
Ray rays = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hits;
if (Input.GetMouseButton(0)) {
if (Physics.Raycast(rays, out hits)) {
objRayHit = hits.collider.gameObject;
//获取组件
matRayHit = hits.collider.gameObject.GetComponent<MeshRenderer>().material;
}
}
}
//定义函数,通过UI按钮调用
public void RedMaterial() {
objRayHit.GetComponent<MeshRenderer>().material = matRed;
}
public void BlueMaterial() {
objRayHit.GetComponent<MeshRenderer>().material = matBlue;
}
public void YellowMaterial()
{
objRayHit.GetComponent<MeshRenderer>().material = matYellow;
}
public void OwnMaterial()
{
objRayHit.GetComponent<MeshRenderer>().material = matRayHit;
}
}
工程的下载地址链接:链接: https://pan.baidu.com/s/1qYbbSmw 密码: 91zi 。
unity版本:Unity 5.1.2f1 (64-bit)
大家有好的想法,可以写一下