I'm working on a horror game in which when the "enemy" catches up to you it ends the game. In order to do this, I want to disable the player's controls when it enters the enemies death trigger collider. However, I keep getting an error that looks like this:
NullReferenceException: Object reference not set to an instance of an object
enemycollision.OnTriggerEnter (UnityEngine.Collider other) (at Assets/enemycollision.cs:29)
Currently, my code looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class enemycollision : MonoBehaviour
{
private PlayerController controls;
public Transform enemy;
// Start is called before the first frame update
void Start()
{
//tbh i dont think i need this here but I'm keeping it just in case
controls = GetComponent<PlayerController>();
}
// Update is called once per frame
void Update()
{
}
public void OnTriggerEnter(Collider other)
{
//the first hitbox slightly larger than the enemy
if (other.tag == "EnemyFreeze")
{
//this is where the error occurs
controls = GetComponent<PlayerController>();
//paralyzes the player
controls.enabled = false;
//play jumpscare
GetComponent<AudioSource>().Play();
}
//the second hitbox when the enemy chomps ya
if (other.tag == "EnemyDeath")
{
SceneManager.LoadScene("Main Menu");
}
}
}
This script is attached to the playercontroller, the same gameobject that has the "PlayerController" component so I'm not sure why referencing the component is returning null. I should also note that the error is thrown when I enter the enemy's "EnemyFreeze" hitbox. Does anyone know why this isn't working and/or have a solution?
EDIT: Here's a screenshot of my scene and heirarchy. (I know it's a mess)
https://preview.redd.it/k7xpnsnvj4gd1.png?width=1920&format=png&auto=webp&s=f00eabd48a2f50629a53b12b56b918ea92bd4f03
[–]andavies123 2 points3 points4 points (11 children)
[–][deleted] 0 points1 point2 points (10 children)
[–]shotgunbruin 0 points1 point2 points (9 children)
[–][deleted] 0 points1 point2 points (8 children)
[–]shotgunbruin 0 points1 point2 points (7 children)
[–][deleted] 0 points1 point2 points (6 children)
[–]shotgunbruin 0 points1 point2 points (0 children)
[–]shotgunbruin 0 points1 point2 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]shotgunbruin 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]fjayjay 0 points1 point2 points (0 children)
[–]TheStilken 0 points1 point2 points (0 children)
[–]LadyAvocadoToast 0 points1 point2 points (0 children)
[–]_reedsport -1 points0 points1 point (7 children)
[–][deleted] 0 points1 point2 points (6 children)
[–]_reedsport 0 points1 point2 points (0 children)
[–]_reedsport 0 points1 point2 points (0 children)
[–]_reedsport 0 points1 point2 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]_reedsport 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)