GetComponent<>() not fetching script

I am new to Unity and trying to figure my way around a NullReferenceException (Object reference not set to an instance of an object).
This is the hierarchy of objects in the scene:

Scene 3D

Game Manager

Map Generator

This is the GameManager.cs script:

namespace Forest {
    public class GameManager : MonoBehaviour 
    {
        protected int width=90;
        protected int height=40;
        public GoodPlayerController goodPlayerCtrl;
        public MapGenerator mapObj;
        // public GameObject goal;

        int[,] map;

        void Start() 
        {		
            GenerateAll();
        }

        void Update() 
        {
            if (Input.GetMouseButtonDown(0)) 
            {
                GenerateAll();
            }
        }

        void GenerateAll()
        {
            mapObj = GetComponent<MapGenerator>();
            map = mapObj.GenerateMap(width, height); //Error

            MeshGenerator meshGen = GetComponent<MeshGenerator>();
	meshGen.GenerateMesh(map, 1);


            // goodPlayerCtrl = GetComponent<GoodPlayerController>();
            // goodPlayerCtrl.SpawnPlayer(mapObj, map);
        }
    }
}

And this is the MapGenerator.cs script:

namespace Forest 
{
public class MapGenerator : MonoBehaviour
{
	protected int width;
	protected int height;

	int[,] map;

	public int[,] GenerateMap(int w, int h) 
	{	
		width = w;
		height = h;
		map = new int[width,height];

		// processing the map

	return map;

	}
}
}

I also notice another thing in the heirarchy:
image
In the Script section, the Map Obj reference becomes

None (Map Generator)

when I run/play the scene. I think this is the cause of the error but I can’t figure out how to fix it.

1 Answer

1

GetComponent will only find components on the same hierarchy level as the current script.

If you want to find a component that exists in one of the children of the current object, then you need to use GetComponentInChildren.

(Just a side note, GetComponentInChildren and GetComponentsInChildren will also return components on the current object if it exists. This will be important if you have the same component at both the current hierarchy level and a lower level.)