Unity C#: I'm getting a NullReferenceException and I'm not sure how to fix/improve it

44 Views Asked by At

I'm making a simple score-based shooting game with 3D graphics in Unity. Most of the main functionality is working, but I am having trouble with the implementation of the scoring system that's causing the NullReferenceException to occur.

To help describe the issue at hand, I have pasted the code for the player, basic enemy and the scoring system for the game.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Player : MonoBehaviour
{
    // Variables set for the object; links object to other objects within the project
    [SerializeField] private float playerSpeed = 10;
    [SerializeField] private GameObject bullet;
    [SerializeField] private Transform bulletSpawn;
    [SerializeField] private GameObject explosion;
    [SerializeField] private GameObject restart;
    private int playerScore;
    private Score _score;

    // Start is called before the first frame update
    void Start()
    {
        _score = GameObject.Find("Score").GetComponent<Score>();
    }

    // Update is called once per frame
    void Update()
    {
        // Variables for movement inputs
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        float verticalInput = Input.GetAxisRaw("Vertical");
        // Player's position is 'transformed' every frame 
        transform.position += new Vector3(horizontalInput * playerSpeed * Time.deltaTime, 0, verticalInput * playerSpeed * Time.deltaTime);

        // Shoot input
        if (Input.GetButtonDown("Jump"))
            Instantiate(bullet, bulletSpawn.position, bulletSpawn.rotation);

        // Quit game input
        if (Input.GetButtonDown("Cancel"))
            UnityEngine.SceneManagement.SceneManager.LoadScene("Title");
    }

    // Method for incrementing the player's score
    public void ScoreUp(int points)
    {
        playerScore += points;
        _score.applyScore(playerScore);
    }

    // Method for when this certain object collides with another
    void OnTriggerEnter(Collider other)
    {
        // When the object collides with a tagged object "enemy"
        if (other.CompareTag("Enemy"))
        {
            // Spawn two other game objects and destroy this one
            Instantiate(explosion, transform.position, transform.rotation);
            Instantiate(restart, transform.position, transform.rotation);
            Destroy(gameObject);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BasicEnemy : MonoBehaviour
{
    [SerializeField] private float enemySpeed = 9;
    [SerializeField] private float detonateTimer = 3;
    [SerializeField] private float randomSpawn = 6;
    [SerializeField] private GameObject explosion;
    [SerializeField] private int scoreGain = 1;
    private Player _player;

    // Start is called before the first frame update
    void Start()
    {
        // The object spawns at a random distance away from its spawn point
        transform.position += new Vector3(Random.Range(randomSpawn, -randomSpawn), 0, 0);
        _player = GameObject.Find("Player Cone").GetComponent<Player>();
    }

    // Update is called once per frame
    void Update()
    {
        // Enemy's position is 'transformed' according to game time
        transform.position = transform.position - new Vector3(0, 0, enemySpeed * Time.deltaTime);
        // A timer dictates the amount of time the enemy object remains spawned within the scene
        detonateTimer -= Time.deltaTime;
        if (detonateTimer <= 0)
            Destroy(gameObject);
    }

    // Method for when this certain object collides with another
    void OnTriggerEnter(Collider other)
    {
        // When the object collides with a tagged object "bullet"
        if (other.CompareTag("Bullet"))
        {
            // Spawns the explosion particle and despawns the enemy
            if (_player != null)
            {
                _player.ScoreUp(scoreGain);
            }
            Instantiate(explosion, transform.position, transform.rotation);
            Destroy(gameObject);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Score : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI _score;

    // Start is called before the first frame update
    void Start()
    {
        _score.text = "0";
    }

    // Method within the score manager to add to the score counter on UI
    public void applyScore(int playerScore)
    {
        _score.text = playerScore.ToString();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

This is the tutorial I used to try and implement this specific feature in my game with.

I recognized via the errors I was receiving through the editor's console that the error's popped up in the lines in each start function which tries to look for the corresponding object within the game scene. And no matter what, the error seems to pop up.

I'm not exactly great at sorting out an issue such as this, so I'm wondering how this issue could be fixed and maybe if I'm better off with going for a different method of implementing the scoring system instead.

0

There are 0 best solutions below