2016-11-06 3 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은 각 버튼의 상태를 저장하고 오른쪽 버튼에 올바른 값을로드하는 작업을 담당합니다.