- Home /
How to save an item as bought in player prefs?
I have a Character Selection scene, in which you can see the characters once at a time and see the next or the previous one by ui buttons. Recently I've added money, and works perfectly, but I can't get to buy a character, and then save it in order to avoid having to buy it again. I have tried PlayerPrefsX, and i have an "Items bought" list but it all confuses me a bit. (Sorry for the long script)
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
public class CharacterSelection : MonoBehaviour
{
private GameObject[] characterList;
private int index;
public List<GameObject> ItemsBought = new List<GameObject> ();
public Button selectShipButton;
public Button buyShipButton;
public int cost;
public Text moneyText;
void Start ()
{
index = PlayerPrefs.GetInt ("CharacterSelected");
characterList = new GameObject[transform.childCount];
for (int i = 0; i < transform.childCount; i++) {
characterList [i] = transform.GetChild (i).gameObject;
}
foreach (GameObject go in characterList) {
go.SetActive (false);
}
if (characterList [index]) {
characterList [index].SetActive (true);
}
ItemsBought.Add (characterList [0]);
selectShipButton.interactable = false;
moneyText.text = "" + MoneyScript.money.ToString();
}
void Update ()
{
if (ItemsBought.Contains (characterList [index])) {
buyShipButton.interactable = false;
selectShipButton.interactable = true;
}
}
public void ToggleLeft ()
{
characterList [index].SetActive (false);
index--;
if (index < 0) {
index = characterList.Length - 1;
}
characterList [index].SetActive (true);
buyShipButton.interactable = true;
selectShipButton.interactable = false;
}
public void ToggleRight ()
{
characterList [index].SetActive (false);
index++;
if (index > characterList.Length - 1) {
index = 0;
}
characterList [index].SetActive (true);
buyShipButton.interactable = true;
selectShipButton.interactable = false;
}
public void SelectShip ()
{
PlayerPrefs.SetInt ("CharacterSelected", index);
SceneManager.LoadScene ("MainLevel");
}
public void Buy ()
{
if (MoneyScript.money >= cost) {
ItemsBought.Add (characterList [index]);
MoneyScript.money -= cost;
PlayerPrefs.SetInt ("Money", MoneyScript.money);
moneyText.text = "" + MoneyScript.money.ToString();
Debug.Log (MoneyScript.money);
} else {
Debug.Log ("Not enough money");
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How can I use 'buy character button'? 1 Answer
Playerprefs not working on android 0 Answers
Saving a list of items 1 Answer
How to save gameobject values with respect to scene? 1 Answer