如何在Unity中保存项目列表?

时间:2017-09-22 14:33:48

标签: c# list unity3d save 2d

我不知道如何保存我拥有的List<T>项目以及库存脚本和数据库项目脚本。我想保存我库存中的物品,但我不知道如何。我尝试创建一个类并创建一个Update()函数,但id不起作用。它给了我一个错误

  

inventory<item>无法反序列化

请问我该如何保存这些物品?

以下是包含保存/加载功能的播放器数据的脚本。

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

    public class PlayerData : MonoBehaviour {

        public int HP,MP,HPMAX,MPMAX,STR,DEF,EXP,LVL;
        public Text HPtext,MPtext,STRtext,DEFtext,LVLtext,amountTxt;
        public static PlayerData Pdata;
        public GameObject player;
        public int amount = 20;
        public bool UseKey;
        public bool poisened;
        public float counter = 5;
//==============================================================
        public List<Item> Inventory = new List<Item> ();
//==============================================================

        public float x,y ;
        inventoryTest inv;

        void Awake()
        {
            if(Pdata == null)
            {
                DontDestroyOnLoad(gameObject);
                Pdata = this;
            }
            else if(Pdata != this)
            {
                Destroy(gameObject);
            }
        }

        void Start()
        {
            inv = GameObject.FindWithTag("Player").GetComponent<inventoryTest>();
            HP = 20;
            MP = 5;
            HPMAX = 20;
            MPMAX = 5;
            STR = 8;
            DEF = 8;
            EXP = 0;
            LVL = 1;
        }
        void Update()
        {
//==========================================
            Inventory = inv.Inventory;
//==========================================
            amountTxt.text = ""+amount;
            HPtext.text = ""+HP;
            MPtext.text = ""+MP;
            STRtext.text = ""+STR;
            DEFtext.text = ""+DEF;
            LVLtext.text = ""+LVL;
            x = player.transform.position.x;
            y = player.transform.position.y;

            if(HP > HPMAX){
                HP = HPMAX;
            }
            if(MP > MPMAX){
                MP = MPMAX;
            }
            if(MP <= 0){
                MP = 0;
            }
            if(HP <= 0){
                HP = 0;
            }

            if(amount <= 0){
                amount = 0;
            }
            if(amount >= 99){
                amount = 99;
            }

            if(EXP == 100){
                EXP = 0;
                LVL++;
                STR++;
                DEF++;
                HPMAX += 10;
                MPMAX += 5;
            }
            if(LVL == 99){
                LVL = 99;
            }
        }

        void FixedUpdate(){
            if(poisened){
                counter -= Time.deltaTime;
                if(counter < 0f){
                    HP -= 1;
                    counter = 5;
                }
            }
        }
        public void Save(){
            BinaryFormatter BF = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath + "/S_F.dat" );

            playerDataClass data = new playerDataClass();
            data.HP = HPMAX;
            data.MP = MPMAX;
            data.STR = STR;
            data.DEF = DEF;
            data.EXP = EXP;
            data.LVL = LVL;
            data.y = y;
            data.x = x;
//====================================
            data.Inventory = Inventory;
//====================================
            BF.Serialize(file,data);
            file.Close();

        }

        public void Load(){
            if(File.Exists(Application.persistentDataPath + "/S_F.dat")){

            BinaryFormatter BF = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/S_F.dat", FileMode.Open);
            playerDataClass data = (playerDataClass) BF.Deserialize(file);
            file.Close();
            HPMAX = data.HPMAX;
            MPMAX = data.MPMAX;
            HP = data.HP;
            MP = data.MP;
            STR = data.STR;
            DEF = data.DEF;
            EXP = data.EXP;
            LVL = data.LVL;
            x = data.x;
            y = data.y;
            player.transform.position= new Vector2(x,y);
            }
        }
    }


    [Serializable]
    public class playerDataClass
    {
        public int HPMAX,MPMAX,HP,MP,STR,DEF,EXP,LVL;
        public float x,y ;
//=======================================================
        public List<Item> Inventory = new List<Item> ();
//=======================================================

    }

这里编辑的是库存脚本

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class inventoryTest : MonoBehaviour {

    public Transform panel,MenuPosition,gPanelPosition;
    public List<Item> Inventory = new List<Item> ();
    public ItemDatabase data;
    public Text testText,saveTextl,USEtext,EQUIPtext;
    PlayerData Playerdata;
    PlayerControl contol;
    public Color saveColor;
    public bool Eaquiped;

     int GeneralMenu = 2;
     int optionMenu = 2;
     int Index3 = 0;
     int Index2 = 0;
     int Index = 0;

    public float Yoffset;
    public Image iconGeneral,iconMini,icon;
    public GameObject saveMessage,ave,arrowAmount,gPanel,itemOption,camerA,Menu;
    public bool A,B,moveup,movedown,SaveOptionAvalable,openOption,gOption,t,pressed,faceDoor;

     void Start(){
        contol = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerControl> ();
        Playerdata = GameObject.FindGameObjectWithTag ("Playerdata").GetComponent<PlayerData> ();
        data = GameObject.FindGameObjectWithTag ("database").GetComponent<ItemDatabase> ();
        camerA = GameObject.FindWithTag("MainCamera");

        Color colorT = saveColor;
        colorT.a = 0.1f;
        saveTextl.color = colorT;

        gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
        itemOption.SetActive(false);
        saveMessage.SetActive(false);
    }


        void Update (){
        t = true;

            if(SaveOptionAvalable){
            Color colorT = saveColor;
            colorT.a = 1f;
            saveTextl.color = colorT;
        }else if(!SaveOptionAvalable){
            Color colorT = saveColor;
            colorT.a = 0.1f;
            saveTextl.color = colorT;
            }

//====== Menu DESPLAY ==========================================================================================================================    

        //==for toch cotrole====================================================================================
        if (B && !pressed) {                    
            pressed = true;
            Menu.transform.position = new Vector2(camerA.transform.position.x,camerA.transform.position.y);
            Time.timeScale = 0;
            arrowAmount.SetActive(false);
            B = !B;

        }else if (B && pressed && !openOption && !gOption && !SaveOptionAvalable) {
            Time.timeScale = 1;
            pressed = !pressed;
            Menu.transform.position = new Vector2(MenuPosition.transform.position.x,MenuPosition.transform.position.y);
            if(contol.equipbow == true)
            {
            arrowAmount.SetActive(true);
            }
            B = !B;
        }
        else if (B && pressed && openOption){
            openOption = !openOption;
            itemOption.SetActive(false);
            Color colorT = saveColor;
            colorT.a = 1f;
            USEtext.color = colorT;
            EQUIPtext.color = colorT;
            B = !B;
        }

//====BACK TO GENERAL MENU===============================================================================================================
        //=====FOR TOCH CONTROL==============================================================================
        if(B && pressed && gOption) {
            gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
            gOption = !gOption;
            if(contol.inSaveErea == true){
                SaveOptionAvalable = true;
            }
            else if (contol.inSaveErea == false){
                SaveOptionAvalable = false;
            }
            B = !B;
        }
        if( A && pressed && !gOption) {
            if(Index3 == 0){
            gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x,gPanelPosition.transform.position.y);
            gOption = true;
            Debug.Log(gOption);
            SaveOptionAvalable = false;
            A =!A;
            }
            if(Index3 == 1 && SaveOptionAvalable && !gOption){
            saveMessage.SetActive(true);
            Debug.Log(SaveOptionAvalable);
            gOption = true;
            A =!A;
            }
    }
        //=====================================================================================================
        //==== KEYBOARD CONTROL================================================================================
//  if(Input.GetKeyDown (KeyCode.B)&& pressed && gOption ){
//          gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x * 500,gPanelPosition.transform.position.y *500);
//          gOption = !gOption;
//  }
//  if(Input.GetKeyDown(KeyCode.A) && pressed && !gOption){
//      if(Index3 == 0){
//          gPanel.transform.position = new Vector2(gPanelPosition.transform.position.x,gPanelPosition.transform.position.y);
//          gOption = true;
//          Debug.Log(gOption);
//          return;
//          }
//      if(Index3 == 1 && !SaveOptionAvalable){
//          }
//      if(Index3 == 2){
//        }
//  }

//=======================================================================================================================================
//===SAVE BITTON AND SAVE MESSAGE========================================================================================================

        //====TOUCH CONTROL===================================================================================================

        if(A && pressed && SaveOptionAvalable)
        {
            saveMessage.SetActive(false);
            Playerdata.Save();
            Debug.Log("SAVED");
            SaveOptionAvalable = !SaveOptionAvalable;
            gOption = !gOption;
            A = !A;

        }
        if(B && pressed && SaveOptionAvalable)
        {
            saveMessage.SetActive(false);
            SaveOptionAvalable = true;
            SaveOptionAvalable = !SaveOptionAvalable;
            Debug.Log("CANCELED");
            B = !B;
        }
        //===KEYBOARD CONTROL==================================================================================================

//=============================================================================================================================
//===UP/DOWN NAVIGATION MENU===================================================================================================
        //===TOUCH CONTROL==============================================================
        if(movedown && pressed && !gOption && !openOption ){
            movedown = !movedown;
                if(Index3 < GeneralMenu -1){
                    Index3++;
                    Vector2 position = iconGeneral.transform.position;
                    position.y -= Yoffset;
                    iconGeneral.transform.position = position;
                    return;
                }
        }   

        if(moveup && pressed && !gOption && !openOption){
            moveup = !moveup;
                if(Index3 > 0){
                    Index3--;
                    Vector2 position = iconGeneral.transform.position;
                    position.y += Yoffset;
                    iconGeneral.transform.position = position;
                    return;
                }
        }




//=======INVENTORY : Selectig Item With Up and Down Arrows and pressing A to Use and B to Cancel ============================================================================================================================
        for(int i = 0 ; i < Inventory.Count; i++){
            //===TOUCH CONTROL========================================================================================
            if(movedown && pressed){
                movedown = !movedown;
                if(Index < Inventory.Count -1 && !openOption ){
                    Index++;
                    Vector2 position = icon.transform.position;
                    position.y -= Yoffset;
                    icon.transform.position = position;
                    return;
                }if(Index2 < optionMenu -1 && openOption){
                        Index2++;
                        Vector2 position = iconMini.transform.position;
                        position.y -= Yoffset;
                        iconMini.transform.position = position;
                        return;
                }
            }
            if(moveup && pressed){
                moveup = !moveup;
                if(Index > 0 && !openOption ){
                    Index -- ;
                    Vector2 position = icon.transform.position;
                    position.y += Yoffset;
                    icon.transform.position = position;
                    return;
                }if(Index2 > 0 && openOption){
                        Index2--;
                        Vector2 position = iconMini.transform.position;
                        position.y += Yoffset;
                        iconMini.transform.position = position;
                        return;
                }
            }

            //===============================================================================================================
//======= USE/EQUIPE MENU ===================================================================================================
            //===TOUCH CONTROL===============================================================================================
            if(A && pressed && !openOption && gOption && !SaveOptionAvalable){
                openOption = true;
                itemOption.SetActive(true);
                A = !A;
            }


            if(A && openOption){
                openOption = !openOption;
            //===== IF PRESS USE TOUCH CONTROL=================================================================================================
        if(Index2 == 1)
            {
            if(Index == i){

                        if(Inventory[i].ItemId == 5 && contol.equipSword == true && contol.equipbow == false){

                            contol.equipSword = false;
                            contol.equipbow = true;
                            t = false;
                            var ttt = GameObject.Find("sword").GetComponent<Text>();
                            ttt.text = "sword" + "";
                            testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                            testText.text = Inventory [i].Itemname + "     <E>";
                            A =!A;
                        }
                        if(Inventory[i].ItemId == 4 && contol.equipSword == false && contol.equipbow == true){

                            contol.equipSword = true;
                            contol.equipbow = false;
                            t = false;
                            var ttt = GameObject.Find("bow").GetComponent<Text>();
                            ttt.text = "bow" + "";
                            testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                            testText.text = Inventory [i].Itemname + "   <E>";
                            A =!A;
                        }



                if(Inventory[i].ItemId == 4 && contol.equipSword == false)
                {
                    contol.equipSword = true;
                    contol.equipbow = false;
                    t = false;
                    testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                    testText.text = Inventory [i].Itemname + "   <E>";
                    A =!A;

                }

                    else if(Inventory[i].ItemId == 4 && contol.equipSword == true){

                        contol.equipSword = false;
                        contol.equipbow = false;
                        t = false;
                        testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                        testText.text = Inventory [i].Itemname;
                        A =!A;
                    }

                if(Inventory[i].ItemId == 5 && contol.equipbow == false)
                {
                    contol.equipbow = true;
                    contol.equipSword = false;
                    t = false;
                    testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                    testText.text = Inventory [i].Itemname + "     <E>";
                    A =!A;

                }

                    else if(Inventory[i].ItemId == 5 && contol.equipbow == true){

                        contol.equipbow = false;
                        contol.equipSword = false;
                        t = false;
                        testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                        testText.text = Inventory [i].Itemname;
                        A =!A;

                    }

                        if(Inventory[i].ItemId == 0)
                        {
                            Color colorT = saveColor;
                            colorT.a = 0.1f;
                            EQUIPtext.color = colorT;
                            A =!A;
                        }
                        if(Inventory[i].ItemId == 1)
                        {
                            Color colorT = saveColor;
                            colorT.a = 0.1f;
                            EQUIPtext.color = colorT;
                            A =!A;
                        }
                        if(Inventory[i].ItemId == 2)
                        {
                            Color colorT = saveColor;
                            colorT.a = 0.1f;
                            EQUIPtext.color = colorT;
                            A =!A;
                        }
                        if(Inventory[i].ItemId == 3)
                        {
                            if(!faceDoor){
                            Color colorT = saveColor;
                            colorT.a = 0.1f;
                            EQUIPtext.color = colorT;
                            A =!A;
                            }
                        }

            }
            openOption = true;
        }





                if(Index2 == 0){

                    if(Index == i){
                        if(Inventory[i].ItemId == 0){
                            if(Playerdata.HP != Playerdata.HPMAX){
                            t = false;
                            Inventory[i].capacity--;
                            testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                            testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
                            Playerdata.HP += 20;
                                A =!A;

                            }
                        }
                        if(Inventory[i].ItemId == 1){
                            t = false;
                            Inventory[i].capacity--;
                            testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                            testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
                            Playerdata.poisened = false;
                            A =!A;

                        }
                        if(Inventory[i].ItemId == 2){
                            t = false;
                            Inventory[i].capacity -= 10;
                            testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                            testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
                            Playerdata.amount += 10;
                            A =!A;

                        }
                        if(Inventory[i].ItemId == 3){
                            if(faceDoor){
                            t = false;
                            Inventory[i].capacity--;
                            testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                            testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
                            Playerdata.UseKey = false;
                                A =!A;
                            }
                        }
                        if(Inventory[i].ItemId == 4)
                        {
                            Color colorT = saveColor;
                            colorT.a = 0.1f;
                            USEtext.color = colorT;
                            A =!A;
                        }
                        if(Inventory[i].ItemId == 5)
                        {
                            Color colorT = saveColor;
                            colorT.a = 0.1f;
                            USEtext.color = colorT;
                            A =!A;
                        }

                    }
                    openOption = true;
                }
            }

    //======Item Caoacity = 0 Erase ===================================================================
            if(Inventory[i].capacity <= 0){
                testText = GameObject.Find(Inventory [i].Itemname).GetComponent<Text>();
                Destroy(testText.gameObject);
                Inventory.Remove(Inventory[i]);

                openOption = false;
                itemOption.SetActive(false);
                //icon.gameObject.SetActive(true);
                //iconMini.gameObject.SetActive(false);
                return;
            }
        }
//========================================================================================================================
    }


