Unity RTS Style movement without navmesh agent

Hello, I’m trying to do RTS movement without using navmeshagent system. I have a script that only single select unit and click to order. The point is, if I select a another unit while previous one already moving, new selected unit is moving to the same point while previous one stopped.

Demo:

Code:

private Camera mycam;
private RaycastHit hit;
public Vector3 tf;
public LayerMask ground;
private bool move;


public static UnitMove instance;
private void Awake()
{
    instance = this;
}
private void Start()
{
    mycam = Camera.main;
}
private void Update()
{
    if (Input.GetMouseButtonDown(1) && haveSelected())
    {
        if (UnitClick.Instance.selectChanged)
        {
            getMouseRay();
        }
    }
    if (move)
    {
        SetDestination(UnitClick.Instance.selectedUnit.transform.position, hit);
    }
}
private void SetDestination(Vector3 unitPos, RaycastHit hit)
{
    move = true;
    if (Vector3.Distance(UnitClick.Instance.selectedUnit.transform.position, hit.point) > 0.5f)
    {
        UnitClick.Instance.selectedUnit.transform.position = Vector3.MoveTowards(UnitClick.Instance.selectedUnit.transform.position,
            new Vector3(hit.point.x, UnitClick.Instance.selectedUnit.transform.position.y, hit.point.z), 1f * Time.deltaTime);
    }
}
public void getMouseRay()
{
    Ray ray = mycam.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit, Mathf.Infinity, ground))
    {
        move = true;
    }
}
private bool haveSelected()
{
    if (UnitSelection.Instance.unitSelected.Count > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

What’s a “UnitMove”? Anyways, you made it static, so it’s shared between all scripts. I’d guess that’s the problem.

Also…

… when stating you want to do something different from how it’s usually done, you usually explain why. In this case i can imagine it might be since RTS will usually involve many units and the default path finding is likely single threaded. Depending on how many units your game is going to have you will be bottlenecked by Unitys gameobject workflow anyways. If you need hundreds to thousands and more units, you need to use something like DOTS. If you only have a couple douzen units or so, you can likely use NavMesh as well.

1 Like