lundi 20 mai 2019

How do I spawn an item using Random.Range, but have the waiting time change after each spawn?

Thank you for reading.

My concept is very simple: I am spawning objects. I have three floats: RunEvery, BetweenThis, and AndThis. I can get a value in return, but I am unable to change this value. I'd like a new random number every time, but I just keep getting the same initial value.

RunEvery = Random.Range(BetweenThis, AndThis);

Let's say that BetweenThis is equal to 1, and AndThis is equal to 20. RunEvery then becomes any number between 1 and 20. So if the chosen number is 10, the script will spawn that object every ten seconds.

I'm not looking for, "10, 10, 10, 10, 10...etc."

I need, "10, 7, 5.5, 18, 9...etc."

public UnityEvent OnTimerEnd;

void OnEnable()
{
    SetRandomizer();
    if (RunOnAwake){
        Invoke("Execute", 0);
    }
    if (Loop){
        //SetRandomizer();
        InvokeRepeating("Execute", RunEvery, RunEvery);
    }
    else{
        Invoke("Execute", RunEvery);
    }
}

public void SetRandomizer(){
    RunEvery = Random.Range(BetweenThis, AndThis);
    Debug.Log("The Random Range is " + RunEvery);
}

public void Execute(){
    OnTimerEnd.Invoke();
    //SetRandomizer();
}

I'd like it to keep choosing random numbers, but I can only get the script to repeat the initial value every single time.

I've tried creating new functions that hold the Random.Range stuff, but for some reason, it will only even use that first generated value.

I've tried moving parts of the code around, creating an IEnumerator and just waiting, and I even tried turning the entire script on and off. There's a bunch of other stuff I tried, but I won't bore you with that.

I'm sure it's a simple thing to fix, but it's just not something I can figure out on my own. I looked through the Scripting API and the manual and my C# books, but they only ever talks about using Random.Range only once, not repeatedly.




Aucun commentaire:

Enregistrer un commentaire