Unity: Hierarchy filling up with "New Game Object" objects

What causes this and how to fix it

This is a bug that occurred in my new game "Survivesmith" a while back. I've been ignoring it for too long and today, I decided to find a fix finally.

I searched for a solution online and didn't quite get the answer. So I asked ChatGPT if it could find it. It certainly did and fixed my problem!

Bug:

I have a script that spawns enemies every few seconds. While this script is doing its job, it also started creating unwanted game objects with the name "New Game Object" every time an enemy is spawned. It fills up the hierarchy pretty quickly since they are created at the root. While this didn't throw any performance impact during development, it surely would in an extended play session. Plus, it simply makes debugging during runtime a bit harder.

Fix:

I have a line of code that instantiates a new game object to be assigned an enemy later on. This was the culprit. This is what that line looks like:

GameObject pickedEnemy = new();

In order to fix the whole issue, the only thing I had to do was to assign it "null" instead of "new()". In the wise words of ChatGPT: "This way, pickedEnemy will be null until you find a valid prefab to assign to it. If no valid prefab is found, it will remain null, and you won't encounter the issue of creating unnecessary game objects in the hierarchy." So here's what the fixed line of code looks like:

GameObject pickedEnemy = null;

I hope someone finds this useful!