通过脚本设置激活第三人称角色控制器

时间:2015-07-29 15:11:04

标签: unity3d

我已将3rd person character controller应用于头像,一切似乎都很好。

禁用头像游戏对象后,使用以下代码在运行时重新激活它:

public GameObject avatar;

void Start()
    {
        avatar.SetActive(true);
    }

我收到以下错误消息:

NullReferenceException: Object reference not set to an instance of an object
UnityStandardAssets.Characters.ThirdPerson.ThirdPersonCharacter.CheckGroundStatus () (at Assets/Standard Assets/Characters/ThirdPersonCharacter/Scripts/ThirdPersonCharacter.cs:217)
UnityStandardAssets.Characters.ThirdPerson.ThirdPersonCharacter.Move (Vector3 move, Boolean crouch, Boolean jump) (at Assets/Standard Assets/Characters/ThirdPersonCharacter/Scripts/ThirdPersonCharacter.cs:56)
UnityStandardAssets.Characters.ThirdPerson.ThirdPersonUserControl.FixedUpdate () (at Assets/Standard Assets/Characters/ThirdPersonCharacter/Scripts/ThirdPersonUserControl.cs:73)

当我点击它时,主错误实例似乎位于以下代码块中,与apply root motion一致:

void CheckGroundStatus()
{
    RaycastHit hitInfo;

    #if UNITY_EDITOR
    // Helper to visualise the ground check ray in the scene view.
    Debug.DrawLine( transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance) );
    #endif
    // 0.1f is a small offset to start the ray from inside the character.
    // It is also good to note that the transform position in the sample assets is at the base of the character.
    if ( Physics.Raycast( transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance ) )
    {
        m_GroundNormal = hitInfo.normal;
        m_IsGrounded = true;
        m_Animator.applyRootMotion = true;
    }
    else
    {
        m_IsGrounded = false;
        m_GroundNormal = Vector3.up;
        m_Animator.applyRootMotion = false;
    }
}

有人可以帮我理解原因吗?

2 个答案:

答案 0 :(得分:1)

看起来您没有从Unity Editor中分配Animator,而是从代码(功能开始)分配,但此代码未运行,因为它在场景开始时未启用。

其他问题可能是您从游戏对象中移除了Animator,其中包含 ThirdPersonCharacter 脚本。

答案 1 :(得分:0)

您只需要使用GetComponent

GetComponent<Animator>().applyRootMotion = true;

不要使用变量。