Hello guys I have problem where my FixedUpdate() on movment is called before the Start() function. Afterwards the game runs fine. But there is an exception thrown. From the Documentation it should be clear however that Start() will always be called before the FixedUpdate(). The GameObject this happens on is instantiated if that makes a difference.
Help would greatly appreciated and maybe it will help someone else too.
Here is the Error I get:
UnassignedReferenceException: The variable rb2d of CharacterMovement has not been assigned.
You probably need to assign the rb2d variable of the CharacterMovement script in the inspector.
UnityEngine.Rigidbody2D.get_velocity () <0x151247b0 + 0x0005f> in <0938a4547c9748338e40726420dfbb1d>:0
CharacterMovement.move (UnityEngine.Vector2 velocity) (at Assets/Scripts/CharacterMovement.cs:25)
PlayerMovement.move () (at Assets/Scripts/PlayerMovement.cs:20)
PlayerMovement.FixedUpdate () (at Assets/Scripts/PlayerMovement.cs:12)
Here are the relevant code snippets: Class Movement
using UnityEngine;
[RequireComponent(typeof(CharacterMovement))]
public class PlayerMovement : MonoBehaviour {
private CharacterMovement characterMovement;
private void Start() {
characterMovement = GetComponent<CharacterMovement>();
}
private void FixedUpdate() {
move();
}
public void move() {
float horizontalMovement = Input.GetAxisRaw("Horizontal");
float verticalMovement = Input.GetAxisRaw("Vertical");
characterMovement.resolveDirection(horizontalMovement, verticalMovement);
characterMovement.move(new Vector2(horizontalMovement, verticalMovement));
}
Class CharacterMovement
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class CharacterMovement : MonoBehaviour {
[SerializeField] protected float moveSpeed;
[HideInInspector] public Rigidbody2D rb2d;
[SerializeField] public Direction direction;
[HideInInspector] public bool readyToMove;
[HideInInspector] public Animator animator;
private void Start() {
animator = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
readyToMove = true;
}
public void move(Vector2 velocity) {
if (readyToMove) {
rb2d.velocity = velocity * moveSpeed;
rb2d.velocity = Vector2.ClampMagnitude(rb2d.velocity, moveSpeed);
playWalkingAnimation();
}
//Stop animation if player doesn't move
if (rb2d.velocity == Vector2.zero) {
animator.speed = 0;
}
}
public void stopMovement() {
rb2d.velocity = Vector2.zero;
}