Random.Range runs forever

Hey guys, so I’m trying to use Random.Range to choose between 2 dialogues I have for a given character. However, I need to figure out a more appropriate logic to use than this. I’m currently using timers in update with a ridiculous number of booleans and its really unnecessary so I just want to randomize it instead.

Heres a very similar logic to what I have:

void Update ()
{
    inRange = Physics2D.OverlapCircle (transform.position, Range, thePlayer)

    if (inRange)
   { 
          CharacterMeet ();
   }

}

void CharacterMeet()
{
	int n = Random.Range (0, 2);

      switch (n)
   {
      case 0:
           print ( "value of n = " + n);
           break;

       case 1:
           print ( "value of n = " + n);
           break;
   }

}

Currently 0 and 1 are getting printed every frame. Instead after picking a random number I needed it to leave CharacterMeet() method. If there is a way I can do this without using coroutines that would be great. This is a message that should display when the player gets close to an AI character, so if the player leaves the range while the code is running I get an error.

I understand Random.Range running forever in what is expected since this is what the code is doing each frame, but I needed to interrupt that somehow only with one value from Random.Range at a time when the player is in the range and I wasn’t sure how to go about doing this.

(Maybe it’ll work best with a coroutine I’m might just not be using it properly)

Thanks a lot guys :slight_smile:

The issue isn’t the random number, the issue is when your character gets in range, CharacterMeet() is being called every frame. OverlapCircle isn’t a one and done thing, if two positions overlap, it will continue to be true until it isn’t.


I suggest using triggers instead. Which is adding colliders to your characters and setting them to trigger. Then you can get a callback OnTriggerEnter() and those only get called once (unless you back out of the character collider and back in again). From OnTriggerEnter() method call your CharacterMeet();