当前位置: 动力学知识库 > 问答 > 编程问答 >

unity3d - Setting Active a 3rd person character controller through script

问题描述:

I have applied a 3rd person character controller to an avatar, and everything seems fine.

Once I disable the avatar game object, and use the following code to re-activate it at run time:

public GameObject avatar;

void Start()

{

avatar.SetActive(true);

}

I get the following error message:

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)

When I click on it, the main error instance seems to be in the following block of code, in the line with 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;

}

}

Could someone please help me understand why?

网友答案:

It looks like you don't have assigned Animator from Unity Editor but from code (function Start) but this code didn't run because it wasn't enabled at beginning of scene.

Other problem might be that you removed Animator from Game Object where you have your ThirdPersonCharacter script.

分享给朋友:
您可能感兴趣的文章:
随机阅读: