2016-11-06 59 views
0

我想在遊戲中製作一個簡單的角色店。我做了4個UI按鈕,每個按鈕在點擊時調用BuySkin函數。這是通用腳本,我把這些按鈕中的每一個,然後我只是調整了像價格這樣的變量。我在保存店鋪狀態方面遇到問題。我想到的第一件事就是這個。但是當我購買一個角色然後重新開始遊戲時,所有角色都會解鎖。有什麼建議麼?儲蓄店狀態

using UnityEngine; 
using UnityEngine.UI; 
using System.Collections; 
using System; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.IO; 

public class Button : MonoBehaviour { 

public int price = 100; 
public int bought = 1; 

public AnimatorOverrideController overrideAnimator; 

private PlayerController player; 
private Text costText; 

void Start() 
{ 
    player = GameObject.FindObjectOfType<PlayerController>(); 
    costText = GetComponentInChildren<Text>(); 
    costText.text = price.ToString(); 
    Load(); 

    if (bought == 2) 
    { 
     costText.enabled = false; 
    } 
    else 
    { 
     costText.enabled = true; 
    } 
} 

public void BuySkin() 
{ 
    if(CoinManager.coins >= price) 
    { 
     if(bought == 1) 
     { 
      player.GetComponent<Animator>().runtimeAnimatorController = overrideAnimator; 
      bought = 2; 
      CoinManager.coins -= price; 
      costText.enabled = false; 
      Save(); 
     } 
    } 
    if (bought == 2) 
    { 
     player.GetComponent<Animator>().runtimeAnimatorController = overrideAnimator; 
    } 
} 

public void Save() 
{ 
    BinaryFormatter bf = new BinaryFormatter(); 
    FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.shopstates"); 
    ShopData data = new ShopData(); 
    data.bought = bought; 

    bf.Serialize(file, data); 
    file.Close(); 
} 

public void Load() 
{ 
    if (File.Exists(Application.persistentDataPath + "/playerInfo.shopstate")) 
    { 
     BinaryFormatter bf = new BinaryFormatter(); 
     FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.shopstates", FileMode.Open); 
     ShopData data = (ShopData)bf.Deserialize(file); 
     file.Close(); 

     bought = data.bought; 
    } 
} 
} 

[Serializable] 
class ShopData 
{ 
    public int bought; 
} 

回答

0

發現問題很簡單。

當您按下按鈕並保存狀態時,您的"playerInfo.shopstate"將包含data.bought = 2。下次您加載遊戲時,每個按鈕都會調用Load()方法,並且每個按鈕都將讀取相同的文件。因爲文件有2,每個按鈕都會得到bought = 2;

請考慮您的所有按鈕都屬於同一商店,但每個商店都有獨特的狀態。有幾種方法可以解決它,例如ShopManager可以保存每個按鈕的狀態,並負責爲右按鈕加載正確的值。