How to return to a value used before? (C#)

Hi.
What I currently am trying to do is to take the player character’s ability to move away from him during a dialogue.

For that, I wanted to reduce his speed to 0 as long as the dialogue menu is open.
That in itself is no problem, but after the dialogue I dynamically want to change the speed back to the value it was before.

I guess that means I got to save that value before setting it to 0, then returning to that saved value. How do I do that?
My example below does not work.

Thanks in advance!!

(It’s about playerController.speed and usedSpeed).

void OnGUI()
{
	if (showDialogue)
	{
		GameObject Dusty = GameObject.Find("Dusty");
		PlayerController playerController = Dusty.GetComponent<PlayerController>();

		usedSpeed = playerController.speed;
		playerController.speed = 0;

		GUILayout.BeginArea(new Rect(10,10,200,200));
		GUILayout.Label("Stop running around, will you?");
		GUILayout.Label("I really feel nervous about this.");

		if (GUILayout.Button("Yeah, me too."))
		{
			Time.timeScale= 1;
			showDialogue = false;
			playerController.speed = usedSpeed;
		}

		if (GUILayout.Button("Really? I'm rather excited!"))
		{
			Time.timeScale= 1;
			showDialogue = false;
			playerController.speed = usedSpeed;
		}

		GUILayout.EndArea();
	}

You’re setting usedSpeed to zero on the second iteration of the OnGUI loop. Let me explain:

First time showDialogue is true:

  1. usedSpeed is set to speed of playerController, e.g. 10.0f or whatever you have.
  2. playerController.speed is then set to 0.

Now, since this is running in the OnGUI loop, this code will run again if the player doesn’t press anything, so the second time this happens:

  1. usedSpeed is set to speed of playerController, and now the playerController.speed is 0, because you just set it to 0 in the last iteration of OnGUI, so now usedSpeed is 0 as well.

What you could do to solve this is to only set usedSpeed when playerController.speed is not 0, so it remains the same during a dialogue scene, e.g.:

if (showDialogue)
{
   GameObject Dusty = GameObject.Find("Dusty");
   PlayerController playerController = Dusty.GetComponent<PlayerController>();
	
	if (playerController.speed != 0) {
		usedSpeed = playerController.speed;
	}
	
   playerController.speed = 0;

   GUILayout.BeginArea(new Rect(10,10,200,200));
   GUILayout.Label("Stop running around, will you?");
   GUILayout.Label("I really feel nervous about this.");

   if (GUILayout.Button("Yeah, me too."))
   {
     Time.timeScale= 1;
     showDialogue = false;
     playerController.speed = usedSpeed;
   }

   if (GUILayout.Button("Really? I'm rather excited!"))
   {
     Time.timeScale= 1;
     showDialogue = false;
     playerController.speed = usedSpeed;
   }

   GUILayout.EndArea();
}