Keep getting 2 null exceptions one for animator another for charactercontroller. Isn’t consistant, latest one is animator. CharacterController isn’t working.
using UnityEngine;
using System.Collections;
using System;
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
Animator animator;
CharacterController characterController;
[System.Serializable]
public class AnimationSettings
{
public string verticalVelocityFloat = "Speed";
public string horizontalVelocityFloat = "Direction";
public string JumpBool = "isJumping";
public string GroundedBool = "isGrounded";
}
[SerializeField]
public AnimationSettings animations;
[System.Serializable]
public class PhysicsSettings
{
public float gravityModifier = 9f;
public float baseGravity = 50f;
public float resetGravityValue = 5f;
}
[SerializeField]
public PhysicsSettings physics;
[System.Serializable]
public class MovementSettings
{
public float jumpSpeed = 5f;
public float jumpTime = 0.25f;
}
[SerializeField]
public MovementSettings movement;
bool jumping;
bool resetGravity;
float gravity;
void start()
{
animator = GetComponent<Animator> ();
characterController = GetComponent<CharacterController> ();
SetupAnimator ();
}
void Update()
{
ApplyGravity ();
Animate (Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"));
}
public void Animate(float Speed, float Direction)
{
animator.SetFloat (animations.verticalVelocityFloat, Speed);
animator.SetFloat (animations.horizontalVelocityFloat, Direction);
animator.SetBool (animations.GroundedBool, characterController.isGrounded);
animator.SetBool (animations.JumpBool, jumping);
}
public void ApplyGravity()
{
if (!characterController.isGrounded)
{
if (!resetGravity)
{
gravity = physics.resetGravityValue;
resetGravity = true;
}
gravity += Time.deltaTime * physics.gravityModifier;
}
else
{
gravity = physics.baseGravity;
resetGravity = false;
}
Vector3 gravityVector = new Vector3 ();
if (!jumping)
{
gravityVector.y -= gravity;
}
else
{
gravityVector.y = movement.jumpSpeed;
}
characterController.Move(gravityVector * Time.deltaTime);
}
public void Jump()
{
if (jumping)
return;
if (characterController.isGrounded)
{
jumping = true;
StartCoroutine (StopJump ());
}
}
IEnumerator StopJump()
{
yield return new WaitForSeconds (movement.jumpTime);
jumping = false;
}
//Set animator with the child avatar
public void SetupAnimator()
{
Animator[] animators = GetComponentsInChildren<Animator> ();
if (animators.Length > 0)
{
for (int i = 0; i < animators.Length; i++)
{
Animator anim = animators [i];
Avatar av = anim.avatar;
if (anim != animator)
{
animator.avatar = av;
Destroy (anim);
}
}
}
}
}
