Object reference not set to an instance of an object problem

Good evening to all
In one scene, I have several InputFields that are there to enter the names of all the participants.
What I would like to do next is to get the first name of each participant in a list.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Players : MonoBehaviour
{
    public GameObject[] PlayerInput;
    public InputField PlayerName;
    public string[] AllPlayersName;
    int i = 0;

    public void InstentiatePlayer()
    {
        Debug.Log("Button On");
        PlayerInput = GameObject.FindGameObjectsWithTag("PlayerList");

        foreach (GameObject Player in PlayerInput)
        {
            Debug.Log("Button Enter");
            PlayerName = Player.GetComponent<InputField>();
            AllPlayersName[i] = PlayerName.text;
            i++;
        }
        Debug.Log("Button Exit");
    }

   
}

But I get this error message “NullReferenceException: Object reference not set to an instance of an object”. What I don’t understand is that all my InputFields have a value.
Do I need to check that each one has a text? If so, would you have a solution?

Thank you for your help.

Which line is causing the exception?

If I had to guess, it’s probably line 22 - which would mean that one or more GameObjects with the PlayerList tag do not have an InputField component.

1 Like

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

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.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.