Skip to content

Instantly share code, notes, and snippets.

@monry
Created August 31, 2020 11:03
Show Gist options
  • Save monry/500565e26002d5cf7975dd67bdbb863d to your computer and use it in GitHub Desktop.
Save monry/500565e26002d5cf7975dd67bdbb863d to your computer and use it in GitHub Desktop.
JsonUtility.ToJson() に IEnumerable な要素を渡してみた
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Monry
{
public class SerializeIEnumerable : MonoBehaviour
{
private void Start()
{
Debug.Log(JsonUtility.ToJson(new Items())); // {"itemList":[{"index":1},{"index":2},{"index":3},{"index":4},{"index":5}]}
Debug.Log(JsonUtility.ToJson(new ItemList())); // {}
}
[Serializable]
private class Item
{
[SerializeField] private int index;
public Item(int index)
{
this.index = index;
}
}
[Serializable]
private class ItemList : List<Item>
{
public ItemList()
{
AddRange(
new List<Item>
{
new Item(1),
new Item(2),
new Item(3),
new Item(4),
new Item(5),
}
);
}
}
[Serializable]
private class Items : IEnumerable<Item>
{
[SerializeField] private List<Item> itemList = new List<Item>
{
new Item(1),
new Item(2),
new Item(3),
new Item(4),
new Item(5),
};
public IEnumerator<Item> GetEnumerator()
{
return itemList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment