Quantcast
Channel: Latest Questions on Unity Answers
Viewing all articles
Browse latest Browse all 171066

How to correctly handle unit selection

$
0
0
So, I'm trying to create a basic RTS game, but I keep stumbling at this part, while selecting all of the units using the GUI.Box method, I don't know how to store them somewhere to make them actually registered as "Selected" currently I'm just using a boolean value, which, works... although, it doesn't relay any data. **I'm trying to figure out how to relay some information, so I can list how many units I have selected, and group them by their name.** Here's the crappily written code, go easy on me, it's my first week. using UnityEngine; using System.Collections; public class MouseManager : MonoBehaviour { public static Rect selectionRect = new Rect(0,0,0,0); private Vector3 startClick = -Vector3.one; void Update() { drawSelectionBox(); } void drawSelectionBox() { if(Input.GetMouseButtonDown (0)) { startClick = Input.mousePosition; } if(Input.GetMouseButtonUp (0)) { if(selectionRect.width < 0) { selectionRect.x += selectionRect.width; selectionRect.width = -selectionRect.width; } if(selectionRect.height < 0) { selectionRect.y += selectionRect.height; selectionRect.height = -selectionRect.height; } startClick = -Vector3.one; } if(Input.GetMouseButton (0)) { selectionRect = new Rect(startClick.x, screenToRectSpace(startClick.y), Input.mousePosition.x - startClick.x, screenToRectSpace(Input.mousePosition.y) - screenToRectSpace(startClick.y)); } } public static float screenToRectSpace(float y) { return Screen.height - y; } void OnGUI() { if(startClick != -Vector3.one) { GUI.color = new Color(1, 1, 1, 0.5f); GUI.Box (selectionRect, ""); } } } Then, for handling the selection, I have this attatched to the units prefab bool selected = false; void checkSelected() { if(renderer.isVisible && Input.GetMouseButton(0)) { Vector3 camPos = Camera.mainCamera.WorldToScreenPoint(transform.position); camPos.y = MouseManager.screenToRectSpace(camPos.y); selected = MouseManager.selectionRect.Contains (camPos); } if(selected) renderer.material.color = Color.red; else renderer.material.color = Color.white; } My idea behind this was to create a GameObject Array and store everything in there, but I'm just not sure how to go about it. I could do it if it was single unit selection, but now that I'm talking about selecting multiple units at the same time, I'm not sure how to go about it.

Viewing all articles
Browse latest Browse all 171066

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>