Search Unity

Bug NullReferenceException: Object reference not set to an instance of an object PlayerController.FixedU

Discussion in 'Scripting' started by tyronwei, Jan 15, 2021.

  1. tyronwei

    tyronwei

    Joined:
    Dec 19, 2020
    Posts:
    3
    Hello,

    So I am following the tutorial for lesson 6.2 on unity learn. My scripts have been exactly the same as the one that is shown in the tutorial except that my one does not work. The console window keeps telling me: "
    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.FixedUpdate () (at Assets/Scripts/PlayerController.cs:30)". And I have no clue where I went wrong. Please help me!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.     // Private variables
    8.     // [SerializeField] private float speed = 10.0f;
    9.     [SerializeField] private float horsePower = 0;
    10.     private float turnSpeed = 50.0f;
    11.     private float horizontalInput;
    12.     private float verticalInput;
    13.  
    14.     private Rigidbody playerRb;
    15.  
    16.     void Start()
    17.     {
    18.         playerRb.GetComponent<Rigidbody>();
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void FixedUpdate()
    23.     {
    24.         // Player inputs
    25.         horizontalInput = Input.GetAxis("Horizontal");
    26.         verticalInput = Input.GetAxis("Vertical");
    27.  
    28.         // We move the vehicle forward
    29.         //transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
    30.         playerRb.AddRelativeForce(Vector3.forward * horsePower * verticalInput);
    31.  
    32.         // Turning the vehicle
    33.         transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed * horizontalInput);
    34.  
    35.     }
    36. }
    37.  
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Code (CSharp):
    1. playerRb.GetComponent<Rigidbody>();
    you copied this code wrong, it should be
    Code (CSharp):
    1. playerRb = GetComponent<Rigidbody>();
     
  3. tyronwei

    tyronwei

    Joined:
    Dec 19, 2020
    Posts:
    3
    there is a rigidbody attached.
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Sorry check my post again, I edited it.
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Again, please reread my earlier post - your code is wrong.
     
  6. tyronwei

    tyronwei

    Joined:
    Dec 19, 2020
    Posts:
    3
    Thank you I see. Thank you so much
     
    PraetorBlue likes this.