Ok, So I am working on an RTS Game, And I have Made a script that can Select my Units Via drawing a rectangle And it works Perfectly. However, I Was trying to make the Single Target Selection Using Raycasting and Integrate it with my “Selection Manager” Script but I keep Failing. Please Keep in Mind I am a noob so bite-Size Answers would be very much appreciated.
Thanks in Advance!
I use 3 Scripts for this.
-
Unit Selector, the problem is with this script. Named: “Mouse Point”
-
Selection Manager. Named “Selection Manager”
-
A Script On my Units that Indicates they Have been selected with Some Art. Named: “Unit”
-
This is how my Rectangular Script Works.
1)----------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MousePoint : MonoBehaviour
{
RaycastHit hitInfo;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
callSelectionManager();
}
if (Input.GetMouseButtonUp(0))
{
callSelectionManager();
}
}
void callSelectionManager()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
foreach (Unit myUnits in SelectionManager.unitList)
{
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity))
{
if (hitInfo.collider.tag == "Player1" && hitInfo.collider.gameObject == myUnits) // I tried (hitInfo.collider.tag == "Player1" && hitInfo.collider.gameObject == myUnits) and 100 other things with no luck
{
//****This is where I am stuck****
myUnits.SetSelector(true);
Debug.Log(hitInfo.collider.name);
}
}
}
}
}
}
2)---------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelectionManager : MonoBehaviour
{
public static List<Unit> unitList = new List<Unit>();
}
3)-------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Unit : MonoBehaviour
{
public GameObject selectorIndicator;
void Start()
{
SetSelector(false);
SelectionManager.unitList.Add(this);
}
public void SetSelector(bool on)
{
selectorIndicator.SetActive(on);
}
}
- A fraction of My rectangular Script---------
foreach (Unit myUnits in SelectionManager.unitList)
{
if (selectionRect.Contains(Camera.main.WorldToScreenPoint(myUnits.transform.position)))
{
myUnits.SetSelector(true);
}
}