赞
踩
想要隐藏/显示物体,最简单粗暴的方法是使用SetActive方法,但是这会导致其挂载的脚本也一起失效。
如果单单只是想让游戏物体看不见,可以利用GetComponent方法
这是要隐藏的物体的对象:
private GameObject hideObject;
单个物体隐藏方法:
hideObject.GetComponent<Renderer>().enabled = false;
物体和它的子物体一起隐藏的方法:
foreach (Renderer renderer in hideObject.GetComponentsInChildren<Renderer>())
{
renderer.enabled = false;
}
显示物体方法同理。
再加其他细节的完整代码:
(可以同时隐藏/显示多个物体和它的子物体)
using UnityEngine; /// <summary> /// 隐藏/显示物体 /// </summary> public class HideOrShowObject : MonoBehaviour { [Header("要隐藏的物体")] [SerializeField] private GameObject[] hideObjects; [Header("要显示的物体")] [SerializeField] private GameObject[] showObjects; /// <summary> /// 隐藏物体 /// </summary> protected void Hide() { foreach (GameObject hObject in hideObjects) { foreach (Renderer renderer in hObject.GetComponentsInChildren<Renderer>()) { renderer.enabled = false; } } } /// <summary> /// 显示物体 /// </summary> protected void Show() { foreach (GameObject sObject in showObjects) { foreach (Renderer renderer in sObject.GetComponentsInChildren<Renderer>()) { renderer.enabled = true; } } } }
很好,方法有了,再写个脚本继承它,使玩家进入触发器时触发方法。
完整代码:
using UnityEngine; /// <summary> /// 挂在触发器下 /// 隐藏/显示物体 /// </summary> public class TriggerHOrSObj : HideOrShowObject { [Header("控制触发类型")] [Tooltip("anyState:进入/离开触发器都可以触发\ntriggerEnter:进入触发器时触发\ntriggerExit:离开触发器时触发")] [SerializeField] private TriggerType triggerType = TriggerType.anyState; private void OnTriggerEnter(Collider other) { if (triggerType == TriggerType.triggerEnter || triggerType == TriggerType.anyState) { Hide(); //Show(); } } private void OnTriggerExit(Collider other) { if (triggerType == TriggerType.triggerExit || triggerType == TriggerType.anyState) { Hide(); //Show(); } } } /// <summary> /// 触发器触发条件类型 /// </summary> public enum TriggerType { anyState, triggerEnter, triggerExit }
效果图:
看都看了,点个赞呗~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。