My bullet is being set to null

Hello,
I am on section 5.30 and 5.31 and I am getting an error that my bullet is not being instantiated when I click. The error reads, “ArgumentException: The Object you want to instantiate is null.” When I put my prefab into the hierarchy, the bullet works, but if it is not in the hierarchy, then it does not work. I am not sure what I did wrong.

This is my code for the bullet
void OnFire(InputValue value)
{
if (!isAlive) { return; }
Instantiate(bullet, gun.position, transform.rotation);
}

Thanks

Hi Cork_Emperor,

In which course are you?

Sorry for the confusion. I am in Complete Unity 2D Developer: Create Your Own 2D Games Using Unity C#

Please check if something is assigned to the “Bullet” field in the Inspector. Make sure it is a prefab, not a game object in your Hierarchy.

The bullet in the Hierarchy very likely gets destroyed at runtime, and if you try to spawn a destroyed/non-existent object, you get an error message.

Hello Nina,
I don’t think I have any game objects in the hierarchy assigned as a bullet, only a prefab, but I still get the same error.

The following screenshot is what I see in unity:

Have you tried to remove the object from the Bullet field and to reassign it?

If so, have you already tried to add Debug.Logs to your code to see what is going on during runtime? And have you already compared your code to the Lecture Project Changes which can be found in the Resources of this lecture? Maybe your code tries to destroy the bullet prefab at runtime or sets the field to null.

Hello Nina ,
I am confused by what you mean removing the object from the bullet field and reassigning it. I tried debug.llogs in my code and all I see is the same error message in the console. Also, for some reason, I can’t see the lecture project change for Complete Unity 2D Developer: Create Your Own 2D Games Using Unity C# section 5.31. Please tell me what I am doing wrong.

Thank you

You have this line of code:

Instantiate(bullet, gun.position, transform.rotation);

The bullet variable is null by default. null means that there is no object reference. In Rick’s version of this game, we exposed the bullet variable in the Inspector, and we assigned a prefab to this variable.

If you added Debug.Logs but see the same messages as before, this means that the Debug.Log messages were not logged into your Console. And that means that the code blocks where you added Debug.Log did not get executed. Without knowing where you added Debug.Log, it is impossible for me to tell if you did anything wrong.

Have you already tried to rewatch the video at least one more time? Maybe a detail is missing in your project.

Ok I looked over the video and I realized I accidentally had a line of code in Start() that messed up the whole thing. Thank you for your help!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms