提交 8a950da8 编写于 作者: T tanghai

配置字段可以热更

上级 2f8c15a7
......@@ -18,5 +18,10 @@ namespace Model
throw new Exception($"load config file fail, path: {path} {e}");
}
}
public static T ToObject<T>(string str)
{
return MongoHelper.FromJson<T>(str);
}
}
}
......@@ -288,6 +288,19 @@ public class ExcelExporterEditor : EditorWindow
}
string fieldName = cellInfos[j].Name;
if (fieldName == "Id" || fieldName == "_id")
{
if (this.isClient)
{
fieldName = "Id";
}
else
{
fieldName = "_id";
}
}
string fieldType = cellInfos[j].Type;
sb.Append($"\"{fieldName}\":{Convert(fieldType, fieldValue)}");
}
......
......@@ -21,7 +21,7 @@ namespace MyEditor
{
if (File.Exists(path))
{
this.globalProto = MongoHelper.FromJson<GlobalProto>(File.ReadAllText(path));
this.globalProto = JsonHelper.FromJson<GlobalProto>(File.ReadAllText(path));
}
else
{
......@@ -36,7 +36,7 @@ namespace MyEditor
if (GUILayout.Button("保存"))
{
File.WriteAllText(path, MongoHelper.ToJson(this.globalProto));
File.WriteAllText(path, JsonHelper.ToJson(this.globalProto));
AssetDatabase.Refresh();
}
}
......
B{ "Id" : 1, "Name": "加速buff", "Duration": 1000 }
......
{ "_t" : "GlobalProto", "AssetBundleServerUrl" : "http://127.0.0.1:8080/", "Address" : "127.0.0.1:10002" }
\ No newline at end of file
{ "AssetBundleServerUrl" : "http://127.0.0.1:8080/", "Address" : "127.0.0.1:10002" }
\ No newline at end of file
{"_id":1001,"Name":"米克尔","Desc":"带有强力攻击技能","Position":1,"Height":178,"Weight":68}
{"Id":1001,"Name":"米克尔","Desc":"带有强力攻击技能","Position":1,"Height":178,"Weight":68}
using System;
using LitJson;
namespace Model
{
public static class JsonHelper
{
public static string ToJson(object obj)
{
return JsonMapper.ToJson(obj);
}
public static T FromJson<T>(string str)
{
return JsonMapper.ToObject<T>(str);
}
public static object FromJson(Type type, string str)
{
return JsonMapper.ToObject(type, str);
}
public static T Clone<T>(T t)
{
return FromJson<T>(ToJson(t));
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 4a70fc9ae05ae2443be10cb73468fb7a
timeCreated: 1519957708
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
......@@ -18,7 +18,7 @@
{
Instance = this;
string configStr = ConfigHelper.GetGlobal();
this.GlobalProto = MongoHelper.FromJson<GlobalProto>(configStr);
this.GlobalProto = JsonHelper.FromJson<GlobalProto>(configStr);
}
}
}
\ No newline at end of file
......@@ -45,6 +45,7 @@ namespace Model
// 初始化ILRuntime的protobuf
InitializeILRuntimeProtobuf(appDomain);
LitJson.JsonMapper.RegisterILRuntimeCLRRedirection(appDomain);
}
public static void InitializeILRuntimeProtobuf(ILRuntime.Runtime.Enviorment.AppDomain appDomain)
......
......@@ -27,7 +27,7 @@ namespace Model
{
continue;
}
T t = MongoHelper.FromJson<T>(str2);
T t = ConfigHelper.ToObject<T>(str2);
this.dict.Add(t.Id, t);
}
catch (Exception e)
......
......@@ -32,5 +32,10 @@ namespace Model
throw new Exception($"load global config file fail", e);
}
}
public static T ToObject<T>(string str)
{
return JsonHelper.FromJson<T>(str);
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 524262bcd09288f4faf021fba9216d67
folderAsset: yes
timeCreated: 1519956672
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
#region Header
/**
* IJsonWrapper.cs
* Interface that represents a type capable of handling all kinds of JSON
* data. This is mainly used when mapping objects through JsonMapper, and
* it's implemented by JsonData.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System.Collections;
using System.Collections.Specialized;
namespace LitJson
{
public enum JsonType
{
None,
Object,
Array,
String,
Int,
Long,
Double,
Boolean
}
public interface IJsonWrapper : IList, IOrderedDictionary
{
bool IsArray { get; }
bool IsBoolean { get; }
bool IsDouble { get; }
bool IsInt { get; }
bool IsLong { get; }
bool IsObject { get; }
bool IsString { get; }
bool GetBoolean ();
double GetDouble ();
int GetInt ();
JsonType GetJsonType ();
long GetLong ();
string GetString ();
void SetBoolean (bool val);
void SetDouble (double val);
void SetInt (int val);
void SetJsonType (JsonType type);
void SetLong (long val);
void SetString (string val);
string ToJson ();
void ToJson (JsonWriter writer);
}
}
fileFormatVersion: 2
guid: cce53f18703f06240a0af65238538aa7
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
此差异已折叠。
fileFormatVersion: 2
guid: 42508827a6be4604eb3fe18e91c4bfe8
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
#region Header
/**
* JsonException.cs
* Base class throwed by LitJSON when a parsing error occurs.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
namespace LitJson
{
public class JsonException : ApplicationException
{
public JsonException () : base ()
{
}
internal JsonException (ParserToken token) :
base (String.Format (
"Invalid token '{0}' in input string", token))
{
}
internal JsonException (ParserToken token,
Exception inner_exception) :
base (String.Format (
"Invalid token '{0}' in input string", token),
inner_exception)
{
}
internal JsonException (int c) :
base (String.Format (
"Invalid character '{0}' in input string", (char) c))
{
}
internal JsonException (int c, Exception inner_exception) :
base (String.Format (
"Invalid character '{0}' in input string", (char) c),
inner_exception)
{
}
public JsonException (string message) : base (message)
{
}
public JsonException (string message, Exception inner_exception) :
base (message, inner_exception)
{
}
}
}
fileFormatVersion: 2
guid: 6baa39e766b77564eb4f44430891884b
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
此差异已折叠。
fileFormatVersion: 2
guid: eedf6bf0ee34a7046a333bed691d4101
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
#region Header
/**
* JsonMockWrapper.cs
* Mock object implementing IJsonWrapper, to facilitate actions like
* skipping data more efficiently.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
namespace LitJson
{
public class JsonMockWrapper : IJsonWrapper
{
public bool IsArray { get { return false; } }
public bool IsBoolean { get { return false; } }
public bool IsDouble { get { return false; } }
public bool IsInt { get { return false; } }
public bool IsLong { get { return false; } }
public bool IsObject { get { return false; } }
public bool IsString { get { return false; } }
public bool GetBoolean () { return false; }
public double GetDouble () { return 0.0; }
public int GetInt () { return 0; }
public JsonType GetJsonType () { return JsonType.None; }
public long GetLong () { return 0L; }
public string GetString () { return ""; }
public void SetBoolean (bool val) {}
public void SetDouble (double val) {}
public void SetInt (int val) {}
public void SetJsonType (JsonType type) {}
public void SetLong (long val) {}
public void SetString (string val) {}
public string ToJson () { return ""; }
public void ToJson (JsonWriter writer) {}
bool IList.IsFixedSize { get { return true; } }
bool IList.IsReadOnly { get { return true; } }
object IList.this[int index] {
get { return null; }
set {}
}
int IList.Add (object value) { return 0; }
void IList.Clear () {}
bool IList.Contains (object value) { return false; }
int IList.IndexOf (object value) { return -1; }
void IList.Insert (int i, object v) {}
void IList.Remove (object value) {}
void IList.RemoveAt (int index) {}
int ICollection.Count { get { return 0; } }
bool ICollection.IsSynchronized { get { return false; } }
object ICollection.SyncRoot { get { return null; } }
void ICollection.CopyTo (Array array, int index) {}
IEnumerator IEnumerable.GetEnumerator () { return null; }
bool IDictionary.IsFixedSize { get { return true; } }
bool IDictionary.IsReadOnly { get { return true; } }
ICollection IDictionary.Keys { get { return null; } }
ICollection IDictionary.Values { get { return null; } }
object IDictionary.this[object key] {
get { return null; }
set {}
}
void IDictionary.Add (object k, object v) {}
void IDictionary.Clear () {}
bool IDictionary.Contains (object key) { return false; }
void IDictionary.Remove (object key) {}
IDictionaryEnumerator IDictionary.GetEnumerator () { return null; }
object IOrderedDictionary.this[int idx] {
get { return null; }
set {}
}
IDictionaryEnumerator IOrderedDictionary.GetEnumerator () {
return null;
}
void IOrderedDictionary.Insert (int i, object k, object v) {}
void IOrderedDictionary.RemoveAt (int i) {}
}
}
fileFormatVersion: 2
guid: aa52124c202f8e94ab4e6669171b7bd3
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
#region Header
/**
* JsonReader.cs
* Stream-like access to JSON text.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace LitJson
{
public enum JsonToken
{
None,
ObjectStart,
PropertyName,
ObjectEnd,
ArrayStart,
ArrayEnd,
Int,
Long,
Double,
String,
Boolean,
Null
}
public class JsonReader
{
#region Fields
private static IDictionary<int, IDictionary<int, int[]>> parse_table;
private Stack<int> automaton_stack;
private int current_input;
private int current_symbol;
private bool end_of_json;
private bool end_of_input;
private Lexer lexer;
private bool parser_in_string;
private bool parser_return;
private bool read_started;
private TextReader reader;
private bool reader_is_owned;
private bool skip_non_members;
private object token_value;
private JsonToken token;
#endregion
#region Public Properties
public bool AllowComments {
get { return lexer.AllowComments; }
set { lexer.AllowComments = value; }
}
public bool AllowSingleQuotedStrings {
get { return lexer.AllowSingleQuotedStrings; }
set { lexer.AllowSingleQuotedStrings = value; }
}
public bool SkipNonMembers {
get { return skip_non_members; }
set { skip_non_members = value; }
}
public bool EndOfInput {
get { return end_of_input; }
}
public bool EndOfJson {
get { return end_of_json; }
}
public JsonToken Token {
get { return token; }
}
public object Value {
get { return token_value; }
}
#endregion
#region Constructors
static JsonReader ()
{
PopulateParseTable ();
}
public JsonReader (string json_text) :
this (new StringReader (json_text), true)
{
}
public JsonReader (TextReader reader) :
this (reader, false)
{
}
private JsonReader (TextReader reader, bool owned)
{
if (reader == null)
throw new ArgumentNullException ("reader");
parser_in_string = false;
parser_return = false;
read_started = false;
automaton_stack = new Stack<int> ();
automaton_stack.Push ((int) ParserToken.End);
automaton_stack.Push ((int) ParserToken.Text);
lexer = new Lexer (reader);
end_of_input = false;
end_of_json = false;
skip_non_members = true;
this.reader = reader;
reader_is_owned = owned;
}
#endregion
#region Static Methods
private static void PopulateParseTable ()
{
// See section A.2. of the manual for details
parse_table = new Dictionary<int, IDictionary<int, int[]>> ();
TableAddRow (ParserToken.Array);
TableAddCol (ParserToken.Array, '[',
'[',
(int) ParserToken.ArrayPrime);
TableAddRow (ParserToken.ArrayPrime);
TableAddCol (ParserToken.ArrayPrime, '"',
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddCol (ParserToken.ArrayPrime, '[',
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddCol (ParserToken.ArrayPrime, ']',
']');
TableAddCol (ParserToken.ArrayPrime, '{',
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Number,
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.True,
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.False,
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Null,
(int) ParserToken.Value,
(int) ParserToken.ValueRest,
']');
TableAddRow (ParserToken.Object);
TableAddCol (ParserToken.Object, '{',
'{',
(int) ParserToken.ObjectPrime);
TableAddRow (ParserToken.ObjectPrime);
TableAddCol (ParserToken.ObjectPrime, '"',
(int) ParserToken.Pair,
(int) ParserToken.PairRest,
'}');
TableAddCol (ParserToken.ObjectPrime, '}',
'}');
TableAddRow (ParserToken.Pair);
TableAddCol (ParserToken.Pair, '"',
(int) ParserToken.String,
':',
(int) ParserToken.Value);
TableAddRow (ParserToken.PairRest);
TableAddCol (ParserToken.PairRest, ',',
',',
(int) ParserToken.Pair,
(int) ParserToken.PairRest);
TableAddCol (ParserToken.PairRest, '}',
(int) ParserToken.Epsilon);
TableAddRow (ParserToken.String);
TableAddCol (ParserToken.String, '"',
'"',
(int) ParserToken.CharSeq,
'"');
TableAddRow (ParserToken.Text);
TableAddCol (ParserToken.Text, '[',
(int) ParserToken.Array);
TableAddCol (ParserToken.Text, '{',
(int) ParserToken.Object);
TableAddRow (ParserToken.Value);
TableAddCol (ParserToken.Value, '"',
(int) ParserToken.String);
TableAddCol (ParserToken.Value, '[',
(int) ParserToken.Array);
TableAddCol (ParserToken.Value, '{',
(int) ParserToken.Object);
TableAddCol (ParserToken.Value, (int) ParserToken.Number,
(int) ParserToken.Number);
TableAddCol (ParserToken.Value, (int) ParserToken.True,
(int) ParserToken.True);
TableAddCol (ParserToken.Value, (int) ParserToken.False,
(int) ParserToken.False);
TableAddCol (ParserToken.Value, (int) ParserToken.Null,
(int) ParserToken.Null);
TableAddRow (ParserToken.ValueRest);
TableAddCol (ParserToken.ValueRest, ',',
',',
(int) ParserToken.Value,
(int) ParserToken.ValueRest);
TableAddCol (ParserToken.ValueRest, ']',
(int) ParserToken.Epsilon);
}
private static void TableAddCol (ParserToken row, int col,
params int[] symbols)
{
parse_table[(int) row].Add (col, symbols);
}
private static void TableAddRow (ParserToken rule)
{
parse_table.Add ((int) rule, new Dictionary<int, int[]> ());
}
#endregion
#region Private Methods
private void ProcessNumber (string number)
{
if (number.IndexOf ('.') != -1 ||
number.IndexOf ('e') != -1 ||
number.IndexOf ('E') != -1) {
double n_double;
if (Double.TryParse (number, out n_double)) {
token = JsonToken.Double;
token_value = n_double;
return;
}
}
int n_int32;
if (Int32.TryParse (number, out n_int32)) {
token = JsonToken.Int;
token_value = n_int32;
return;
}
long n_int64;
if (Int64.TryParse (number, out n_int64)) {
token = JsonToken.Long;
token_value = n_int64;
return;
}
ulong n_uint64;
if (UInt64.TryParse(number, out n_uint64))
{
token = JsonToken.Long;
token_value = n_uint64;
return;
}
// Shouldn't happen, but just in case, return something
token = JsonToken.Int;
token_value = 0;
}
private void ProcessSymbol ()
{
if (current_symbol == '[') {
token = JsonToken.ArrayStart;
parser_return = true;
} else if (current_symbol == ']') {
token = JsonToken.ArrayEnd;
parser_return = true;
} else if (current_symbol == '{') {
token = JsonToken.ObjectStart;
parser_return = true;
} else if (current_symbol == '}') {
token = JsonToken.ObjectEnd;
parser_return = true;
} else if (current_symbol == '"') {
if (parser_in_string) {
parser_in_string = false;
parser_return = true;
} else {
if (token == JsonToken.None)
token = JsonToken.String;
parser_in_string = true;
}
} else if (current_symbol == (int) ParserToken.CharSeq) {
token_value = lexer.StringValue;
} else if (current_symbol == (int) ParserToken.False) {
token = JsonToken.Boolean;
token_value = false;
parser_return = true;
} else if (current_symbol == (int) ParserToken.Null) {
token = JsonToken.Null;
parser_return = true;
} else if (current_symbol == (int) ParserToken.Number) {
ProcessNumber (lexer.StringValue);
parser_return = true;
} else if (current_symbol == (int) ParserToken.Pair) {
token = JsonToken.PropertyName;
} else if (current_symbol == (int) ParserToken.True) {
token = JsonToken.Boolean;
token_value = true;
parser_return = true;
}
}
private bool ReadToken ()
{
if (end_of_input)
return false;
lexer.NextToken ();
if (lexer.EndOfInput) {
Close ();
return false;
}
current_input = lexer.Token;
return true;
}
#endregion
public void Close ()
{
if (end_of_input)
return;
end_of_input = true;
end_of_json = true;
if (reader_is_owned)
reader.Close ();
reader = null;
}
public bool Read ()
{
if (end_of_input)
return false;
if (end_of_json) {
end_of_json = false;
automaton_stack.Clear ();
automaton_stack.Push ((int) ParserToken.End);
automaton_stack.Push ((int) ParserToken.Text);
}
parser_in_string = false;
parser_return = false;
token = JsonToken.None;
token_value = null;
if (! read_started) {
read_started = true;
if (! ReadToken ())
return false;
}
int[] entry_symbols;
while (true) {
if (parser_return) {
if (automaton_stack.Peek () == (int) ParserToken.End)
end_of_json = true;
return true;
}
current_symbol = automaton_stack.Pop ();
ProcessSymbol ();
if (current_symbol == current_input) {
if (! ReadToken ()) {
if (automaton_stack.Peek () != (int) ParserToken.End)
throw new JsonException (
"Input doesn't evaluate to proper JSON text");
if (parser_return)
return true;
return false;
}
continue;
}
try {
entry_symbols =
parse_table[current_symbol][current_input];
} catch (KeyNotFoundException e) {
throw new JsonException ((ParserToken) current_input, e);
}
if (entry_symbols[0] == (int) ParserToken.Epsilon)
continue;
for (int i = entry_symbols.Length - 1; i >= 0; i--)
automaton_stack.Push (entry_symbols[i]);
}
}
}
}
fileFormatVersion: 2
guid: 34c5ff0ba40437b41a9fdad9cb33f841
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
#region Header
/**
* JsonWriter.cs
* Stream-like facility to output JSON text.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace LitJson
{
internal enum Condition
{
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext
{
public int Count;
public bool InArray;
public bool InObject;
public bool ExpectingValue;
public int Padding;
}
public class JsonWriter
{
#region Fields
private static NumberFormatInfo number_format;
private WriterContext context;
private Stack<WriterContext> ctx_stack;
private bool has_reached_end;
private char[] hex_seq;
private int indentation;
private int indent_value;
private StringBuilder inst_string_builder;
private bool pretty_print;
private bool validate;
private TextWriter writer;
#endregion
#region Properties
public int IndentValue {
get { return indent_value; }
set {
indentation = (indentation / indent_value) * value;
indent_value = value;
}
}
public bool PrettyPrint {
get { return pretty_print; }
set { pretty_print = value; }
}
public TextWriter TextWriter {
get { return writer; }
}
public bool Validate {
get { return validate; }
set { validate = value; }
}
#endregion
#region Constructors
static JsonWriter ()
{
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter ()
{
inst_string_builder = new StringBuilder ();
writer = new StringWriter (inst_string_builder);
Init ();
}
public JsonWriter (StringBuilder sb) :
this (new StringWriter (sb))
{
}
public JsonWriter (TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
this.writer = writer;
Init ();
}
#endregion
#region Private Methods
private void DoValidation (Condition cond)
{
if (! context.ExpectingValue)
context.Count++;
if (! validate)
return;
if (has_reached_end)
throw new JsonException (
"A complete JSON symbol has already been written");
switch (cond) {
case Condition.InArray:
if (! context.InArray)
throw new JsonException (
"Can't close an array here");
break;
case Condition.InObject:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't close an object here");
break;
case Condition.NotAProperty:
if (context.InObject && ! context.ExpectingValue)
throw new JsonException (
"Expected a property");
break;
case Condition.Property:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't add a property here");
break;
case Condition.Value:
if (! context.InArray &&
(! context.InObject || ! context.ExpectingValue))
throw new JsonException (
"Can't add a value here");
break;
}
}
private void Init ()
{
has_reached_end = false;
hex_seq = new char[4];
indentation = 0;
indent_value = 4;
pretty_print = false;
validate = true;
ctx_stack = new Stack<WriterContext> ();
context = new WriterContext ();
ctx_stack.Push (context);
}
private static void IntToHex (int n, char[] hex)
{
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10)
hex[3 - i] = (char) ('0' + num);
else
hex[3 - i] = (char) ('A' + (num - 10));
n >>= 4;
}
}
private void Indent ()
{
if (pretty_print)
indentation += indent_value;
}
private void Put (string str)
{
if (pretty_print && ! context.ExpectingValue)
for (int i = 0; i < indentation; i++)
writer.Write (' ');
writer.Write (str);
}
private void PutNewline ()
{
PutNewline (true);
}
private void PutNewline (bool add_comma)
{
if (add_comma && ! context.ExpectingValue &&
context.Count > 1)
writer.Write (',');
if (pretty_print && ! context.ExpectingValue)
writer.Write ('\n');
}
private void PutString (string str)
{
Put (String.Empty);
writer.Write ('"');
//直接存储原始字符串,不再做任何转义字符的解析
writer.Write(str);
writer.Write('"');
return;
int n = str.Length;
for (int i = 0; i < n; i++) {
switch (str[i]) {
case '\n':
writer.Write ("\\n");
continue;
case '\r':
writer.Write ("\\r");
continue;
case '\t':
writer.Write ("\\t");
continue;
case '"':
case '\\':
writer.Write ('\\');
writer.Write (str[i]);
continue;
case '\f':
writer.Write ("\\f");
continue;
case '\b':
writer.Write ("\\b");
continue;
}
if ((int) str[i] >= 32 && (int) str[i] <= 126) {
writer.Write (str[i]);
continue;
}
// Default, turn into a \uXXXX sequence
IntToHex ((int) str[i], hex_seq);
writer.Write ("\\u");
writer.Write (hex_seq);
}
writer.Write ('"');
}
private void Unindent ()
{
if (pretty_print)
indentation -= indent_value;
}
#endregion
public override string ToString ()
{
if (inst_string_builder == null)
return String.Empty;
return inst_string_builder.ToString ();
}
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
public void Write (bool boolean)
{
DoValidation (Condition.Value);
PutNewline ();
Put (boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write (decimal number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (double number)
{
DoValidation (Condition.Value);
PutNewline ();
string str = Convert.ToString (number, number_format);
Put (str);
if (str.IndexOf ('.') == -1 &&
str.IndexOf ('E') == -1)
writer.Write (".0");
context.ExpectingValue = false;
}
public void Write (int number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (long number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (string str)
{
DoValidation (Condition.Value);
PutNewline ();
if (str == null)
Put ("null");
else
PutString (str);
context.ExpectingValue = false;
}
[CLSCompliant(false)]
public void Write (ulong number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void WriteArrayEnd ()
{
DoValidation (Condition.InArray);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("]");
}
public void WriteArrayStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("[");
context = new WriterContext ();
context.InArray = true;
ctx_stack.Push (context);
Indent ();
}
public void WriteObjectEnd ()
{
DoValidation (Condition.InObject);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("}");
}
public void WriteObjectStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("{");
context = new WriterContext ();
context.InObject = true;
ctx_stack.Push (context);
Indent ();
}
public void WritePropertyName (string property_name)
{
DoValidation (Condition.Property);
PutNewline ();
PutString (property_name);
if (pretty_print) {
if (property_name.Length > context.Padding)
context.Padding = property_name.Length;
for (int i = context.Padding - property_name.Length;
i >= 0; i--)
writer.Write (' ');
writer.Write (": ");
} else
writer.Write (':');
context.ExpectingValue = true;
}
}
}
fileFormatVersion: 2
guid: d7e55786108cec142901e6e98a7387b2
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
此差异已折叠。
fileFormatVersion: 2
guid: 921ed30584efeda40ac7e4c6813770b7
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BEC78343-4BA2-4757-807F-7CDBF1F70C83}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LitJson</RootNamespace>
<AssemblyName>LitJson</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IJsonWrapper.cs" />
<Compile Include="JsonData.cs" />
<Compile Include="JsonException.cs" />
<Compile Include="JsonMapper.cs" />
<Compile Include="JsonMockWrapper.cs" />
<Compile Include="JsonReader.cs" />
<Compile Include="JsonWriter.cs" />
<Compile Include="Lexer.cs" />
<Compile Include="ParserToken.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ILRuntime\ILRuntime.csproj">
<Project>{79ef2f29-89d1-4097-986c-5e4eefe0fa33}</Project>
<Name>ILRuntime</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
fileFormatVersion: 2
guid: 30f38d8afcc673b4fade8338ebfe94a9
timeCreated: 1519956672
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
#region Header
/**
* ParserToken.cs
* Internal representation of the tokens used by the lexer and the parser.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
namespace LitJson
{
internal enum ParserToken
{
// Lexer tokens (see section A.1.1. of the manual)
None = System.Char.MaxValue + 1,
Number,
True,
False,
Null,
CharSeq,
// Single char
Char,
// Parser Rules (see section A.2.1 of the manual)
Text,
Object,
ObjectPrime,
Pair,
PairRest,
Array,
ArrayPrime,
Value,
ValueRest,
String,
// End of input
End,
// The empty rule
Epsilon
}
}
fileFormatVersion: 2
guid: d4c90418461b2a446a2b8519ebd1638c
timeCreated: 1519956672
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System;
using LitJson;
namespace Hotfix
{
public static class JsonHelper
{
public static string ToJson(object obj)
{
return JsonMapper.ToJson(obj);
}
public static T FromJson<T>(string str)
{
return JsonMapper.ToObject<T>(str);
}
public static object FromJson(Type type, string str)
{
return JsonMapper.ToObject(type, str);
}
public static T Clone<T>(T t)
{
return FromJson<T>(ToJson(t));
}
}
}
\ No newline at end of file
using Model;
namespace Hotfix
{
public class BuffConfig: AConfig
{
public string Name { get; set; }
public int Duration { get; set; }
public BuffConfig()
{
}
public BuffConfig(long id): base(id)
{
}
}
[Config(AppType.Client)]
public class BuffCategory: ACategory<BuffConfig>
{
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 8433bdafcbe56e140b3fe0c93722e0cf
timeCreated: 1498118076
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using Model;
namespace Hotfix
{
[Config(AppType.Client)]
public partial class UnitConfigCategory : ACategory<UnitConfig>
{}
public class UnitConfig: AConfig
{
public string Name;
public string Desc;
public int Position;
public int Height;
public int Weight;
}
}
fileFormatVersion: 2
guid: bab6c7de3c7c1d940bf6eb1d0e8506f2
timeCreated: 1505441063
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
......@@ -27,6 +27,11 @@ namespace Hotfix
Game.Scene.AddComponent<OpcodeTypeComponent>();
Game.Scene.AddComponent<MessageDispatherComponent>();
// 加载热更配置
Model.Game.Scene.GetComponent<ResourcesComponent>().LoadBundle("config.unity3d");
Game.Scene.AddComponent<ConfigComponent>();
Model.Game.Scene.GetComponent<ResourcesComponent>().UnloadBundle("config.unity3d");
Game.EventSystem.Run(EventIdType.InitSceneStart);
}
catch (Exception e)
......
using System;
using System.Collections.Generic;
using System.Linq;
using Model;
namespace Hotfix
{
/// <summary>
/// 管理该所有的配置
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class ACategory<T>: ICategory where T : AConfig
{
protected Dictionary<long, T> dict;
public virtual void BeginInit()
{
this.dict = new Dictionary<long, T>();
string configStr = ConfigHelper.GetText(typeof (T).Name);
foreach (string str in configStr.Split(new[] { "\n" }, StringSplitOptions.None))
{
try
{
string str2 = str.Trim();
if (str2 == "")
{
continue;
}
T t = ConfigHelper.ToObject<T>(str2);
this.dict.Add(t.Id, t);
}
catch (Exception e)
{
throw new Exception($"parser json fail: {str}", e);
}
}
}
public Type ConfigType
{
get
{
return typeof (T);
}
}
public virtual void EndInit()
{
}
public T this[long type]
{
get
{
T t;
if (!this.dict.TryGetValue(type, out t))
{
throw new KeyNotFoundException($"{typeof (T)} 没有找到配置, key: {type}");
}
return t;
}
}
public T TryGet(int type)
{
T t;
if (!this.dict.TryGetValue(type, out t))
{
return null;
}
return t;
}
public T[] GetAll()
{
return this.dict.Values.ToArray();
}
public T GetOne()
{
return this.dict.Values.First();
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 2f769b2838d3a384e88c8b0627564a46
timeCreated: 1474947006
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
namespace Hotfix
{
/// <summary>
/// 每个Config的基类
/// </summary>
public abstract class AConfig: Entity
{
protected AConfig()
{
}
protected AConfig(long id): base(id)
{
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: af363bf85da8f694796a3438be6df56b
timeCreated: 1474947006
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 3a286d83056068f4ba8dfcf7a37b926d
timeCreated: 1498879455
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: f3b8997482f68c0418b3982ed475def2
timeCreated: 1475898829
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System;
using System.Collections.Generic;
using Model;
namespace Hotfix
{
[ObjectSystem]
public class ConfigComponentAwakeSystem : AwakeSystem<ConfigComponent>
{
public override void Awake(ConfigComponent self)
{
self.Awake();
}
}
[ObjectSystem]
public class ConfigComponentLoadSystem : LoadSystem<ConfigComponent>
{
public override void Load(ConfigComponent self)
{
self.Load();
}
}
/// <summary>
/// Config组件会扫描所有的有ConfigAttribute标签的配置,加载进来
/// </summary>
public class ConfigComponent: Component
{
private Dictionary<Type, ICategory> allConfig;
public void Awake()
{
this.Load();
}
public void Load()
{
this.allConfig = new Dictionary<Type, ICategory>();
Type[] types = Model.Game.Hotfix.GetHotfixTypes();
foreach (Type type in types)
{
object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
if (attrs.Length == 0)
{
continue;
}
object obj = Activator.CreateInstance(type);
ICategory iCategory = obj as ICategory;
if (iCategory == null)
{
throw new Exception($"class: {type.Name} not inherit from ACategory");
}
iCategory.BeginInit();
iCategory.EndInit();
this.allConfig[iCategory.ConfigType] = iCategory;
}
}
public T GetOne<T>() where T : AConfig
{
Type type = typeof (T);
ICategory configCategory;
if (!this.allConfig.TryGetValue(type, out configCategory))
{
throw new Exception($"ConfigComponent not found key: {type.FullName}");
}
return ((ACategory<T>) configCategory).GetOne();
}
public T Get<T>(long id) where T : AConfig
{
Type type = typeof (T);
ICategory configCategory;
if (!this.allConfig.TryGetValue(type, out configCategory))
{
throw new Exception($"ConfigComponent not found key: {type.FullName}");
}
return ((ACategory<T>) configCategory)[id];
}
public T TryGet<T>(int id) where T : AConfig
{
Type type = typeof (T);
ICategory configCategory;
if (!this.allConfig.TryGetValue(type, out configCategory))
{
return default(T);
}
return ((ACategory<T>) configCategory).TryGet(id);
}
public T[] GetAll<T>() where T : AConfig
{
Type type = typeof (T);
ICategory configCategory;
if (!this.allConfig.TryGetValue(type, out configCategory))
{
throw new Exception($"ConfigComponent not found key: {type.FullName}");
}
return ((ACategory<T>) configCategory).GetAll();
}
public T GetCategory<T>() where T : class, ICategory, new()
{
T t = new T();
Type type = t.ConfigType;
ICategory configCategory;
bool ret = this.allConfig.TryGetValue(type, out configCategory);
return ret? (T)configCategory : null;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: c38338e46c7049bdbfaf34a0ab31cb52
timeCreated: 1505111255
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System;
using Model;
using UnityEngine;
namespace Hotfix
{
public static class ConfigHelper
{
public static string GetText(string key)
{
try
{
GameObject config = Model.Game.Scene.GetComponent<ResourcesComponent>().GetAsset<GameObject>("config.unity3d", "Config");
string configStr = config.Get<TextAsset>(key).text;
return configStr;
}
catch (Exception e)
{
throw new Exception($"load config file fail, key: {key}", e);
}
}
public static string GetGlobal()
{
try
{
GameObject config = (GameObject)Resources.Load("KV");
string configStr = config.Get<TextAsset>("GlobalProto").text;
return configStr;
}
catch (Exception e)
{
throw new Exception($"load global config file fail", e);
}
}
public static T ToObject<T>(string str)
{
return JsonHelper.FromJson<T>(str);
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 0e19c00909caacf4bb8cdd8e39e2e365
timeCreated: 1477905905
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System;
namespace Hotfix
{
public interface ISupportInitialize2
{
void BeginInit();
void EndInit();
}
public interface ICategory: ISupportInitialize2
{
Type ConfigType { get; }
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: e1c7d45390174bd4f923a1584cf84029
timeCreated: 1474944962
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
......@@ -54,13 +54,21 @@
<Compile Include="Base\Helper\ArrayHelper.cs" />
<Compile Include="Base\Helper\AssetBundleHelper.cs" />
<Compile Include="Base\Helper\ExceptionHelper.cs" />
<Compile Include="Base\Helper\JsonHelper.cs" />
<Compile Include="Base\Object\IStart.cs" />
<Compile Include="Component\OperaComponent.cs" />
<Compile Include="Entity\Config\BuffConfig.cs" />
<Compile Include="Entity\Config\UnitConfig.cs" />
<Compile Include="Event\TestHotfixSubscribMonoEvent_LogString.cs" />
<Compile Include="Handler\Actor_CreateUnitsHandler.cs" />
<Compile Include="Handler\Actor_TestHandler.cs" />
<Compile Include="Handler\Frame_ClickMapHandler.cs" />
<Compile Include="Handler\G2C_TestHotfixHandler.cs" />
<Compile Include="Module\Config\ACategory.cs" />
<Compile Include="Module\Config\AConfig.cs" />
<Compile Include="Module\Config\ConfigComponent.cs" />
<Compile Include="Module\Config\ConfigHelper.cs" />
<Compile Include="Module\Config\ICategory.cs" />
<Compile Include="Module\Message\IActorMessage.cs" />
<Compile Include="Module\Message\HotfixMessageDispatcher.cs" />
<Compile Include="Module\Message\IMessage.cs" />
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册