//=====CHECK FOR ITEM IF EXIST AND ADD ITEM TO INVENTORY ================================================================================================
    public void AddItem(int id) {
        Item itemADD = data.fetchItem(id);

        if(CheckForItemExist(itemADD)) {
            for (int i = 0; i < Inventory.Count; i++) {
                if(Inventory[i].ItemId == id) { 
                        t = false;
                        Inventory[i].capacity ++;
                        testText = GameObject.Find(itemADD.Itemname).GetComponent<Text>();
                        testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
                        Debug.Log (testText.text);

                    if(Inventory[i].Itemtype == Item.ItemType.ammo) {
                        Inventory[i].capacity += 10;
                        Inventory[i].capacity -= 1;
                        testText = GameObject.Find(itemADD.Itemname).GetComponent<Text>();
                        testText.text = Inventory [i].Itemname + ": " + Inventory [i].capacity;
                    }
                    break;
                }
            }
        }else{
            for (int i = 0; i < Inventory.Count; i++) {
                if(Inventory[i].ItemId == -1){
                    t = true;
                    Inventory[i] = itemADD;
                    DesplayInventory();             
                }
            }
        }

    }
//====================================================================================================
    bool CheckForItemExist(Item item) {
        for (int i = 0; i < Inventory.Count; i++)
            if(Inventory[i].ItemId == item.ItemId)
                return true;
        return false;
    }       
