Hello everybody,
So, I was making a game where the player must roll a ball on a platform and if they were to fall, they would get a “Press R to try again” message. After pressing R, the level would restart. However, when I press R, I get a Null Reference Exception:
“NullReferenceException: Object reference not set to an instance of an object
PlayerController.LateUpdate () (at Assets/Scripts/PlayerController.cs:39)”
I double checked every line of code and I cannot find the problem. At the line of code where I get an exception, Im using an object of a class to access one of its functions, the object was already initialised. Would you help me pinpoint the error? Thank you in advance.
Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
private float verticalMov;
private float horizontalMov;
public float speed = 250, jumpSpeed = 15.0f, gravity = 10;
public int score;
public Text scoreText, winText, tryAgainText;
private Vector3 movement;
private Rigidbody rb;
public LoadNewLevel loadNewLevel;
void Start () {
rb = GetComponent<Rigidbody>();
score = 0;
}
void LateUpdate () {
horizontalMov = Input.GetAxis("Horizontal");
verticalMov = Input.GetAxis("Vertical");
movement = new Vector3(horizontalMov, 0.0f, verticalMov);
if (Input.GetButtonDown("Jump"))
{
//jumpSpeed = 5.0f;
movement.y = jumpSpeed;
}
rb.AddForce(movement * speed * Time.deltaTime);
if (transform.position.y < -10)
{
tryAgainText.text = ("Press R to try again");
}
if (Input.GetKeyDown(KeyCode.R) && transform.position.y < -10)
{
loadNewLevel.LoadNextLevel();
}
if (jumpSpeed > 0)
{
jumpSpeed -= gravity * Time.deltaTime;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Coins"))
{
other.gameObject.SetActive(false);
score++;
scoreText.text = "Score: " + score.ToString();
}
if (score > 4)
{
winText.text = ("YOU WIN!");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadNewLevel : MonoBehaviour {
public void LoadNextLevel() {
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}