TurnBasedStrategyCourse/Assets/Scripts/UnitActionSystem.cs

50 lines
1.6 KiB
C#

using System;
using UnityEngine;
public class UnitActionSystem : MonoBehaviour {
[SerializeField] private LayerMask UnitsLayerMask;
[SerializeField] private Unit selectedUnit;
public static UnitActionSystem Instance { get; private set; }
public Unit SelectedUnit {
get => selectedUnit;
private set => selectedUnit = value;
}
private void Awake() {
if (Instance is not null) {
Debug.LogError($"There is more than one UnitActionSystem! {transform} - {Instance}");
Destroy(gameObject);
return;
}
Instance = this;
}
private void Update() {
if (Input.GetMouseButtonDown(0)) {
if (TryHandleUnitSelection()) return;
if (SelectedUnit is null) return;
GridPosition mouseGridPosition = LevelGrid.Instance.GetGridPosition(MouseWorld.GetPosition());
if (selectedUnit.MoveAction.IsValidActionGridPosition(mouseGridPosition)) SelectedUnit.MoveAction.Move(mouseGridPosition);
}
}
public event EventHandler OnSelectedUnitChanged;
private bool TryHandleUnitSelection() {
if (!Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit raycastHit, float.MaxValue, UnitsLayerMask)) return false;
if (raycastHit.transform.TryGetComponent(out Unit unit) && unit is not null) {
SetSelectedUnit(unit);
return true;
}
return false;
}
private void SetSelectedUnit(Unit unit) {
SelectedUnit = unit;
OnSelectedUnitChanged?.Invoke(this, EventArgs.Empty);
}
}