Hamzaoud
Hamzaoud

Reputation: 1

How to not have my function executed in a single frame?

I'm making a 3D roulette game, where when the player presses the 'bet' button the ball will be positioned in a given location and also a force will be added to the ball. I've added 37 individual box colliders to know where the ball lands.

My problem is that from my understanding the bet function gets executed in a single frame. This means that the script checks for the fallen number before the ball has finished moving and landed inside a box collider. So the for the first bet the number fallen will be 0 even if it lands on another number, and then on the 2nd bet it will have the value of the first fallen number, etc...

public void BetSpinWheel()
{
    uiController.repeatButton.interactable = true;

    Spin();

    int earnings = CalculateEarnings(currentBet.ToArray(), lastNumbers);
    UpdateBalance(earnings);

    lastBet.Clear();
    foreach(Bet bet in currentBet)
    {
        lastBet.Add(bet);
    }

    currentBet.Clear();
    updateUI();
    uiController.ChangeLastNumberText();

}

private void Spin()
{

    audioSource.Stop();
    audioSource.Play();

    ballController.SpinBall();

    while (ballController.isMoving)
    { random++; }

    if (!ballController.isMoving && ballController.hasBallEnteredCollider)
    {
        lastNumbers = ballController.numberFallen;
        print(lastNumbers);
    }
}

and here is the ballController.SpinBall() function:

    public void SpinBall()
{
    rb.constraints = RigidbodyConstraints.None;
    transform.position = ballStartPosition;
    rb.velocity = Vector3.zero;

    transform.rotation = Quaternion.Euler(0f, 0f, 0f);
    rb.AddForce(forceToAdd, ForceMode.Impulse);
    print(isMoving);

}

If you would like to view the whole project, you can find it here: https://github.com/hamzaOud/Assignment02

Upvotes: 0

Views: 43

Answers (1)

WQYeo
WQYeo

Reputation: 4056

Use a Coroutine:

// The button should call this
public void BetSpinWheel() {
    StartCoroutine(BetSpinWhellCoroutine());
}

private IEnumerator BetSpinWheelCoroutine() {
    // Your bet stuff here
}

You can also 'store' a coroutine, so that you can stop it if you need to:

private Coroutine betSpinWheelCoroutine

// The button should call this
public void BetSpinWheel() {
    // Stop the coroutine first if it was running.
    if (betSpinWheelCoroutine != null){
        StopCoroutine(betSpinWheelCoroutine);
    }

    betSpinWheelCoroutine = StartCoroutine(BetSpinWhellCoroutine());
}

private IEnumerator BetSpinWheelCoroutine() {
    // Your bet stuff here
}

Upvotes: 2

Related Questions