//====================================================================================================
    public void DesplayInventory() {
        for (int i = 0; i < Inventory.Count; i++) {
              var _text =Instantiate(Resources.Load("Text",typeof (Text)))as Text;
              testText =_text;
              _text.transform.position = panel.transform.position;
              _text.transform.SetParent(panel);
              _text.transform.localScale = new Vector3(1,1,1);
            break;
        }
    }
}

 //===========================================================================================================     

这是Item脚本

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
[System.Serializable]
public class Item {

    public int ItemId;
    public string Itemname;
    public ItemType Itemtype;
    public int ItemPower;
    public int capacity;



    public enum ItemType
    {
        weapon,
        spells,
        consumable,
        ammo,
    }

    public Item(int id,string name,int power,ItemType type,int cap)
    {
        capacity = cap;
        ItemId = id;
        Itemname = name;
        ItemPower = power;
        Itemtype = type ;
    }


    public Item()

    {
        this.ItemId = -1;
        }


}

这是项目数据库脚本

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class ItemDatabase : MonoBehaviour {


    public List<Item> items = new List<Item>();

    void Start()
    {
            items.Add (new Item (0, "Potion", 0, Item.ItemType.consumable,1));
            items.Add (new Item (1, "Antidot", 0, Item.ItemType.consumable, 1));
            items.Add (new Item (2, "Arrows", 0, Item.ItemType.ammo,10));
            items.Add (new Item (3, "KEY", 0, Item.ItemType.consumable,1));
            items.Add (new Item (4, "sword", 15, Item.ItemType.weapon,1));
            items.Add (new Item (5, "bow", 50, Item.ItemType.weapon,1));
        }


    public Item fetchItem(int id)
    {
        for (int i = 0 ; i < items.Count;i++)
            if(items[i].ItemId == id)
                return items[i];
            return null;
    }



}

1 个答案:

答案 0 :(得分:0)

看起来您缺少Serializeable属性。 将它添加到您的Item类中,就像这样 - &gt;

[Serializable]
  public class Item {
    ///Your code here
  }