Skip to content

Instantly share code, notes, and snippets.

@kamend
Created August 9, 2023 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamend/ddf30de73ae17017d3b85c0f984cc0a1 to your computer and use it in GitHub Desktop.
Save kamend/ddf30de73ae17017d3b85c0f984cc0a1 to your computer and use it in GitHub Desktop.
Holding unstructured data in a Dictionary
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DictExperiments
{
public static class DictExt
{
public class SceneObjectParser : IDisposable
{
public Dictionary<string, PropertyValue> Dict { get; set; }
public string Name()
{
return Dict["Name"].Str();
}
public float Age()
{
return Dict["Age"].Flt();
}
public void Dispose()
{
Dict = null;
}
}
private static SceneObjectParser _sceneObjectParser = new SceneObjectParser();
public static string Str(this Dictionary<string, PropertyValue> dict,string Key)
{
return dict[Key].Str();
}
public static SceneObjectParser ToSceneObject(this Dictionary<string, object> dict)
{
_sceneObjectParser.Dict = dict;
return _sceneObjectParser;
}
}
public interface IValue
{
}
public struct StringValue : IValue
{
public string Val;
public StringValue(string v)
{
Val = v;
}
}
public struct FloatValue : IValue
{
public float Val;
public FloatValue(float v)
{
Val = v;
}
}
public struct PropertyValue
{
public IValue Value;
public PropertyValue(IValue v)
{
Value = v;
}
public PropertyValue(string str)
{
Value = new StringValue(str);
}
public PropertyValue(float f)
{
Value = new FloatValue(f);
}
public string Str()
{
return ((StringValue)Value).Val;
}
public float Flt()
{
return ((FloatValue)Value).Val;
}
public static PropertyValue Str(string value)
{
return new PropertyValue(new StringValue(value));
}
public static PropertyValue Flt(float value)
{
return new PropertyValue(new FloatValue(value));
}
}
public class DictionaryHelper : MonoBehaviour
{
private Dictionary<string, PropertyValue> props = new Dictionary<string, PropertyValue>();
// Start is called before the first frame update
void Start()
{
props["Name"] = PropertyValue.Str("Kamen");
props["Age"] = PropertyValue.Flt(12.0f);
using var obj = props.ToSceneObject();
Debug.Log(obj.Name());
Debug.Log(obj.Age());
Debug.Log(props.Str("Name"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment