- Home /
Carry a boolean value from scene to scene?
Hi I'm making a text game in C# and I want certain Boolean variables to carry there values from one scene to another scene.
Say I have a scene with the variable
public bool weapon = true;
and the next scene has this value by default
public bool weapon = false;
How would would I get the first scenes value to carry over to the second scene?
Thanks
Answer by DoTA_KAMIKADzE · Apr 24, 2015 at 03:33 PM
If you want just few boolean values then I'd recommend just to set them as static variables, like this:
public static bool weapon = true;
Though if you have plenty of them and want to keep them with whole class/object holder or you might happen to have few instances of that class and want to keep values independant you might want to use DontDestroyOnLoad.
Just read through both links that I've provided above^ and choose whichever suits you more.
Cool thanks. This does the job as I only have a couple of boolean values :)
Answer by Jessespike · Apr 24, 2015 at 03:33 PM
Add the static keyword:
public static bool weapon;
Another option is to have some type of Manager behaviour that has DonDestroyOnLoad called.
Answer by InfernoZYB · Apr 24, 2015 at 04:07 PM
I recommend you check out PlayerPrefs. "PlayerPrefs".
Here is you're script modified that should work. Also with this method you could add a "save" feature. Now since you did not provide me with a full code you will need to make modifcations but you should get a base idea. (If you want sent the full code in a comment and I will add this stuff)
using UnityEngine;
using System.Collections;
public class KeepVar : MonoBehaviour {
public bool weapon;
int weaponInt = 0;
public string Scene;
// Use this for initialization
void Start () {
if (PlayerPrefs.GetInt ("pweapon") == 1) {
weapon = true;
} else {
weapon = false;
}
}
// Update is called once per frame
void Update () {
if (weapon == true) {
weaponInt = 1;
}
if (weapon == false) {
weaponInt = 0;
}
if (Input.GetKeyDown (KeyCode.W)) {
PlayerPrefs.SetInt("pweapon", weaponInt);
Application.LoadLevel(Scene);
}
}
}
Thanks for the comment. $$anonymous$$ay try that in the future when I've got more boolean values. At the moment I only have a couple so I'm using static booleans.
Yea I totally forgot about static variables xP. But with this way if you go onto the link I have in my answer you can make a save feature. Which is why this first came to $$anonymous$$d. And I use this a lot.
Inferno Could I add a script I've been working on and could you see if you could make it work like you did that script you posted.