Weird Selection box behaviour

Hi all,

For some reason my selection box behaves like this:

What could be the issue?

This is my UnitSelectionHandler code:

private void Update()
{
        if (Mouse.current.leftButton.wasPressedThisFrame)
        {
            StartSelectionArea();
        }
        else if (Mouse.current.leftButton.wasReleasedThisFrame)
        {
            ClearSelectionArea();
        }
        else if(Mouse.current.leftButton.isPressed)
        {
            UpdateSelectionArea();
        }
}

private void StartSelectionArea()
    {
        foreach (Unit selectedUnit in SelectedUnits)
            {
                selectedUnit.Deselect();
            }
            SelectedUnits.Clear();

        unitSelectionArea.gameObject.SetActive(true);

        startPosition = Mouse.current.position.ReadValue();

        UpdateSelectionArea();
    }

private void UpdateSelectionArea()
    {
        Vector2 mousePos = Mouse.current.position.ReadValue();

        float areaWidth = mousePos.x - startPosition.x;
        float areaHeight = mousePos.y - startPosition.y;

        unitSelectionArea.sizeDelta = new Vector2 (Mathf.Abs(areaWidth), Mathf.Abs(areaHeight));
        unitSelectionArea.anchoredPosition = startPosition + new Vector2(areaWidth /2, areaHeight /2);
    }

private void ClearSelectionArea()
    {
        Ray ray = mainCam.ScreenPointToRay(Mouse.current.position.ReadValue());
        if (!Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, layerMask))
        {
            return;
        }
        if(!hit.collider.TryGetComponent<Unit>(out Unit unit)) 
        {
             return;
        }
        if (!unit.hasAuthority) { return; }

        SelectedUnits.Add(unit);

        foreach(Unit selectedUnit in SelectedUnits)
        {
            selectedUnit.Select();
        }
    }

Also these are the components on the image and the canvas:


1 Like

OK, so turns out if I do not reset the values on the Image Rect Transform like in this episode, it works just fine. Setting the anchor to the lower left was just enough. I don’t know why this happens but if anyone has the same problem this might fix it.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms