Random Number keeps generating over and over

Hi! I have a script I’m trying to make work.
The issue currently is that after the first random pick, it keeps picking again and again without any delay, thus making the object have a seizure.
The script:

	public void RandomDelay()
	{
		RandomPick = Random.Range(1, 4);
		Debug.Log("NEW RANDOM PICKED");
	}

	if (RandomPick == 1)
	{
		transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
		Debug.Log("RANDOM CHOICE 1");
		InvokeRepeating ("RandomDelay", 3.0f, 3.0f);
	}
	
	if (RandomPick == 2)
	{
		transform.position = Vector2.MoveTowards(transform.position, -target.position, speed * Time.deltaTime);
		Debug.Log("RANDOM CHOICE 2");
		InvokeRepeating ("RandomDelay", 3.0f, 3.0f);
	}
	
	if (RandomPick == 3)
	{
		transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime * 0); //Doesn't move
		Debug.Log("RANDOM CHOICE 3");
		InvokeRepeating ("RandomDelay", 3.0f, 3.0f);
	}		

If anyone has any ideas that could make this work properly, I’d love to hear them!

Hi,
invoke repeating means you keep calling a function… and it keeps repeating … therefore in your case your are calling a new repeat session every 3 seconds without cancelling the previous sessions… so you will quickly have hundreds of instance of this formula repeating.

//change:

InvokeRepeating ("RandomDelay", 3.0f, 3.0f);

//to:

StartCoroutine("Repick");

//and then
IEnumerator DelayedAnimation ()
    {
        yield return new WaitForSeconds(3.0f);
       RandomDelay();
    }

also - your item won’t move if you don’t put the transform position in a void update() … so use your randomdelay to assign a destination to a vector 3 variable and then movetowards that variable in your update part.

hope that helps,

Fixed it by adding a CancelInvoke at the end of the Random Delay method.

	public void RandomDelay()
	{
		RandomPick = Random.Range(1, 4);
		Debug.Log("NEW RANDOM PICKED");
		CancelInvoke("RandomDelay");
	}