- Home /
Trying to save/load from PlayerPrefs to Array and vice-versa
I'm trying to keep a ranking. When i test with a simple float variable it works fine, the code is this:
var controller : Component;
var ranking : float;
var done : boolean;
function Start () {
controller = GetComponent("GameController");
pegaRanking();
}
function Update () {
if (controller.end && !done){
rankeia(controller.time);
setaRanking();
showRanking();
done = true;
}
}
function pegaRanking(){
if(PlayerPrefs.HasKey("lugar")) ranking = PlayerPrefs.GetFloat("lugar");
}
function setaRanking(){
PlayerPrefs.SetFloat("lugar",ranking);
}
function rankeia(tempo : float){
if(ranking == null){
ranking = tempo;
return;
}
if(tempo > ranking) ranking = tempo;
}
function showRanking(){
Debug.Log(ranking);
}
but when i make ranking into a float[], it simply doesnt work. I've been testing with the very same code, like this:
var controller : Component;
var ranking : float[];
var done : boolean;
function Start () {
controller = GetComponent("GameController");
pegaRanking();
}
function Update () {
if (controller.end && !done){
rankeia(controller.time);
setaRanking();
showRanking();
done = true;
}
}
function pegaRanking(){
if(PlayerPrefs.HasKey("lugar")) ranking[0] = PlayerPrefs.GetFloat("lugar");
}
function setaRanking(){
PlayerPrefs.SetFloat("lugar",ranking[0]);
}
function rankeia(tempo : float){
if(ranking[0] == null){
ranking[0] = tempo;
return;
}
if(tempo > ranking[0]) ranking[0] = tempo;
}
function showRanking(){
Debug.Log(ranking[0]);
}
the only difference is that there's a [0] after every ranking. why does it not work?
thanks in advance
Answer by fafase · May 23, 2014 at 07:56 PM
Your array does not exist.
When you do:
var ranking:float[];
you are creating the reference to an array of float, this is just information for the compiler to use the reference, but you still need to create the location of the array:
var ranking:float[] = new float[10];
now I have the reference for an array of type float and I also create 10 locations for float. The beginning of those 10 locations is given to the reference, now I can place value in the array:
ranking[0] = value;