public void GiveTarget(Selectable target) { // First we'll try to resolve 'target' as either a Unit or a Tile. SelectableCell targetCell = target as SelectableCell; SelectableUnit targetUnit; if (targetCell == null) // it's not a SelectableTile, maybe it's a SelectableUnit { targetUnit = target as SelectableUnit; } else if (targetCell.IsOccupied()) // it IS a SelectableTile, and it's occupied! { targetUnit = GetComponentInChildren <SelectableUnit>(); } else // it is a non-occupied SelectableTile { unit.MoveTo(targetCell.GetCell()); return; } if (targetUnit != null) // it is a SelectableUnit, try to attack it. { if (IsValidTarget(targetUnit)) { unit.Attack(targetUnit.GetUnit()); // Let Unit figure out whether it's in range of weapon and such } else { Debug.Log("Other Unit not a valid target"); } } }
void Update() { if (Input.GetKey(KeyCode.Escape)) { ClearSelection(); } // Handle Selection with left click if (CurrentMode == SelectionMode.Normal || CurrentMode == SelectionMode.GivingOrder) { // First: Left mouse button to select a target unit if (Input.GetMouseButtonDown(0)) // Left mouse button { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(ray.origin, ray.direction * float.MaxValue, Color.cyan, 10f); // Debug our ray! RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo)) { SelectableUnit leftClickedObj = hitInfo.collider.GetComponentInParent <SelectableUnit>(); if (leftClickedObj != null) { ClearSelection(); // Deselect previous object if (leftClickedObj.CanBeSelected()) { SelectUnit(leftClickedObj); } else { Debug.Log("Unit not selectable by you!"); } } else { Debug.Log("Clicked object not a selectable unit!"); } } } } if (CurrentMode == SelectionMode.GivingOrder) { // Right mouse button to give a target to our current selection if (Input.GetMouseButtonDown(1)) // Right mouse button { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo)) { Selectable rightClickedObj = hitInfo.collider.GetComponentInParent <Selectable>(); if (rightClickedObj != null) { CurrentSelection.GiveTarget(rightClickedObj); ClearSelection(); } } } } if (CurrentMode == SelectionMode.PlacingUnit) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo)) { SelectableCell newHoverCell = hitInfo.collider.GetComponentInParent <SelectableCell>(); if (HoverCell != newHoverCell) { if (HoverCell != null) { HoverCell.OnDeselect(); } HoverCell = newHoverCell; // Can also be null! if (HoverCell != null) { HoverCell.OnSelect(); } } } else // Moused over nothing { if (HoverCell != null) { HoverCell.OnDeselect(); HoverCell = null; } } if (Input.GetMouseButton(0)) // Place with left mouse button { if (HoverCell != null) { CurrentBuilder.SpawnUnit(HoverCell.GetCell()); ClearSelection(); } } if (Input.GetMouseButton(1)) // cancel with right { ClearSelection(); } } }