Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved How to set placeholder for playerpref if there are none.

Discussion in 'Scripting' started by joshuaradec, Oct 21, 2021.

  1. joshuaradec

    joshuaradec

    Joined:
    Jun 14, 2019
    Posts:
    14
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using TMPro;
    6.  
    7. //this script is a temp band-aid solution so that whatever user input in user data gets saved and shown after each restarts
    8. public class SaveUserData : MonoBehaviour
    9. {
    10.  
    11.     public TMP_InputField Country;
    12.     public TMP_InputField Occupation;
    13.     public TMP_InputField Age;
    14.  
    15.     public TMP_Text inCountry;
    16.     public TMP_Text inOccupation;
    17.     public TMP_Text inAge;
    18.  
    19.     public void ClickSaveButton()
    20.     {
    21.         PlayerPrefs.SetString("Country", Country.text);
    22.         PlayerPrefs.SetString("Occupation", Occupation.text);
    23.         PlayerPrefs.SetString("Age", Age.text);
    24.         Debug.Log("You are from " + PlayerPrefs.GetString("Country"));
    25.         Debug.Log("Your occupation is " + PlayerPrefs.GetString("Occupation"));
    26.         Debug.Log("Your age is " + PlayerPrefs.GetString("Age"));
    27.  
    28.     }
    29.  
    30.     private void Start()
    31.     {
    32.         inCountry.text = PlayerPrefs.GetString("Country");
    33.         inOccupation.text = PlayerPrefs.GetString("Occupation");
    34.         inAge.text = PlayerPrefs.GetString("Age");
    35.  
    36.     }
    37. }
    38.  
    I am trying to make it so that in the event that the app run for the first time, there will be a placeholder string. I have yet to figure out on how to do so, any help would be appreciated.
     
  2. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,363
    https://docs.unity3d.com/ScriptReference/PlayerPrefs.GetString.html

    If you notice the top of this documentation page for PlayerPrefs.GetString(), you will see two declarations. Your code is using the function form listed at the top, just passing one argument like "Country". You can also pass the defaults you want.

    Code (CSharp):
    1.          inCountry.text = PlayerPrefs.GetString("Country", "Romania");
    2.         inOccupation.text = PlayerPrefs.GetString("Occupation", "Oral Phlebotomist");
    3.         inAge.text = PlayerPrefs.GetString("Age", "2000");
    4.  
     
  3. joshuaradec

    joshuaradec

    Joined:
    Jun 14, 2019
    Posts:
    14
    I see, thank you for your guidance.