RTS Unit Movement, Units of the same tag are all selected
So as the Question says. When I go to select a unit, It selects all current instances of units under the same tag. I.e "TankUnit" I am using a raycast system to detect If I'm clicking the unit. What should I do to prevent this from happening?
https://gyazo.com/467a9d1131167fc08a308f621f28c290
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);
}
}
Comment
Answer by tormentoarmagedoom · Oct 02, 2019 at 07:54 PM
Hello there.
I understand this script is attached to the tank unit. This playerAgent variable, where you ddefine it? via inspector?
Its like you send the SetDestination() function to both tanks.
Try this to be sure its not here the problem. Change this
playerAgent.SetDestination(hit.point);
for this:
gameObject.GetComponent<NavMeshAgent>().SetDestination(hit.point);
And say what you have.
I know this is an incredibly late reply but this question has now been answered, Im very sorry!