For anyone who wants to avoid singletons from this specific lesson

I was able to decouple the visuals from the action system by having two events on the Unit class. Now anything can select or deselect units based on its own logic:

    public event Action OnUnitSelected;
    public event Action OnUnitDeSelected;

    public void Select() {
        OnUnitSelected?.Invoke();
    }
    
    public void DeSelect() {
        OnUnitDeSelected?.Invoke();
    }

Then in the UnitActionSystem it can select, or deselect units:

    private void SetSelectedUnit(Unit unit) {
        // Warning about lifetime check omitted, not important in this example
        selectedUnit?.DeSelect();
        unit.Select();

        selectedUnit = unit;
    }

Now, the UnitSelectedVisual class only cares about the state of the unit its attached to, and its events, and has no coupling to any other classes that can alter the selected state of the unit:

    private void Start() {
        unit.OnUnitSelected += HandleSelectedUnitSelected;
        unit.OnUnitDeSelected += HandleSelectedUnitDeSelected;
        
        // Show in edit mode, disable when play mode starts
        _meshRenderer.enabled = false;
    }

    private void HandleSelectedUnitSelected() {
        _meshRenderer.enabled = true;
    }
    
    private void HandleSelectedUnitDeSelected() {
        _meshRenderer.enabled = false;
    }

Of course, I haven’t gone through this whole course, so implementing it this way may give me a huge headache later trying to convert from the intended way to my way. So warning to anyone else who wants to try this.

5 Likes

Yup that’s another valid approach. I don’t think it will conflict with any code further in the course but make sure you do implement the Singleton on the UnitActionSystem since that will be used in other places.

1 Like

Privacy & Terms