0

Script Example:

public class Example : MonoBehaviour
{
  public ParticleSystem particles;
  private GameObject prefab;

  void Update()
  {
  
  // Finds object with script attached, once it spawns into scene
  if (FindObjectsOfType<AnotherScript>().Length != 0)
  {
    prefab = GameObject.Find("ObjectThatSpawns");
    particles.transform.position = prefab.transform.position
  }
}

This code was working flawlessly until it randomly stopped for no reason. I haven't changed anything about it or anything associated with it. Now I get a NullReferenceException.

I've transferred it into multiple different scripts and still gives the error.

NOTE: The NullReference is pointed at the "particles.transform.position = prefab.transform.position"

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Koast
  • 1
  • 2
  • Null reference exceptions are pretty clear. It means you are missing an assigned reference to an object. Your `GameObject.Find` is failing as it can not find an object by the name `ObjectThatSpawns`. Check out [this thread](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). – TEEBQNE May 13 '21 at 19:53

1 Answers1

0

Try it may be fixed..

public class Example : MonoBehaviour
{

  [SerializeField]ParticleSystem particles;
  [SerializeField] GameObject prefab;

  void LateUpdate()
  {
  
  // Finds object with script attached, once it spawns into scene
  if (FindObjectsOfType<AnotherScript>().Length != 0)
  {
    prefab = GameObject.Find("ObjectThatSpawns");

    if (prefab != null)
     particles.transform.position = prefab.transform.position
     
  }

}
CptNaed
  • 68
  • 1
  • 11
  • 1
    and what if `particles` is `null`? Also note: yes, this avoids the exception **BUT** this still doesn't make your code work as expected ... the exception is **desired** because it means something in your code is broken, behaving unexpected. Your solution here would just hide the issue .. good luck debugging then until you find the place where something misbehaved ;) – derHugo May 13 '21 at 19:57