Action to cycle to next friendly unit in unit list (completed course)

I have completed the course so I have all the scripts implemented that the course teaches. Im very new to coding, I understand what should be done but not how to get there with code.

Im wondering how I would code a new action for cycling through friendly units in the scene. I assume Id access UnitManager.Instance.GetFriendlyUnitList(). From there, Id just need to cycle through each unit in the list and set it with UnitActionSystem.Instance.SetSelectedUnit(unit).

What would the code to cycle through and select next unit in list look like?

The way I set that up was in UnitActionSystem (I’ve cut out and changed some code to hopefully make it more readable):

In bool TryHandleUnitSelection() I added this at the bottom:

        if (InputManager.Instance.IsTabKeyDownThisFrame())
        {
            return SelectNextUnit();
        }

        return false;
    }

Which calls this when the player presses Tab:

    public bool SelectNextUnit()
    {
        List<Unit> units = UnitManager.Instance.GetFriendlyUnitList();

        if (units.Count <= 1) // If there's one (or zero) Units we can't cycle
        {
            return false;
        }

        int selectedUnitIndex = units.IndexOf(_selectedUnit);

        if (selectedUnitIndex == units.Count - 1) // If the currently selected Unit is the last in the list we cycle to the first Unit in the list
        {
            SetSelectedUnit(units[0]);
            return true;
        }
        else
        {
            SetSelectedUnit(units[selectedUnitIndex + 1]);
            return true;
        }
    }

I think that’s all you need for it to work. I changed a lot of things in the project in a lot of places so I can’t be certain. (And, to be clear, if you copied this directly you’d also need to set up the InputManager with a IsTabKeyDownThisFrame() method.

1 Like

This looks like an excellent solution to the problem, and is pretty much what I would have come up with! Well done.

1 Like

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

Privacy & Terms