Skip to content

Instantly share code, notes, and snippets.

@kamend
Created August 9, 2023 07:57
Show Gist options
  • Select an option

  • Save kamend/ddf30de73ae17017d3b85c0f984cc0a1 to your computer and use it in GitHub Desktop.

Select an option

Save kamend/ddf30de73ae17017d3b85c0f984cc0a1 to your computer and use it in GitHub Desktop.

Revisions

  1. kamend created this gist Aug 9, 2023.
    128 changes: 128 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,128 @@
    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"));

    }
    }
    }