Hi I can’t understand why my code is throwing a nullreferenceexception.
But basically I want to make it so in a spaceship game when I shoot an enemy, that it makes a particle spawn at their transform.
The code works when I find a specific gameobject and pass that in method, but I don’t understand why it throws the exception when I pass the gameobject the enemy script is attached to:
In the enemy.cs
private void OnParticleCollision(GameObject other)
{
Debug.Log("This is what other is: " + other);
Debug.Log("This is what gameobject is: " + gameObject);
particlesHandler = FindObjectOfType<ParticlesHandler>();
particlesHandler.SpawnExplosionParticles(this.gameObject);
Destroy(gameObject, 2f);
}
public class ParticlesHandler : MonoBehaviour
{
[SerializeField] GameObject explosionParticles;
public void SpawnExplosionParticles(GameObject objectToSpawnAt)
{
GameObject explosionvfx = Instantiate(explosionParticles,
objectToSpawnAt.gameObject.transform.parent.position, Quaternion.identity);
explosionvfx.transform.parent = objectToSpawnAt.transform;
}
}
I did a test and passed :
FindObjectOfType<PlayerController>().gameObject;
Which worked making the particle spawn the players ship.
This is the nullreference I’m getting:
NullReferenceException: Object reference not set to an instance of an object
ParticlesHandler.SpawnExplosionParticles (UnityEngine.GameObject objectToSpawnAt) (at Assets/Scripts/ParticlesHandler.cs:11)
Enemy.OnParticleCollision (UnityEngine.GameObject other) (at Assets/Scripts/Enemy.cs:21)
I can’t figure out why this is happening because gameobject in the enemy script does identify/find the correct gameobject that I have fired a laser at.
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:
drag it in using the inspector
code inside this script initializes it
some OTHER external code initializes it
? something else?
This is the kind of mindset and thinking process you need to bring to this problem:
Thank you for such a detailed response with practical wisdom for dealing with this issue for now and the future.
I was just in the middle of typing to you that I had tried a load of different steps including attaching visual studios debugger and looking at the values of the variables.
And then I thought I will try something else and then I noticed in my code:
In the objectToSpawnAt.gameObject.transform.parent.position, my players ship has a parent object, unlike the enemy ships don’t.
So even though the variables being passed had values. I’ve just realized I was trying to pass the transform to a parent of the enemy that doesn’t even exist.