Why use an array and a foreach loop?

(Forgive me if I’m missing something very obvious.)

In the Configurable Cursors lecture we set up a system to change the cursor’s appearance by searching through an array for the correct type. The types are set in the array by ‘the designer’ in Unity’s inspector using serialized fields. Why is this better than making Texture2D serialized fields for the icon the designer wants to use? (And a serialized field for the Vector2 hotspot if that also needs to be changed.)

New cursor types can’t be added in Unity’s inspector, only the ones already in the script can be selected and configured so, for example, if the designer adds an icon to interact with a door, the new type needs to be added through code. The code is already setting the appropriate type in the desired places: InteractWithCombat() uses SetCursor(CursorType.Combat), InteractWithMovement() uses CursorType.Movement in the same SetCursor() method. If we add a new method InteractWithDoor() we’ll logically use SetCursor(CursorType.Door).

As such we can have:

[SerializeField] Texture2D movementIcon;
[SerializeField] Vector2 movementHotspot;

private bool InteractWithMovement()
        {
            RaycastHit hit;
            bool hasHit = Physics.Raycast(GetMouseRay(), out hit);

            if (hasHit)
            {
                if (Input.GetMouseButton(0))
                {
                    mover.StartMoveAction(hit.point, 1f);
                }
                SetCursor(movementIcon, movementHotspot);
                return true;
            }
            return false;
        }

void SetCursor(Texture2D icon, Vector2 hotspot)
        {
            Cursor.SetCursor(icon, hotspot, CursorMode.Auto);
        }

And more serialized fields for whatever other icons (and their hotspot positions) we intend to use. This does the same thing as far as I can tell, but without the need of an array of structs and a foreeach loop to search through them. Unity’s Inspector (and thus the designer) has as much control as the array version and does the same amount of work in either scenario.

In the next few lectures, we’ll be introducing a different paradigm for interacting with the world. We’ll be asking components like CombatTarget or Pickups to Interact. Over the four courses, we’ll be adding more components that handle raycasts and specify what type of cursor they will be using.

1 Like

Aha, so it’s preparing for future things and I haven’t missed the point of doing it that way.

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

Privacy & Terms