I want to pass variable values between scenes in unity, I've tried using static variables but it gives me an error when I try to edit it.
Asked
Active
Viewed 75 times
-1
-
2Has been answered [here](https://stackoverflow.com/questions/32306704/how-to-pass-data-and-references-between-scenes-in-unity) – TEEBQNE Oct 14 '21 at 23:46
1 Answers
1
Use PlayerPrefs
to store values. For example, If I wanted to a variable, I would go into the script then enter:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SceneSwitch : MonoBehaviour {
//Declare variable
int var1 = 2f;
//Go into where you would move then use PlayerPrefs to store values
void SwitchScene() {
PlayerPrefs.SetInt("var", var1);
PlayerPrefs.Save();
}
//Load the values from another scene (put this into another script)
int LoadThing() {
return PlayerPrefs.GetInt("var");
}
}
-
I would not update the player prefs in any `Update` function. You can determine when a scene is loading/unloading. Setting and saving player prefs that frequently is not performant at all. – TEEBQNE Oct 14 '21 at 23:47
-