I am trying to build an RTS game and I have managed to form a way to select a unit using Raycast and the tag system. I made it so that if the object the ray falls onto is of tag "TankUnit" Make so and so variable true and allow it to move to another place. However, Units of the same tag even when not selected also move. How do I fix this problem? The script is bound to each unit.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI;
public class UnitController: MonoBehaviour { bool clicked = false; //public float speed = 10f; //public float rotationSpeed = 10f;
public LayerMask groundLayer;
public NavMeshAgent playerAgent;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
Debug.Log("Clicked");
FindClickPos();
}
if (Input.GetMouseButton(1) && clicked == true)
{
Debug.Log("I clicked right mouse");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
MoveTo(hit);
}
}
}
private void FindClickPos()
{
RaycastHit hitInfo = new RaycastHit();
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
if (hit == true)
{
Debug.Log("I hit " + hitInfo.collider.name);
if (hitInfo.collider.tag == "TankUnit")
{
Debug.Log("I hit" + hitInfo.collider.tag + "!");
clicked = true;
}
else
{
Debug.Log("I didnt hit a unit :/");
clicked = false;
}
}
else
{
Debug.Log("I didnt hit anything...");
clicked = false;
}
}
void MoveTo(RaycastHit hit)
{
Debug.Log("Position: " + hit.point);
playerAgent.SetDestination(hit.point);
}
}