I am calling a function from a different script script and I am getting this error "NullReferenceException: Object reference not set to an instance of an object PlayerCollision.OnTriggerEnter (UnityEngine.Collider collision)" What do I do? This is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
void OnTriggerEnter(Collider collision)
{
if(collision.gameObject.CompareTag("BlackSnow"))
{
GameManager.Instance.blackSnowEvent(collision.gameObject);
}
}
}
this is the code in the script where the function is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public ParticleSystem blackSnowParticleSystem;
private bool snowActivated = false;
public int duration = 5;
#region Singleton
private static GameManager instance;
public static GameManager Instance
{
get
{
return instance;
}
}
void Start()
{
}
IEnumerator wait(int arg){
yield return new WaitForSeconds(arg);
}
public void blackSnowEvent(GameObject snowTrigger){
if(snowActivated == false){
snowActivated = true;
snowTrigger.SetActive(false);
blackSnowParticleSystem.Play();
Debug.Log(duration);
StartCoroutine(wait(duration));
blackSnowParticleSystem.Stop();
snowActivated = false;
}
}
#endregion
}
CodePudding user response:
The member GameManager.Instance
is never assigned, so it is null at runtime. You are attempting to invoke the member blackSnowEvent
on a null reference. To solve, GameManager.Instance
must be assigned before you attempt to invoke its members
CodePudding user response:
The error is not because you are calling a method from a different script, it is because you are trying to pass a null
value as an argument to it.
The error is because in your if
statement in your void OnTriggerEnter(Collider collision)
method, you are trying to check if the collided object has a tag "BlackSnow" or not. But that collider doesn't necessarily be something, it may also be null. Hence, Hence modify the if
statement to this.
if(collision != null && collision.gameObject.CompareTag("BlackSnow")) {
GameManager.Instance.blackSnowEvent(blackSnowParticleSystem, collision.gameObject);
}
In this scenario, if the compiler detects that the collision object is null, then it doesn't proceed further, therefore doesn't throw any error.