GameObject is not added to the List

Hello there!

I’m writing a simple snake game. The snake’s body consists of several GameObjects (three by default, not counting the head). When starting the game, I want to add the body of the snake (its three objects) to the List. However, Unity gives me this error:
8415939--1112763--upload_2022-9-5_14-53-36.png

pointing to the last line in the code where I am trying to add an GameObject to the List.

At the same time, when I display the result of “GameObject.Find(bodyName)”, the game calmly finds this GameObject (as it should be):
8415939--1112772--upload_2022-9-5_15-0-48.png

However, when I try to add the same object to the List, the game starts to complain.

Here is the code snippet in question:
8415939--1112751--upload_2022-9-5_14-48-55.png

Sorry for such stupid questions. I just ran out of solutions. I wouldn’t even think that I’d be stuck on such a trifle

Null errors are one of the most common errors!

  1. Find out what is null
  2. Find out why it’s null
  3. Fix it

The error tells you line 41. But, you didn’t use code tags posting your full code, so normally you’d only guess.
But, I already know what is wrong.

  1. Your list is null.
  2. You didn’t initialize it.
  3. Initialize it

Read up on c# list and you should have this fix in no time!

3 Likes

It’s the List itself that is null I think. You have to create a new list before adding things to it

bodyList = new List<GameObject>();

Edit: Posted at the same time!

2 Likes

The error complained not about the object, but about the list itself, because it was not created, although it was declared. It seems that today I got up on the wrong foot

Thank you for quick response!

2 Likes