unity入门学习日记:通过射线检测控制对象脚本的开关(准心指向物体开启高光)
- 高光效果的实现
- 控制高光的开关
高光效果的实现
使用unity资源商城中的OutlineEffect包实现高光效果
包里面有两个C#脚本:Outline和Outline Effect。将Outline应用到要实现高光的物体上,Outline Effect应用到摄像机上(这里的摄像机应该是游戏视角对应的摄像机)
此时进入游戏可以看到应用了Outline脚本的物体有高光效果,但是无法控制其开关
控制高光的开关
想要实现的效果:当屏幕中心的准心移动到有高光效果的物体上时,该物体发出高光,当移开时高光关闭。
在应用了Outline Effect组件的摄像机上新建名为“Hit Test”的组件脚本。内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using cakeslice;public class HitTest : MonoBehaviour
{public Outline pastframe = null;// Start is called before the first frame updatevoid Start(){}// Update is called once per framevoid Update(){RaycastHit hit;if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit)){if(hit.collider.gameObject.GetComponent()){if(pastframe){pastframe.enabled = false;hit.collider.gameObject.GetComponent().enabled = true;pastframe = hit.collider.gameObject.GetComponent();}else{hit.collider.gameObject.GetComponent().enabled = true;pastframe = hit.collider.gameObject.GetComponent();}}else {pastframe.enabled = false;pastframe = null;}}else{if(pastframe){pastframe.enabled = false;pastframe = null;}}}
}
有一个小问题就是如果在脚本的开头不加using cakeslice; 的话,在编译的时候会报错找不到名为Outline的类或者命名空间,这是因为Outline是在命名空间cakeslice中定义的类,加上之后就不会报错了。
补充一点: 像上面这样做,在运行游戏后会发现无论是否勾选Outline组件,有高光物体的高光都是默认开启的,如果需要保证脚本在游戏开始时保持关闭,可以在组件的Start()函数中添加一句this.enabled = false;