using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class Shelves : MonoBehaviour, IDataPersistence { public GameObject ShelfPrefab; private List items = new List(); void Awake() { Clear(); } public void LoadData(GameData data) { Clear(); foreach (ShelfData shelfData in data.shelves) { Add(shelfData); } } public void SaveData(GameData data) { data.shelves.Clear(); foreach (Shelf shelf in GetComponentsInChildren()) { ShelfData shelfData = new ShelfData(); shelf.SaveData(shelfData); data.shelves.Add(shelfData); } } public void Add(ShelfData data) { GameObject instance = Instantiate(ShelfPrefab, new Vector3(data.location.x, data.location.y, 0), Quaternion.Euler(0, 0, data.angle), transform); Shelf shelf = instance.GetComponent(); shelf.LoadData(data); items.Add(shelf); } private void Clear() { items.Clear(); while (transform.childCount > 0) DestroyImmediate(transform.GetChild(0).gameObject); } [ContextMenu("Test Initialize")] void TestInitialize() { Clear(); for (int i = 0; i < UnityEngine.Random.Range(3, 5); i++) { ShelfData shelf = new ShelfData() { type = "random shelf", location = new Vector2(UnityEngine.Random.value * 20 - 10, UnityEngine.Random.value * 10 - 5), angle = 0, }; shelf.inventory.capacity = UnityEngine.Random.Range(10, 40); shelf.inventory.items.Add("123", UnityEngine.Random.Range(5, 10)); Add(shelf); } } }