How can I convert an array of components into their gameobjects?

Hello.
I’m trying to make a weapon pickup object.
As planned, when my car hits an object, the “Weapon Change” script is launched.
It checks for available gunPlace of the appropriate type and creates a weapon there.

And everything would be fine, but I constantly catch NullReferenceException when trying to translate a component into a game object.

Please tell me what’s wrong. I will be grateful.

Here is my script so far:

using System.Collections.Generic;
using UnityEngine;

public class GunChange : MonoBehaviour
{
    private List<GameObject> gunplaces;
    [SerializeField] GameObject turretBase; // keeps weapon prefab
    private GunType.Type type;
void Update()
    {
        transform.Rotate(0, 25f * Time.deltaTime, 0); // rotates object to pick up
    }

    void OnTriggerEnter(Collider other)
    {
        if(other.CompareTag("Player"))
        {
            FindGunPlace(other.gameObject);
            Destroy(gameObject);
        }
    }
    void FindGunPlace(GameObject player)
    {
        var Type = turretBase.GetComponentInChildren<GunBaseScript>();
        type = Type.weaponCharacteristics.gunType; //Get gunType in gun prefab: small, main or support.

        var gunplacesProt = player.GetComponentsInChildren<GunPlaceScript>(); //Get all the gun places of your car.
        for (int i = 0; i < gunplacesProt.Length; i++)
        {
            if (gunplacesProt[i].gunType == type) //if the place is of the appropriate type, then add it to the list of appropriate gun places.
            {
                gunplaces.Add(gunplacesProt[i].gameObject); //and there is a NullReferenceException
            }
        }
    }
}

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

It appears that GetComponentInChildren returns an array of Component objects in which case you need to cast the item to a GunPlaceScript.

Inside your for loop (if you don’t want to use foreach syntax

var gunPlace = (GunPlaceScript)gunplacesProt[i];

and reference gunPlace from then on

You absolutely do NOT need to cast the results of GetComponentsInChildren, and this has nothing to do with the problem at hand.

The OP’s issue is very simple. They never initialized gunPlaces. It needs to be initialized:

private List<GameObject> gunPlaces = new();