Random position, overlap issue

Hello guys, i im trying to random position of 3 targets so they dont overlap, but sometimes they overlap i dont know why. Im randoming position then looking if distance to some targets is less than 100, than i loop again, but something goes wrong i dont know what.

 void Start () {
        targets = GameObject.FindGameObjectsWithTag("Target");
        SetTargetsPositions();
    }
   

    private void SetTargetsPositions()
    {
        for (int i = 0; i < targets.Length; i++)
        {
            RandomPos(targets[i]);
        }
    }
    private void RandomPos(GameObject target)
    {
        Vector2 randomPosition;
        randomPosition = new Vector2(Random.Range(-285, 285), Random.Range(336, -262));
        for (int i = 0; i < GetTargetList(target).Count; i++)
        {         
            if (Vector2.Distance(randomPosition, GetTargetList(target)[i].GetComponent<RectTransform>().anchoredPosition) < 100)
            {
                randomPosition = new Vector2(Random.Range(-285, 285), Random.Range(336, -262));
                i = 0;
            }
        }
       
        target.GetComponent<RectTransform>().anchoredPosition = randomPosition;
    }
    private List<GameObject> GetTargetList(GameObject target)
    {
        List<GameObject> sortedTargets = new List<GameObject>();
        for (int i = 0; i < targets.Length; i++)
        {
            if (targets[i] != target)
                sortedTargets.Add(targets[i]);
        }
        return sortedTargets;
    }

In your RandomPos function you set ‘i = 0’ when you pick a new position. That needs to be ‘i = -1’ as the for loop will increment it at the end and you’ll start at 1 on the next iteration.

1 Like

Thanks, you are right, that was an issue!