-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataDecoder.cs
More file actions
84 lines (73 loc) · 2.63 KB
/
Copy pathDataDecoder.cs
File metadata and controls
84 lines (73 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
https://github.com/konbraphat51/UnityPythonConnectionModules
Author: Konbraphat51
License: Boost Software License (BSL1.0)
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Events;
namespace PythonConnection
{
public abstract class DataDecoder : MonoBehaviour
{
/// <summary>
/// Dictionary of data type name to actual C# class type reference
/// </summary>
private Dictionary<Type, UnityEvent<DataClass>> correspondingEvents;
/// <summary>
/// Convert from data_type name to actual C# class type reference
/// </summary>
/// template:
/// return new Dictionary<string, Type>(){
/// {"data_type_name", typeof(C#_class_type)}
/// }
protected abstract Dictionary<string, Type> DataToType();
//constructor
public DataDecoder()
{
//get pre-defined data type
Dictionary<string, Type> dataToType = DataToType();
//initialize `correspondingEvents`
PrepareEvents(dataToType.Values.ToArray());
}
public void DecodeAndReport(string dataTypeName, string dataJson)
{
//get data type
Type dataType = DataToType()[dataTypeName];
//convert json to data class
DataClass data = JsonUtility.FromJson(dataJson, dataType) as DataClass;
//report data
correspondingEvents[dataType].Invoke(data);
}
/// <summary>
/// Register new callback when data received
/// </summary>
/// <param name="dataType">type of the data class</param>
/// <param name="callback">callback when data received</param>
public void RegisterAction(Type dataType, UnityAction<DataClass> callback)
{
correspondingEvents[dataType].AddListener(callback);
}
/// <summary>
/// Unregister callback when data received
/// </summary>
/// <param name="dataType">type of the data class</param>
/// <param name="callback">callback when data received</param>
public void RemoveAction(Type dataType, UnityAction<DataClass> callback)
{
correspondingEvents[dataType].RemoveListener(callback);
}
private void PrepareEvents(Type[] types)
{
//prepare events
correspondingEvents = new Dictionary<Type, UnityEvent<DataClass>>();
foreach (Type type in types)
{
correspondingEvents.Add(type, new UnityEvent<DataClass>());
}
}
}
}