mardi 16 novembre 2021

How to avoid Unity Random.Range function to generate same numbers?

I have a method to generate a GameObject at a certain (random) angle each time the method is called. Sometimes it happens that two GameObject are generated by this method at same random angle, overlapping them.

I need to avoid this but I don't know how to do.

Here is the code for the method:

public Branch CreateBranch()
{
    GameObject newBranchGo = new GameObject("Branch");
    newBranchGo.transform.position = transform.position;
    newBranchGo.transform.parent = transform;

    newBranchGo.transform.rotation = transform.rotation;

    var angle = tree.GoldenAngle;
    if (tree.NumChildren == 1)
    {
        angle = 0;
        //Debug.Log("Angle: " + angle);
        newBranchGo.transform.Rotate(angle, 0f, 0f, Space.Self);
    }
    else
    {
        if (Random.Range(0f, 1f) < 0.8f)
        {
            angle = -angle;
        }

        if (Random.Range(0f, 1f) < 0.5f)
        {
            newBranchGo.transform.Rotate(angle, 0f, 0f, Space.Self);
        }
        else
        {
            newBranchGo.transform.Rotate(0f, angle, 0f, Space.Self);
        }
    }

    Branch branch = newBranchGo.AddComponent<Branch>();
    branch.BranchInit(tree, GetComponent<Bud>());

    return branch;
}



Aucun commentaire:

Enregistrer un commentaire