I’ve been reviewing this code and just can’t find my error. I’m sure it’s just a typo.
Pressing play, the Visual Selector doesn’t turn off when I select my other unit.
I’ve run through the videos and double-checked my references. Something is preventing the event from firing.
UnitSelectedVisual code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitSelectedVisual : MonoBehaviour
{
[SerializeField] private Unit unit;
private MeshRenderer meshRenderer;
private void Awake() {
meshRenderer = GetComponent<MeshRenderer>();
}
private void Start()
{
UnitActionSystem.Instance.OnSelectedUnitChanged += UnitActionSystem_OnSelectedUnitChanged;
UpdateVisual();
}
private void UnitActionSystem_OnSelectedUnitChanged(object sender, EventArgs emtpy)
{
UpdateVisual();
}
private void UpdateVisual()
{
if(UnitActionSystem.Instance.GetSelectedUnit() == unit)
{
meshRenderer.enabled = true;
}else{
meshRenderer.enabled = false;
}
}
}
UnitActionSystem Code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitActionSystem : MonoBehaviour
{
public static UnitActionSystem Instance { get; private set; }
public event EventHandler OnSelectedUnitChanged;
[SerializeField] private Unit selectedUnit;
[SerializeField] private LayerMask unitLayerMask;
private void Awake() {
if(Instance !=null)
{
Debug.LogError(" There's more than one UnitActionSystem " + transform + " - " + Instance);
Destroy(gameObject);
return;
}
Instance = this;
}
private void Update(){
if(Input.GetMouseButton(0))
{
if(TryHandleUnitSelection()) return;
selectedUnit.Move(MouseWorld.GetPos());
}
}
private bool TryHandleUnitSelection(){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, unitLayerMask)){
if (raycastHit.transform.TryGetComponent<Unit>(out Unit unit))
{
selectedUnit = unit;
return true;
}
}
return false;
}
private void SetSelectedUnit(Unit unit)
{
selectedUnit = unit;
OnSelectedUnitChanged?.Invoke(this, EventArgs.Empty);
}
public Unit GetSelectedUnit(){
return selectedUnit;
}
}
SelectedVisual Inspector
Unit Inspector