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

Time:11-17

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;
}

CodePudding user response:

An easy method is rejection-sampling. Simply take your random value, do some check, and generate a new value if the check fails. In this case I would assume the check would be if objects overlap or the value is to close to a previous value.

CodePudding user response:

You can change starting seed of random number generator in Unity so every time latest seed generates different random numbers within range Something Like:

    Random.InitState(DateTime.UtcNow.Millisecond);
    float NonRepeatedResult = Random.Range(0f, 1f);
    if(NonRepeatedResult < 0.8f)
    {
        //Do your stuff
    }
    ......

Here current milliseconds change rapidly every time , changing seed for every random number generation which adds element of uniqueness in consecutive generations.

  • Related