一个同学问:动画状态机中的动画上挂载得到脚本为什么可以获取Player身上的Player Controller组件的问题的解答:
校长答:
在Unity中,animator.GetComponent<PlayerController>(); 能够找到挂载在Player身上的PlayerController脚本组件的原因是因为 GetComponent 方法的设计和使用方式。具体来说,GetComponent 方法用于获取当前游戏对象(即 animator 所属的游戏对象)上的指定组件。
在你的代码中,animator 是一个 Animator 组件的实例,而 Animator 组件是挂载在某个游戏对象上的。通过 animator.gameObject 可以获取到这个游戏对象,然后使用 GetComponent<PlayerController>() 方法就可以获取到这个游戏对象上挂载的 PlayerController 组件。 这种设计允许你在不直接访问游戏对象的情况下,通过 Animator 组件间接获取到挂载在其上的其他组件。这是Unity中组件系统的一部分,使得开发者可以通过不同的组件接口来操作和访问游戏对象的属性和方法。 animator.GetComponent<PlayerController>(); 能够找到挂载在Player身上的PlayerController脚本组件,是因为 GetComponent 方法的设计允许通过组件接口间接获取到挂载在其上的其他组件。 简单来说就是如果你有一个组件挂载在人物上,你就可以通过这个组件对象来get到组件对象所挂载的对象的组件对象,是不是有点绕?慢慢体会。
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class HurtAnimation : StateMachineBehaviour
- {
- // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
- override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
- {
- }
- // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
- override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
- {
- }
- // OnStateExit is called when a transition ends and the state machine finishes evaluating this state
- override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
- {
- animator.GetComponent<PlayerController>();
- }
复制代码
|