Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

PlayerPref not saving ?

Discussion in 'Scripting' started by Mattyerial, Oct 14, 2018.

  1. Mattyerial

    Mattyerial

    Joined:
    Oct 5, 2018
    Posts:
    51
    I want my object to delete if it has already been picked up the next time the game starts.
    Am i doing this right ?


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class KeySave : MonoBehaviour {
    7.  
    8.     public int got;
    9.  
    10.         public void awake (){
    11.        
    12.         got = PlayerPrefs.GetInt ("Key");
    13.         if (PlayerPrefs.GetInt ("Key") == 1)
    14.             Object.Destroy (gameObject);
    15.             }
    16.  
    17.     public void OnTriggerEnter2D(Collider2D other){
    18.        
    19.         if (other.tag == "Player") {
    20.             PlayerPrefs.SetInt("key", 1);
    21.             PlayerPrefs.Save ();
    22.         }
    23.     }
    24. }
    25.  
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,907
    Code (CSharp):
    1. public void Awake (){
    C# is case-sensitive.
     
  3. AdamRamberg

    AdamRamberg

    Joined:
    Dec 8, 2016
    Posts:
    22
    @LurkingNinjaDev answer will probably fix your problem, but you might also want to add a default value of 0 when you are getting the key:
    Code (CSharp):
    1. got = PlayerPrefs.GetInt ("Key", 0);
     
  4. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,907
    If we're digging deeper, than the
    Code (CSharp):
    1. if (PlayerPrefs.GetInt ("Key") == 1)
    also should be
    Code (CSharp):
    1. if (got == 1)
     
  5. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    There's also a method to check if the key exists already, which is PlayerPref.HasKey(...).
     
  6. Mattyerial

    Mattyerial

    Joined:
    Oct 5, 2018
    Posts:
    51
    I have solved it. The first k in Key was in capitals.
    Thank you for the help.