using System.Diagnostics.Contracts; using System.Xml.Serialization; using UnityEngine; public class UnitCommander : MonoBehaviour { public GameObject selectionMarkerPrefab; public LayerMask layerMask; //components private UnitSelection unitSelection; private Camera cam; void Awake() { //get the components unitSelection = GetComponent(); cam = Camera.main; } // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { } // Update is called once per frame void Update() { if(Input.GetMouseButtonDown(1) && unitSelection.HasUnitSelected()) { Ray ray = cam.ScreenPointToRay(Input.mousePosition); RaycastHit hit; Unit[] selectedUnits = unitSelection.GetSelectedUnits(); if(Physics.Raycast(ray, out hit, 100, layerMask)) { if(hit.collider.CompareTag("Ground")) { SelectionMarker marker = CreateSelectionMarker(hit.point, false); UnitsMoveToPosition(hit.point, selectedUnits, marker); } else if(hit.collider.CompareTag("Resource")) { UnitsGatherResource(hit.collider.GetComponent(), selectedUnits); CreateSelectionMarker(hit.point, true); } } } } void UnitsMoveToPosition(Vector3 movePos, Unit[] units, SelectionMarker marker) { for(int x = 0; x < units.Length; x++) { // Only the first unit owns the marker so it isn't destroyed multiple times units[x].MoveToPosition(movePos, x == 0 ? marker : null); } } //creates a new selection marker at the position we right click SelectionMarker CreateSelectionMarker(Vector3 pos, bool large) { GameObject marker = Instantiate(selectionMarkerPrefab, pos + new Vector3(0, 0.01f, 0), Quaternion.identity); if(large) marker.transform.localScale = Vector3.one * 3; return marker.GetComponent(); } //called when we command units to move somewhere void MoveUnitsToPosition(Vector3 movePos, Unit[] units) { Vector3[] destinations = UnitMover.GetUnitGroupDestination(movePos, units.Length, 2); for(int x = 0; x < units.Length; x++) { units[x].MoveToPosition(destinations[x]); } } //called when we command units to gather a resource void UnitsGatherResource(ResourceSource resource, Unit[] units) { if(units.Length == 1) { units[0].GatherResource(resource, UnitMover.GetUnitDestinationAroundResource(resource.transform.position)); } else { Vector3[] destinations = UnitMover.GetUnitGroupDestinationsAroundResource(resource.transform.position, units.Length); for(int x = 0; x