Hello i am making my first game and I finished adding the quality settings to my game how do i save the players options so that the option is always chosen even after quitting the game.I tried watching tutorials but it does not work
i just want the saving of the options the player chooses even after game is closed
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class SettingsMenu : MonoBehaviour
{
public TMPro.TMP_Dropdown resolutionDropdown;
Resolution[] resolutions;
private void Start()
{
int CurrentResolutionIndex = 0;
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolutionIndex = 0;
for (int i = 0; i < resolutions.Length; i++)
{
string Option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(Option);
if (resolutions[i].width == Screen.currentResolution.width &&
resolutions[i].height == Screen.currentResolution.height)
{
CurrentResolutionIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = CurrentResolutionIndex;
resolutionDropdown.RefreshShownValue();
}
public void SetResolution(int ResolutionIndex)
{
Resolution resolution = resolutions[ResolutionIndex];
Screen.SetResolution(resolution.width, resolution.height, Screen.fullScreen);
}
public void SetQuality(int qualityIndex)
{
QualitySettings.SetQualityLevel(qualityIndex);
}
public void SetFullscreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
}
}
Your settings can be represented as individual integers and floats, you just need to save every parameter you need.
Related
I had a script that controlled my main menu that was on a GameObject and moved it to another gameobject and reconnected all the loose ends. now for some reason none of my buttons work, even with highlighting.
just had two gameobjects and moved the script between them using the editor
the script itself doesnt do much, just this:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public GameObject mainMenu;
public GameObject optionsMenu;
public GameObject modeMenu;
public Dropdown resolutionDropdown;
private Resolution[] resolutions;
public Toggle fullscreenToggle;
public void StartGameLocal()
{
SceneManager.LoadScene("Local2P");
}
public void StartGameAI()
{
SceneManager.LoadScene("AI2P");
}
public void MenuToOptions()
{
mainMenu.SetActive(false);
optionsMenu.SetActive(true);
}
public void OptionsToMenu()
{
mainMenu.SetActive(true);
optionsMenu.SetActive(false);
}
public void MenuToMode()
{
mainMenu.SetActive(false);
modeMenu.SetActive(true);
}
public void ModeToMenu()
{
mainMenu.SetActive(true);
modeMenu.SetActive(false);
}
public void ExitGame()
{
Application.Quit();
}
void Start()
{
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolutionIndex = 0;
for (int i = 0; i < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.width && resolutions[i].height == Screen.height)
currentResolutionIndex = i;
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
if (Screen.fullScreen == true)
{
fullscreenToggle.isOn = true;
}
}
public void SetResolution(int resolutionIndex)
{
Resolution resolution = resolutions[resolutionIndex];
Screen.SetResolution(resolution.width,
resolution.height, Screen.fullScreen);
PlayerPrefs.SetInt("ResolutionPreference", resolutionDropdown.value);
}
public void SetFullscreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
if (isFullscreen)
{
PlayerPrefs.SetInt("FullscreenPreference", 1);
}
else
{
PlayerPrefs.SetInt("FullscreenPreference", 0);
}
}
void Update()
{
if (Input.GetKey(KeyCode.Escape))
{
if (optionsMenu.activeSelf)
{
OptionsToMenu();
}
else if (optionsMenu.activeSelf)
{
ModeToMenu();
}
else
{
Application.Quit();
}
}
}
}
i dont know how to fix this and why my buttons just stopped working, even after reconnecting everything, but please help!
p.s. havent checked the update code to see if it worked, if yall have suggestions let me know
Your buttons likely pointed to the functions in this script in their OnClick handlers. If you moved the location of the script, you need to go to each of the buttons and hook those handlers back up.
I have been working on a customization system that allows a player to customize their skin color and particle trail of their character. I have the system working and am now attempting to save the data through JsonUtility and then load it. I plan on saving the data with the play button then transitioning to a new scene and having it load at start() of the new scene. But, for testing I have been using a load button as it should still work...but it doesn't.
My current SaveSystem script is supposedly working since the DebugLog "Save file created" for saving files appears when the button is pressed. But, when pressing the load button nothing changes yet the DebugLog "Save file found and loaded" still appears. I am kinda lost as to where to go and how to load the data into the Customization script since I am still new to C# Json and serializing in general.
Here are my 3 scripts:
SaveSystem Script
using UnityEngine;
using System.IO;
public static class SaveSystem
using UnityEngine;
using System.IO;
public static class SaveSystem
{
public static string directory = "/saveData";
public static string fileName = "MyData.txt";
public static void SavePlayer(Customization CurrentCustomization)
{
string dir = Application.persistentDataPath + directory;
if(!Directory.Exists(dir))
Directory.CreateDirectory(dir);
Debug.Log("Save file created");
string json = JsonUtility.ToJson(CurrentCustomization);
File.WriteAllText(dir + fileName, json);
}
public static Customization LoadPlayer()
{
string fullPath = Application.persistentDataPath + directory + fileName;
Customization CurrentCustomization = new Customization();
if(File.Exists(fullPath))
{
string json = File.ReadAllText(fullPath);
CurrentCustomization = JsonUtility.FromJson<Customization>(json);
Debug.Log("Save file found and loaded");
}
else
{
Debug.Log("Save file does not exist");
}
return CurrentCustomization;
}
}
CharacterCustomizaiton Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class CharacterCustomization : MonoBehaviour
{
public List<Customization> Customizations;
public int currentCustomizationIndex;
public Customization CurrentCustomization {get; private set;}
[SerializeField] private TextMeshProUGUI bodyColorText;
[SerializeField] private TextMeshProUGUI trailText;
public void Save()
{
SaveSystem.SavePlayer(CurrentCustomization);
}
public void Load()
{
CurrentCustomization = SaveSystem.LoadPlayer();
}
void Awake()
{
foreach(var customization in Customizations)
{
customization.UpdateSubObjects();
customization.UpdateRenderers();
}
}
public void SelectBodyColor(bool isForward)
{
currentCustomizationIndex = 0;
CurrentCustomization = Customizations[currentCustomizationIndex];
if(isForward)
{
CurrentCustomization.NextMaterial();
}
else
{
CurrentCustomization.PreviousMaterial();
}
bodyColorText.text = CurrentCustomization.materialIndex.ToString();
}
public void SelectLTrail(bool isForward)
{
currentCustomizationIndex = 1;
CurrentCustomization = Customizations[currentCustomizationIndex];
if(isForward)
{
CurrentCustomization.NextSubObject();
}
else
{
CurrentCustomization.PreviousSubObject();
}
trailText.text = CurrentCustomization.subObjectIndex.ToString();
}
public void SelectRTrail(bool isForward)
{
currentCustomizationIndex = 2;
CurrentCustomization = Customizations[currentCustomizationIndex];
if(isForward)
{
CurrentCustomization.NextSubObject();
}
else
{
CurrentCustomization.PreviousSubObject();
}
trailText.text = CurrentCustomization.subObjectIndex.ToString();
}
}
Customization Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Customization
{
public string DisplayName;
public List<Renderer> Renderers;
public List<Material> Materials;
public List<GameObject> SubObjects;
public int materialIndex;
public int subObjectIndex;
public void NextMaterial()
{
if(materialIndex == Materials.Count - 1)
{
materialIndex = 0;
}
else
{
materialIndex++;
}
UpdateRenderers();
}
public void PreviousMaterial()
{
if(materialIndex == 0)
{
materialIndex = Materials.Count - 1;
}
else
{
materialIndex--;
}
UpdateRenderers();
}
public void NextSubObject()
{
if(subObjectIndex == SubObjects.Count - 1)
{
subObjectIndex = 0;
}
else
{
subObjectIndex++;
}
UpdateSubObjects();
}
public void PreviousSubObject()
{
if(subObjectIndex == 0)
{
subObjectIndex = SubObjects.Count - 1;
}
else
{
subObjectIndex--;
}
UpdateSubObjects();
}
public void UpdateSubObjects()
{
for(var i = 0; i < SubObjects.Count; i++)
if (SubObjects[i])
SubObjects[i].SetActive(i == subObjectIndex);
}
public void UpdateRenderers()
{
foreach (var renderer in Renderers)
if (renderer)
renderer.material = Materials[materialIndex];
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class SettingsMenu : MonoBehaviour
{
public AudioMixer audioMixer;
public Dropdown resolutionDropdown;
Resolution[] resolutions;
void Start()
{
resolutions = Screen.resolutions;
resolutionDropdown.ClearOptions();
List<string> options = new List<string>();
int currentResolution;
for (int i = 0; i < resolutions.Length; i++)
{
string option = resolutions [i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width &&
resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
}
public void SetResolution (int resolutionIndex)
{
Resolution resolution = resolutions[resolutionIndex];
Screen.SetResolution(resolution. width, resolution.height, Screen.fullScreen);
}
public void SetVolume (float volume)
{
audioMixer.SetFloat("Volume", volume);
}
public void SetQuality (int qualityIndex)
{
QualitySettings.SetQualityLevel(qualityIndex);
}
public void SetFullScreen (bool isFullScreen)
{
Screen.fullScreen = isFullScreen;
}
}
pls help because the Unity Engine is making Errors that i dont understand maybe its the tutorial thats from 2017, i dont know but it would be great if you could help me. it has something to do with current Resolution Index if you need more context pls write me
Compiler Error CS0103 is caused by using an undeclared variable or method. This issue happens where the currentResolutionIndex variable is never defined in the file.
void Start()
{
/* Added the following line of code. To manage this condition when the condition is not always true, the variable must be initialized. */
int currentResolutionIndex = -1;
for (int i = 0; i < resolutions.Length; i++)
{
/* This condition may not always be true. */
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionIndex = i;
}
}
/* If the condition never works correctly, you should control and manage this condition. */
if(currentResolutionIndex != -1)
{
resolutionDropdown.value = currentResolutionIndex;
}
else
{
/* Exception Handling */
}
}
I want my money.text to be in my shop scene to buy some shield.
For some reason my money.text is only on the other scene and it's not going in the shop scene.
This is my shop script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ShopController : MonoBehaviour {
int MoneyAmount;
int isPowerup1Sold,isPowerup2Sold,isPowerup3Sold;
public Text MoneyAmountText;
public Button Buynow1,Buynow2,Buynow3;
// Use this for initialization
void Start () {
MoneyAmount = PlayerPrefs.GetInt ("moneyAmount");
}
// Update is called once per frame
void Update () {
MoneyAmountText.text = "Money : " + MoneyAmount.ToString ();
isPowerup1Sold = PlayerPrefs.GetInt ("isPowerup1Sold");
isPowerup2Sold = PlayerPrefs.GetInt ("isPowerup2Sold");
isPowerup3Sold = PlayerPrefs.GetInt ("isPowerup3Sold");
if (MoneyAmount >= 50 && isPowerup1Sold == 0)
Buynow1.interactable = true;
else
Buynow1.interactable = false;
if (MoneyAmount >= 70 && isPowerup2Sold == 0)
Buynow2.interactable = true;
else
Buynow2.interactable = false;
if (MoneyAmount >= 120 && isPowerup3Sold == 0)
Buynow3.interactable = true;
else
Buynow3.interactable = false;
}
public void buyPowerup1()
{
MoneyAmount -= 50;
PlayerPrefs.SetInt ("isPowerup1Sold", 1);
}
public void buyPowerup2()
{
MoneyAmount -= 70;
PlayerPrefs.SetInt ("isPowerup2Sold", 1);
}
public void buyPowerup3()
{
MoneyAmount -= 120;
PlayerPrefs.SetInt ("isPowerup3Sold", 1);
}
public void exitshop()
{
PlayerPrefs.SetInt ("moneyAmount", MoneyAmount);
Application.LoadLevel ("levelselect");
}
}
this is my money script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Money : MonoBehaviour {
public Text MoneyText;
public static int MoneyAmount = 0;
// Use this for initialization
void Start () {
MoneyAmount = PlayerPrefs.GetInt ("moneyAmount",0);
}
// Update is called once per frame
void Update () {
MoneyText.text = "Money" + MoneyAmount.ToString();
}
}
this is my shield.power script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Money : MonoBehaviour {
public Text MoneyText;
public static int MoneyAmount = 0;
// Use this for initialization
void Start () {
MoneyAmount = PlayerPrefs.GetInt ("moneyAmount",0);
}
// Update is called once per frame
void Update () {
MoneyText.text = "Money" + MoneyAmount.ToString();
}
}
This is where i put my money.text to show in the canvas scene.(the highlight blue color).
Text is an UI component for rendering strings on UI. Each scene need to have its own Text-component.
Then you need to keep the amount of money in one place so that every script dealing with money does not have its own MoneyAmount variable.
Money script could look like this:
public class Money : MonoBehaviour {
static int? cachedAmount = null;
const string playerPrefsKeyName = "moneyAmount";
const int startMoney = 0;
public static int Amount {
get {
if (cachedAmount == null) {
cachedAmount = PlayerPrefs.GetInt (playerPrefsKeyName, startMoney);
}
return cachedAmount.Value;
}
set {
if (cachedAmount == null || value != cachedAmount.Value) {
PlayerPrefs.SetInt (playerPrefsKeyName, value);
cachedAmount = value;
}
}
}
}
...and whenever you use money, you could use
if (Money.Amount >= 70) {
Money.Amount -= 70;
MoneyAmountText.text = "Money : " + Money.Amount.ToString ();
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
thanks for reading, I am working on a small memory card game in C# using Unity. When I run a certain scene I am receiving constant errors.
The errors are as follows:
"NullReferenceException: Object reference not set to an instance of an object
Card.SetUpArt () (at Assets/Scripts/Card.cs:31)
Pairs.SetUpDeck () (at Assets/Scripts/Pairs.cs:62)
Pairs.Update () (at Assets/Scripts/Pairs.cs:23)"
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Card : MonoBehaviour {
public static bool NO_TURN = false;
[SerializeField]
private int cardState; //state of card
[SerializeField]
private int cardNumber; //Card value (1-13)
[SerializeField]
private bool _setUp = false;
private Sprite cBack; //card back (Green square)
private Sprite cFace; //card face (1-10 JQKA)
private GameObject pairsManager;
void Begin()
{
cardState = 1; //cards face down
pairsManager = GameObject.FindGameObjectWithTag("PairsManager");
}
public void SetUpArt()
{
cBack = pairsManager.GetComponent<Pairs>().GetBack(); //<--error
cFace = pairsManager.GetComponent<Pairs>().GetFace(cardNumber);
turnCard();//turns the card
}
public void turnCard() //handles turning of card
{
if (cardState == 0)
{
cardState = 1;
}
else if(cardState == 1)
{
cardState = 0;
}
if (cardState == 0 && !NO_TURN)
{
GetComponent<Image>().sprite = cBack; // shows card back
}
else if (cardState == 1 && !NO_TURN)
{
GetComponent<Image>().sprite = cFace; // shows card front
}
}
//setters and getters
public int Number
{
get {return cardNumber;}
set { cardNumber = value;}
}
public int State
{
get { return cardState; }
set { cardState = value; }
}
public bool SetUp
{
get { return _setUp; }
set { _setUp = value; }
}
public void PairCheck()
{
StartCoroutine(pause ());
}
IEnumerator pause()
{
yield return new WaitForSeconds(1);
if (cardState == 0)
{
GetComponent<Image>().sprite = cBack;
}
else if (cardState == 1)
{
GetComponent<Image>().sprite = cFace;
}
}
}
And:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine;
public class Pairs : MonoBehaviour {
public Sprite[] cardFace; //array of card faces
public Sprite cardBack;
public GameObject[] deck; //array of deck
public Text pairsCount;
private bool deckSetUp = false;
private int pairsLeft = 13;
// Update is called once per frame
void Update () {
if (!deckSetUp)
{
SetUpDeck();
}
if (Input.GetMouseButtonUp(0)) //detects left click
{
CheckDeck();
}
}//Update
void SetUpDeck()
{
for(int i = 0; i <deck.Length; i++)//resets cards
{
deck[i].GetComponent<Card>().SetUp = false;
}
for (int ix = 0; ix < 2; ix++) //sets up cards twice,
{
for(int i = 1; i < 14; i++)//sets up card value (2-10 JQKA)
{
bool test = false;
int val = 0;
while (!test)
{
val = Random.Range(0, deck.Length);
test = !(deck[val].GetComponent<Card>().SetUp);
}//while
//sets up cards
deck[val].GetComponent<Card>().Number = i;
deck[val].GetComponent<Card>().SetUp = true;
}//nested for
}//for
foreach (GameObject crd in deck)
{
crd.GetComponent<Card>().SetUpArt();
}
if (!deckSetUp)
{
deckSetUp = true;
}
}//SetUpDeck
public Sprite GetBack()
{
return cardBack;
}//getBack
public Sprite GetFace(int i)
{
return cardFace[i - 1];
}//getFace
void CheckDeck()
{
List < int > crd = new List<int>();
for(int i = 0; i < deck.Length; i++)
{
if(deck[i].GetComponent<Card>().State == 1)
{
crd.Add(i);
}
}
if(crd.Count == 2)
{
CompareCards(crd);
}
}//CheckDeck
void CompareCards(List<int> crd)
{
Card.NO_TURN = true; //stops cards turning
int x = 0;
if(deck[crd[0]].GetComponent<Card>().Number ==
deck[crd[1]].GetComponent<Card>().Number)
{
x = 2;
pairsLeft--;
pairsCount.text = "PAIRS REMAINING: " + pairsLeft;
if(pairsLeft == 0) // goes to home screen when game has been won
{
SceneManager.LoadScene("Home");
}
}
for(int j = 0; j < crd.Count; j++)
{
deck[crd[j]].GetComponent<Card>().State = x;
deck[crd[j]].GetComponent<Card>().PairCheck();
}
}//CompareCards
}
Any help anyone can offer would be greatly appreciated. Thank you in advance.
Link to GitHub Repository
I don't have knowledge about C#, as I'm working with java. You should initialize your variables. For more information I found this link What is a NullReferenceException, and how do I fix it?