เรามาดูวิธีการใช้งานกันดีกว่า
1. ให้ทำการสร้าง C# Script (PlayerData.cs) และทำการเพิ่ม
using UnityEngine;
using System.Collections;
public class PlayerData : MonoBehaviour
{
// สำหรับกำหนดตำแหน่ง GUI
public Rect saveRect;
public Rect loadRect;
public Rect scoreRect;
public Rect playerNameRect;
// สำหรับเก็บค่า Player
private int score = 0;
private string name = "Player : Unity";
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
++score;
}
}
void OnGUI()
{
// แสดง ชื่อ, คะแนน, ปุ่มโหลด และ ปุ่มเซฟ
GUI.Label(playerNameRect, name);
GUI.Label(scoreRect, "Score : " + score);
if (GUI.Button(saveRect, "Save Data"))
{
SavePlayerData();
}
if (GUI.Button(loadRect, "Load Data"))
{
LoadPlayerData();
}
}
// เซฟคะแนน และ ชื่อ ลง PlayerPrefs
private void SavePlayerData()
{
PlayerPrefs.SetInt("Score", score);
PlayerPrefs.SetString("Player Name", name);
PlayerPrefs.Save();
}
// โหลดคะแนน
private void LoadPlayerData()
{
if (PlayerPrefs.HasKey("Player Name"))
{
score = PlayerPrefs.GetInt("Score");
}
}
}
4. Stop Game และ Run Game อีกครั้งจากนั้นกดปุ่ม Load Data จะเห็นได้ว่า Score จะถูกโหลดเข้ามาจากค่า PlayerPrefs
เท่านี้ก็สามารถนำไปประยุกต์ในเกมได้แล้วครับ
ปล. มีอะไรแนะนำได้นะครับ
NO GAME NO DREAM!!!!