Home > Mobile >  Why is my Float words setting its self to 0 without me setting it, this is the only script with .Set
Why is my Float words setting its self to 0 without me setting it, this is the only script with .Set

Time:10-08

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scriptname : MonoBehaviour
{
   private string Words;
   public float ShowPrefs;

   private void Start()
   {
        PlayerPrefs.DeleteKey("C");
       
        Words = this.gameObject.name;
        PlayerPrefs.SetFloat(Words, 2);
        PlayerPrefs.Save();
   }

   private void Update()
   {
        ShowPrefs = PlayerPrefs.GetFloat(Words);

        if (PlayerPrefs.GetFloat(Words) == 2)
        {
            PlayerPrefs.DeleteKey(Words);
        }
        if (PlayerPrefs.GetFloat(Words) == 1)
        {
            PlayerPrefs.SetFloat(Words, 1);
        }
     }

     private void OnTriggerStay(Collider other)
     {
           if (other.gameObject.name == Words)
           {
                 PlayerPrefs.SetFloat(Words, 1);
                 PlayerPrefs.Save();
           }
           else
           { 
                 PlayerPrefs.SetFloat(Words, 2);
                 PlayerPrefs.Save();
           }
     }
}

The Playerpref.GetFloat(Words); is setting itself to 0 for some reason even if I restart my unity many times. Been Googling and not finding my answers online so am asking here, if anyone know please kindly help me with my foolish brain, thank you!

CodePudding user response:

In Start you do

PlayerPrefs.SetFloat(Words, 2);

so in the very first Update it matches

if (PlayerPrefs.GetFloat(Words) == 2)

so you do

PlayerPrefs.DeleteKey(Words);

which means in the next frame

ShowPrefs = PlayerPrefs.GetFloat(Words);

will return 0.

The same happens if you collide wit anything that is not matching the name.


This

if (PlayerPrefs.GetFloat(Words) == 1)
{
    PlayerPrefs.SetFloat(Words, 1);
}

is pretty unnecessary ... if the value 1 is already stored, then what good is it to store he same value again?


So if I simply comment out that block

//if (PlayerPrefs.GetFloat(Words) == 2)
//{
//    PlayerPrefs.DeleteKey(Words);
//}

it works for me as "expected" (I guess)

enter image description here

  • Related