0

I'm new to C# and Unity. In the line carMain.AddForce(appliedHoverForce, ForceMode.Acceleration); gives this error messege: NullReferenceException: Object reference not set to an instance of an object. I can't seem to find the problem and how do I fix it?. Here is the code.

using NiceCar = UnityEngine.Rigidbody;
using System;
using UnityEngine;
using System.Collections;
using Random = UnityEngine.Random;

public class HoverMotor : MonoBehaviour{
  [Header("Hover Car Settings")]
  // Hover force of a car
  public float hoverForce = 65f;
  // Hover height of a car
  public float hoverHeight = 3.5f;

  private NiceCar carMain;

  public Transform carBody;

  void FixedUpdate()
  {
      UpdateFloating();
  }

  private void UpdateFloating()
  {
      Ray ray = new Ray(transform.position, -transform.up);
      RaycastHit hit;

      if (Physics.Raycast(ray, out hit, hoverHeight))
      {
          float proportionalHeight = (hoverHeight - hit.distance) / hoverHeight;
          Vector3 appliedHoverForce = Vector3.up * (proportionalHeight * (hoverForce + 
          hoverForce * Random.Range(1f, 1.25f)));
          carMain.AddForce(appliedHoverForce, ForceMode.Acceleration);
      } 
  }
}
  • You've not instantiated `carMain`. If `NiceCar` is a reference type (i.e. a class) then it will be initialized as `null` until you assign an instance to it. – ProgrammingLlama Jul 09 '21 at 08:53
  • Initialize NiceCar OnStart(){} or make it public and assign it inside Unity Editor – VisDesign Jul 09 '21 at 12:24

0 Answers0