-2
\$\begingroup\$

I have a small problem. in the game that I'm creating I created an array of items, each item includes a number of variables (cost, level, etc.). my goal is to save your own variables for each item, with the use of PlayerPrefs. These are my two scripts.

in this first script I create the array called (public Item_Manager [] items;), and in the second script initialize variables for each item dell'aray. I tried to save the values in the second script but then when I open the game again, all items are saved with the same variables.

Therefore, how can I do to save every variable of each item in the array with PlayerPrefs?

The variables are:

public float costo;
public float tickValue;
public float count;

This is the First Script

public class Proiettili_Per_Secondo : MonoBehaviour {

public UnityEngine.UI.Text bpsDisplay;
public Click click;
public Item_Manager[] items;

void Start(){
    StartCoroutine (AutoTick ());
}

void Update (){
    bpsDisplay.text = ConvertiroreProiettili.Instance.GetCurrencyInString 
        (GetPallottoleOgnISecondo (), true, false);
}

public float GetPallottoleOgnISecondo(){
    float tick = 0;
    foreach (Item_Manager item in items) {
        tick += item.count * item.tickValue;
    }
    return tick;
}

public void AutoProiettiliPerSec(){
    click.proiettili += GetPallottoleOgnISecondo () / 10;
}

IEnumerator AutoTick(){
    while (true) {
        AutoProiettiliPerSec();
        yield return new WaitForSeconds(0.10f);
    }
}
}

This is the second script

public class Item_Manager : MonoBehaviour {

public UnityEngine.UI.Text titolo;
public UnityEngine.UI.Text costo_;
public UnityEngine.UI.Text livello;
public UnityEngine.UI.Text valore_da_aggiungere;
public Color standard;
public Color caricamento;
public Click click;
public float costo;
public float tickValue;
public float count;
public string costo_stringa; ///NECESSARIO PER TRASFORAMARE IL VALORE COSTO IN UNO PIU CORTO (K, MILLIOM)
public string itemName;
private float baseCost;
private Slider _slider;

void Start () {
    baseCost = costo;
    _slider = GetComponentInChildren<Slider> ();
}

void Update () {
    titolo.text = itemName ;
    costo_.text = (costo_stringa = ConvertiroreProiettili.Instance.GetCurrencyInString (costo, false, false));
    livello.text = "Liv: " + count;
    valore_da_aggiungere.text = "+ " + tickValue + "/Sec";

    _slider.value = click.proiettili / costo * 100;
    if (_slider.value >= 100) {
        GetComponent<Image> ().color = caricamento;
    } else {
        GetComponent<Image> ().color = standard;
    }
}

public void PurchasedItem () {
    if (click.proiettili >= costo) {
        click.proiettili -= costo;
        count += 1;
        costo = Mathf.Round (baseCost * Mathf.Pow(1.50f, count));
    }
}
}
\$\endgroup\$
  • \$\begingroup\$ I'm noticing some of your variable names may have to do with costs/prices/currency. PlayerPrefs is often not an ideal way to store sensitive information like in-game currencies, because users can easily edit the file to change the values. The Unity team recommends using PlayerPrefs only for preference data - like controls or language settings - and use a separate save file for data that affects gameplay. Also, you tagged the question vertex-arrays, but I don't see anything in here about vertices? \$\endgroup\$ – DMGregory May 24 '15 at 21:01
  • \$\begingroup\$ vertexarray, I must be wrong \$\endgroup\$ – user12 May 24 '15 at 21:08
  • \$\begingroup\$ You should not store data in PlayerPrefs (it's only meant for settings). Instead use the file system. And, in case you don't want the players to mess around with the save file, you should use a binary file. \$\endgroup\$ – zoran404 May 24 '15 at 21:46
2
\$\begingroup\$

PlayerPrefs are not designed for saving scores. They are easily modifiable by the end user in a text file. Instead, you should serialize settings, replays, etc. that players have no motivation to hack.

Knowing that, this is how you save to PlayerPrefs:

int Birthday;
void Start ()
{
    Birthday = 172589;
    PlayerPrefs.SetInt ("My Birthday", Birthday);
}

For saving an array, you can serialize it as a string then save the string to PlayerPrefs. I.e.:

//Serializes an int[] into a string then saves it into PlayerPrefs
void SaveIntArray (string Name, int[] IntArray)
{
    string SerializedArray = "";
    string += BytesToString(System.BitConverter.GetBytes (IntArray.Length));
    for (int i = 0; i < IntArray.Length; i++)
    {
        SerializedArray += BytesToString(System.BitConverter.GetBytes(IntArray[i]));
    }
    PlayerPrefs.SetString (Name, SerializedArray);
}

//Gets a string form player prefs and deserializes it as an int[]
int[] GetIntArray (string Name)
{
    string SerializedArray = PlayerPrefs.GetString (Name);
    byte[] SerializedArrayBytes = new byte[SerializedArray.Length]
    for (int i = 0; i < SerializedArray.Length; i++)
    {
        SerializedArrayBytes[i] = (byte)SerializedArray[i];
    }
    int IntArrayLength = BitConverter.ToInt32 (SerializedArrayBytes, 0);
    int[] IntArray = new int[IntArrayLength];

    SerializationPosition = 4;
    for (int i = 0; i < IntArrayLength; i+=1)
    {
        IntArray[i] = BitConverter.ToInt32(SerializedArrayBytes, SerializationPosition);
        SerializationPosition += 4;
    }
}

//Converts an array of bytes to a string
string BytesToString (byte[] bites)
{
   string ret = "";
   for (int i = 0; i < bites.Length; i++)
   {
       ret += (char)bites[i];
   }
}

Alternatively, you can use PlayerPrefsX which has many more such extensions implemented.

If you're making a game for iOS, consider using UnityEngine.Social for saving scores which will save data on a Game Center server that will be unmodifiable except through your game's code.

\$\endgroup\$
  • \$\begingroup\$ ok, but how can I do this for each item in the array? \$\endgroup\$ – user12 May 24 '15 at 21:54
  • \$\begingroup\$ Unity PlayerPrefs don't support arrays by default but you can pretty easily serialize the array as a string and save the string to player prefs. This is what ArrayPrefs2 does: wiki.unity3d.com/index.php/ArrayPrefs2. \$\endgroup\$ – JPtheK9 May 24 '15 at 22:03
  • \$\begingroup\$ Posted some example code for saving an int[] into PP then retrieving it. \$\endgroup\$ – JPtheK9 May 24 '15 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.