Unity开发:如何在不同GameObject的脚本中通过碰撞事件访问Animator
代码调整方案
你当前代码中anim = GetComponent<Animator>()仅会获取脚本挂载对象自身的Animator组件,要实现跨GameObject访问,可参考以下两种实现方案:
方案1:公共变量拖拽赋值(优先推荐)
该方案性能最高,出错概率最低,适合可以提前确定目标Animator所属对象的场景:
using UnityEngine; public class SmallDoor : MonoBehaviour { // 公开Animator变量,后续在Inspector面板中拖拽挂载了目标Animator的GameObject即可完成赋值 public Animator targetDoorAnim; private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { targetDoorAnim.SetBool("DoorOpen", true); } } // 可选扩展:离开触发区域时关闭门 private void OnTriggerExit(Collider other) { if (other.CompareTag("Player")) { targetDoorAnim.SetBool("DoorOpen", false); } } }
- 用
CompareTag替代直接判断tag字符串,性能更优,同时可避免拼写错误导致的隐性问题
方案2:运行时动态查找目标组件
适合无法提前拖拽赋值的动态生成对象场景:
using UnityEngine; public class SmallDoor : MonoBehaviour { private Animator targetDoorAnim; void Start() { // 示例:通过标签查找挂载了目标Animator的GameObject,可根据需求替换为Find等其他查找方法 GameObject doorObject = GameObject.FindGameObjectWithTag("SmallDoor"); if(doorObject != null) { targetDoorAnim = doorObject.GetComponent<Animator>(); } else { Debug.LogError("未找到标签为SmallDoor的目标对象,请检查标签配置"); } } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player") && targetDoorAnim != null) { targetDoorAnim.SetBool("DoorOpen", true); } } }
- 需要提前给带Animator的目标GameObject配置对应的标签,避免查找失败
- 动态查找性能低于方案1,非必要场景优先使用第一种实现
内容的提问来源于stack exchange,提问作者AMVkage
相关产品推荐
相关产品推荐

