0
\$\begingroup\$

So I finally perfected my RTS multiple movement. The situation is that the game objects are added into a list in a script bound to the camera called UnitController they are added from a unit client script MultiselectClient, this client accesses the UnitController class and adds itself the gameObject into the list. Each time I do the drag select I want it to clear the list first before adding any more. But for some reason, it doesn't work?

This is in my UnitController (below):

void MultiSelect(RaycastHit hit)
{
    Debug.Log(SelectedUnits);
    if (SelectedUnits.Count > 0)
    {
        Debug.Log("Moving group to: " + hit.point);
        foreach(GameObject gameObject in SelectedUnits)
        {
            gameObject.GetComponent<NavMeshAgent>().SetDestination(hit.point);
        }
    }
}

This is in my client (below):

public bool Selected = false;
void Update()
{
    if (Input.GetMouseButton(0))
    {
        Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
        camPos.y = Screen.height - camPos.y;

        //if inside the cameras drag selection area then mark player as selected
        Selected = UnitController.selection.Contains(camPos);

        Debug.Log("Selected");
        if(selected){
           addTo();
        }
    }


}

void addTo()
{

    UnitController.SelectedUnits.Remove(gameObject); //I have also tried .clear() which also hasnt worked.



    if (!UnitController.SelectedUnits.Contains(gameObject))
    {
        UnitController.SelectedUnits.Add(gameObject);
        Debug.Log("Added to list: " + UnitController.SelectedUnits);
    }
    else
    {
        Debug.Log("Im already in that list.");
    }
}
\$\endgroup\$
0
\$\begingroup\$

Your problem is this if-statement:

    if(selected){
       addTo();
    }

If the unit isn't selected, nothing happens. It doesn't matter that you do remove or clear inside addTo because addTo isn't being called unless this object is being selected.

    if(selected){
       addTo();
    }
    else{
       UnitController.SelectedUnits.Remove(gameObject);
    }
\$\endgroup\$
  • \$\begingroup\$ How stupid of me, thank you hehe. \$\endgroup\$ – Kiyo Oct 12 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.