Search Unity

Unity wont let me Serialize and Save a Texture2d

Discussion in 'Scripting' started by todopinionweb, Feb 21, 2018.

  1. todopinionweb

    todopinionweb

    Joined:
    Feb 4, 2018
    Posts:
    1
    Good day, i created a inventory for my game that i want to save into a file. The inventory will have items and each item will have a texture2d (and other variables of course). The probolem is that i cant seem to make the texture serializable. Here the code for the Item class:

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

    [System.Serializable]
    public class Item {

    public string itemName;
    public int itemID;
    public string itemDesc;
    public Texture2D itemIcon;
    public int itemPower;
    public int itemEnergy;
    public int itemHp;
    public int itemRarity; //1 comun, 2 raro, 3 epico, 4 legendario
    public ItemType itemType;

    public enum ItemType {
    Weapon,
    Armor,
    Activable

    }

    public Item(string name, int id, string desc, int power, int energy, int hp, int rarity, ItemType type)
    {
    itemName = name;
    itemID = id;
    itemDesc = desc;
    itemIcon = Resources.Load<Texture2D>("Item Icons/" + name);
    itemPower = power;
    itemEnergy = energy;
    itemHp = hp;
    itemRarity = rarity;
    itemType = type;
    }
    public Item()
    {

    }
    }

    Here im trying to save my inventory with the item class:

    [Serializable]
    class PlayerData
    {
    public List<Item> inventory = new List<Item>();

    public PlayerData()
    {
    for(int i = 0; i < 12; i++)
    {
    inventory.Add(new Item());
    }
    }
    }

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

    PlayerData data = new PlayerData();
    for(int i = 0; i < inventory.Count; i++)
    {
    data.inventory = inventory;
    }
    bf.Serialize(file, data);
    file.Close();

    }