lundi 15 avril 2019

Why Random.Range is overlapping button positions from the list in Unity?

I have a list of UI Buttons and Vector2 for positions. I am using random.range to place buttons randomly every time i load them. But it never shows all 5 buttons at different positions. instead overlapping some of them. Can anyone please help me with this?

[SerializeField] List<Button> answersButtons = new List<Button>();
[SerializeField] List<Vector2> positions = new List<Vector2>();

void ShuffleAnswersList()
{             

    for (int i = 0; i < answersButtons.Count; i++)
    {              
       Vector2 tempPosition = 
       answersButtons[i].GetComponent<RectTransform>().position;

       int randomIndex = Random.Range(0, positions.Count);

       answersButtons[i].transform.position = positions[randomIndex];
       answersButtons[randomIndex].GetComponent<RectTransform>().position 
       = tempPosition;

       Debug.Log(randomIndex);          
    }      

}

// shuffle positions
public void Shuffle()
{
    for (int i = 0; i < positions.Count; i++)
    {
        int rnd = Random.Range(0, positions.Count);
        Vector2 tempGO = positions[rnd];
        positions[rnd] = positions[i];
        positions[i] = tempGO;
    }
}




Aucun commentaire:

Enregistrer un commentaire