I’m working on a small game project where an enemy is moving towards the player. Coming in contact with the enemy despawns the player and causes a game over. The game is pretty much functional aside from the enemy, as the player passes through the enemy rather than triggering a game over.
This is the error message I got:
NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/Scripts/GameManager.cs:20)
It appears to be an issue in the game manager script, but I’ll post the obstacle script too if that helps.
GAME MANAGER
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
public int score;
public int scoreTarget;
public TMP_Text scoreText;
public TMP_Text winText;
//***ABOVE IS FOR WIN***
private void Start()
{
winText.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
// If the esc key was pressed and released...
if (Input.GetKeyUp(KeyCode.Escape) == true)
{
// Quit the game (only works with built games)
Application.Quit();
}
//****BOTTOM CODE RELOADS A SCENE AFTER WINNING****
if (Input.GetKeyUp(KeyCode.Space) == true)
{
// Reload the scene
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
//****USE FOR GAME OVER****
public void Lose()
{
winText.gameObject.SetActive(true);
winText.text = "THERE IS NO ESCAPE\npress space to restart";
}
}
ENEMY/OBSTACLE
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ObstacleCheck : MonoBehaviour
{
private float dirX;
private float moveSpeed;
private Rigidbody2D rb;
private Vector3 localScale;
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
dirX = 1f;
moveSpeed = 3f;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
}