Stuck! Newly spawned unit unable to select it :(

When trying to test the selecting of units I keep getting the following error:

NullReferenceException: Object reference not set to an instance of an object
    UnitSelectionHandler.ClearSelectionArea () (at Assets/Scripts/Units/UnitSelectionHandler.cs:41)
    UnitSelectionHandler.Update () (at Assets/Scripts/Units/UnitSelectionHandler.cs:34)

Because of this, I am unable to select the unit.

Here is the code from UnitSelectionHandler:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.InputSystem;
     
    public class UnitSelectionHandler : MonoBehaviour
    {
        [SerializeField] private LayerMask layerMask = new LayerMask();
     
        private Camera mainCamera;
     
        private List<Unit> selectedUnits = new List<Unit>();
     
        private void Stat()
        {
            mainCamera = Camera.main;
        }
     
        private void Update()
        {
            // Checking if we have started a selection
            if(Mouse.current.leftButton.wasPressedThisFrame)
            {
                foreach (Unit selectedUnit in selectedUnits)
                {
                    selectedUnit.Deselect();
                }
     
                selectedUnits.Clear();
            }
            else if(Mouse.current.leftButton.wasReleasedThisFrame)
            {
                ClearSelectionArea();
            }
        }
     
        private void ClearSelectionArea()
        {
            Debug.Log("Hello");
            Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
            
            if(!Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, layerMask)) { return; }
     
            // Check if we have hit a unit
            if(!hit.collider.TryGetComponent<Unit>(out Unit unit)) { return; }
     
            // Check if we own the unit
            if(!unit.hasAuthority) { return; }
            
            // Add the unit we selected.
            selectedUnits.Add(unit);
     
            foreach (Unit selectedUnit in selectedUnits)
            {
                selectedUnit.Select();
            }
        }
    }

I have worked out from doing a log output that it seems to be a problem with line 41:

Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());

But I can’t seem to fault it.

Found the problem, thanks to Mark from the Udemy Q&A.

I had: “Stat” instead of “Start”

private void Stat()
        {
            mainCamera = Camera.main;
        }

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms