2016-11-06 65 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可以保存每个按钮的状态,并负责为右按钮加载正确的值。