public static Vector2 ConvertVector2(JSONClass convert) { Vector2 vector = Vector2.zero; vector.x = convert["x"].AsFloat; vector.y = convert["y"].AsFloat; return vector; }
public static JSONClass ConvertVector2(Vector2 convert) { JSONClass vector = new JSONClass(); vector.Add("x", new JSONData(convert.x)); vector.Add("y", new JSONData(convert.y)); return vector; }
public void Serialize(JSONClass cls) { foreach (var item in Positions) { cls.Add(item.Key, item.Value.Serialize()); } }
public static JSONClass ToJSON(MonoHelper helper) { JSONClass componentData = new JSONClass(); componentData.Add("hash", new JSONData(helper.monoID)); componentData.Add("fields", GetFields(helper)); return componentData; }
public virtual void FromJSON(JSONClass json) { MonoHash hash = helper.GetHash(); hash.fullPosHash = json["hash"]; System.Type t = GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy; FieldInfo[] fields = t.GetFields(flags); FieldInfo[] badFieldArray = typeof(MonoHelper).GetFields(flags); List<string> badFields = new List<string>(); foreach (FieldInfo field in badFieldArray) { badFields.Add(field.Name); } JSONClass fieldJSON = json["fields"].AsObject; foreach (FieldInfo field in fields) { string fieldName = field.Name; if (badFields.Contains(fieldName) || System.Attribute.IsDefined(field, typeof(DontSave))) { continue; } SaveGame.LoadField(fieldJSON[fieldName].AsObject, field, helper); } }
public void Serialize(JSONClass cls) { foreach (var item in _dict) { cls.Add(item.Key, new JSONData(item.Value)); } }
public void Deserialize(JSONClass cls) { _dict.Clear(); foreach (KeyValuePair<string, JSONNode> jsonNode in cls) { _dict.Add(jsonNode.Key, jsonNode.Value.Value); } }
public static Vector3 ConvertVector3(JSONClass convert) { Vector3 vector = Vector3.zero; vector.x = convert["x"].AsFloat; vector.y = convert["y"].AsFloat; vector.z = convert["z"].AsFloat; return vector; }
public JSONNode SerializeColor(Color color) { var cls = new JSONClass { {"r", new JSONData(color.r)}, {"g", new JSONData(color.g)}, {"b", new JSONData(color.b)}, {"a", new JSONData(color.a)} }; return cls; }
public void Deserialize(JSONClass cls) { Positions.Clear(); foreach (KeyValuePair<string, JSONNode> cl in cls) { var locations = new FilterLocations(); if (!(cl.Value is JSONClass)) continue; locations.Deserialize(cl.Value.AsObject); Positions.Add(cl.Key, locations); } }
public MarketItem(JSONClass item) { ProductId = item["ProductId"].Value; Name = item["Name"].Value; Price = item["Price"].AsDouble; SitePrice = item["SitePrice"].AsDouble; SubscriptionPrice = item["SubscriptionPrice"].AsDouble; PremiumSupportPerMonth = item["PremiumSupportPerMonth"].AsDouble; SiteSubscriptionPrice = item["SiteSubscriptionPrice"].AsDouble; PremiumSupportAvailable = item["PremiumSupportAvailable"].AsBool; Owned = item["Owned"].AsBool; }
public string AgentList() { try { AgentBAL oAgentBAL = new AgentBAL(); DataTable dt = new DataTable(); dt = oAgentBAL.SelectAgent(); JSONClass objJSONClass = new JSONClass(); return objJSONClass.CreateJSONParameters(dt); } catch { throw; } }
private static void LoadLocalization() { string currentLanguage = PlayerPrefs.GetString("language", "English"); language = (CurrentLanguage)System.Enum.Parse(typeof(CurrentLanguage), currentLanguage, true); string fileName = GlobalConsts.GetDataPath() + "/GameData/Localization/" + language.ToString() + ".json"; if (!System.IO.File.Exists(fileName)) { fileName = GlobalConsts.GetDataPath() + "/GameData/Localization/English.json"; if (!System.IO.File.Exists(fileName)) { System.IO.File.WriteAllText(fileName, "{}"); } } string rawJSON = JSONSystem.JSON.GetRawJSONFromFile(fileName); localizedStrings = JSONSystem.JSON.Parse(rawJSON) as JSONClass; }
public void Serialize(JSONClass cls) { cls.Add("CodeGenDisabled", new JSONData(CodeGenDisabled)); cls.Add("SnapSize", new JSONData(_snapSize)); cls.Add("Snap", new JSONData(_snap)); cls.Add("CodePathStrategyName", new JSONData(_codePathStrategyName)); cls.Add("GridLinesColor", SerializeColor(GridLinesColor)); cls.Add("GridLinesColorSecondary", SerializeColor(GridLinesColorSecondary)); cls.Add("AssociationLinkColor", SerializeColor(_associationLinkColor)); cls.Add("DefinitionLinkColor", SerializeColor(_definitionLinkColor)); cls.Add("InheritanceLinkColor", SerializeColor(_inheritanceLinkColor)); cls.Add("SceneManagerLinkColor", SerializeColor(_sceneManagerLinkColor)); cls.Add("SubSystemLinkColor", SerializeColor(_subSystemLinkColor)); cls.Add("TransitionLinkColor", SerializeColor(_transitionLinkColor)); cls.Add("ViewLinkColor", SerializeColor(_viewLinkColor)); cls.Add("RootNamespace", new JSONData(RootNamespace)); }
public string PropertyList(string buyorrent, string type, string address) { try { PropertyBAL oPropertyBAL = new PropertyBAL(); PropertyBO oPropertyBO = new PropertyBO(); oPropertyBO.address = address; oPropertyBO.type = type; oPropertyBO.buyorrent = buyorrent; DataTable dt = new DataTable(); dt = oPropertyBAL.FindProperty(oPropertyBO); JSONClass objJSONClass = new JSONClass(); return objJSONClass.CreateJSONParameters(dt); } catch { throw; } }
/// <summary> /// Binds a key to active an InputCommand and saves it to PlayerPrefs. /// Note that it will not save to PlayerPrefs if the build is a debug build. /// </summary> /// <param name="a">The command to bind.</param> /// <param name="k">The key to bind the command to.</param> public static void BindKey(InputCommand a, KeyCode k) { Console.Log("Binding " + k + " to " + a); a.keyPress = k; if (keysPressed.ContainsKey(k)) { keysPressed[k] = a; } else { keysPressed.Add(k, a); } JSONClass bindings = new JSONClass(); foreach (KeyValuePair<KeyCode, InputCommand> kvp in keysPressed) { bindings.Add(kvp.Key.ToString(), new JSONData(kvp.Value.ToString())); } if (!Debug.isDebugBuild) { PlayerPrefs.SetString("bindings", bindings.ToString()); PlayerPrefs.Save(); } }
public void Deserialize(JSONClass cls) { if (cls["CodeGenDisabled"] != null) { CodeGenDisabled = cls["CodeGenDisabled"].AsBool; } CodePathStrategyName = cls["CodePathStrategyName"]; AssociationLinkColor = DeserializeColor(cls["AssociationLinkColor"]); DefinitionLinkColor = DeserializeColor(cls["DefinitionLinkColor"]); InheritanceLinkColor = DeserializeColor(cls["InheritanceLinkColor"]); SceneManagerLinkColor = DeserializeColor(cls["SceneManagerLinkColor"]); SubSystemLinkColor = DeserializeColor(cls["SubSystemLinkColor"]); TransitionLinkColor = DeserializeColor(cls["TransitionLinkColor"]); ViewLinkColor = DeserializeColor(cls["ViewLinkColor"]); SnapSize = cls["SnapSize"].AsInt; Snap = cls["Snap"].AsBool; GridLinesColor = DeserializeColor(cls["GridLinesColor"], new Color(0.271f, 0.271f, 0.271f)); GridLinesColorSecondary = DeserializeColor(cls["GridLinesColorSecondary"], new Color(0.169f, 0.169f, 0.169f)); if (cls["RootNamespace"] != null) { RootNamespace = cls["RootNamespace"].Value; } }
void BuildEnclosure(JSONClass node, Transform parent) { //Instantiate empty game object with lossy scale of enclsoue dims // Recurse through }
public string PropertyListI(string buyorrent, string type, string address, string neighborhood, string startArea, string startRate, string endArea, string endRate) { try { PropertyBAL oPropertyBAL = new PropertyBAL(); PropertyBO oPropertyBO = new PropertyBO(); PropertyBO oIPropertyBO = new PropertyBO(); oPropertyBO.address = address; oPropertyBO.type = type; oPropertyBO.buyorrent = buyorrent; oPropertyBO.neighborhood = neighborhood; oPropertyBO.size = long.Parse(startArea); oPropertyBO.rate = long.Parse(startRate); oIPropertyBO.size = long.Parse(endArea); oIPropertyBO.rate = long.Parse(endRate); DataTable dt = new DataTable(); dt = oPropertyBAL.FindProperty(oPropertyBO, oIPropertyBO); JSONClass objJSONClass = new JSONClass(); return objJSONClass.CreateJSONParameters(dt); } catch { throw; } }
public void MatchmakingServersFromMasterServer(string masterServerHost, ushort masterServerPort, int elo, System.Action <MasterServerResponse> callback = null, string gameId = "myGame", string gameType = "any", string gameMode = "all") { // The Master Server communicates over TCP TCPMasterClient client = new TCPMasterClient(); // Once this client has been accepted by the master server it should send it's get request client.serverAccepted += (sender) => { try { // Create the get request with the desired filters JSONNode sendData = JSONNode.Parse("{}"); JSONClass getData = new JSONClass(); getData.Add("id", gameId); getData.Add("type", gameType); getData.Add("mode", gameMode); getData.Add("elo", new JSONData(elo)); sendData.Add("get", getData); // Send the request to the server client.Send(Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true)); } catch { // If anything fails, then this client needs to be disconnected client.Disconnect(true); client = null; MainThreadManager.Run(() => { if (callback != null) { callback(null); } }); } }; // An event that is raised when the server responds with hosts client.textMessageReceived += (player, frame, sender) => { try { // Get the list of hosts to iterate through from the frame payload JSONNode data = JSONNode.Parse(frame.ToString()); MainThreadManager.Run(() => { if (data["hosts"] != null) { MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray); if (callback != null) { callback(response); } } else { if (callback != null) { callback(null); } } }); } finally { if (client != null) { // If we succeed or fail the client needs to disconnect from the Master Server client.Disconnect(true); client = null; } } }; try { client.Connect(masterServerHost, masterServerPort); } catch (System.Exception ex) { Debug.LogError(ex.Message); MainThreadManager.Run(() => { if (callback != null) { callback(null); } }); } }
public GetElementAttributeRequest(JSONClass json) : base(json) { }
protected abstract void PopulateFromJSON(JSONClass data);
public IEnumerator ISendInvitationToUser(int Id, string message, int EventOrSocietyId, bool shoudShowPopUp, string RoomName = null) { var encoding = new System.Text.UTF8Encoding(); Dictionary <string, string> postHeader = new Dictionary <string, string> (); var jsonElement = new Simple_JSON.JSONClass(); jsonElement ["data_type"] = "save"; jsonElement ["sender_player_id"] = PlayerPrefs.GetInt("PlayerId").ToString(); jsonElement ["reciever_player_id"] = Id.ToString(); jsonElement ["message"] = message; var jsonarray = new JSONArray(); if (RoomName == null) { var jsonItem = new JSONClass(); jsonItem ["item_id"] = EventOrSocietyId.ToString(); jsonItem ["item_type"] = "Society"; jsonarray.Add(jsonItem); } else { var jsonItem = new JSONClass(); jsonItem ["item_id"] = EventOrSocietyId.ToString(); jsonItem ["item_type"] = "CoOp"; var jsonItem2 = new JSONClass(); jsonItem2 ["item_id"] = EventOrSocietyId.ToString(); jsonItem2 ["item_type"] = RoomName; jsonarray.Add(jsonItem); jsonarray.Add(jsonItem2); } jsonElement ["items"] = jsonarray; postHeader.Add("Content-Type", "application/json"); postHeader.Add("Content-Length", jsonElement.Count.ToString()); WWW www = new WWW(InvitationUrl, encoding.GetBytes(jsonElement.ToString()), postHeader); // print ("jsonDtat is ==>> " + jsonElement.ToString ()); yield return(www); if (www.error == null) { JSONNode _jsnode = Simple_JSON.JSON.Parse(www.text); // print ("_jsnode ==>> " + _jsnode.ToString ()); if (_jsnode ["status"].ToString().Contains("200")) { // print ("Success"); if (RoomName == null) { if (shoudShowPopUp) { ShowPopUp("Invitation sent successfully", () => ScreenManager.Instance.Admin_MemberDiscriptionPanel.GetComponent <SocietyDescriptionController> ().SocietyMemberList(true)); } IndicationManager.Instance.SendIndicationToUsers(new int[] { Id }, "Invitation"); } yield return(true); } else { yield return(false); } } else { yield return(false); } }
void SetProp(EffectLayer effectLayer, JSONClass modData) { var fw = modData ["FRAMES WIDE"].AsInt; var fh = modData ["FRAMES HIGH"].AsInt; if (fw > 0) { Debug.Log("Set UV"); effectLayer.UVType = 1; effectLayer.Cols = fw; effectLayer.Rows = Mathf.Max(1, fh); } var renderType = modData ["RENDER TYPE"].Value; if (renderType == "Billboard Up" || renderType == "Billboard Up Camera" || renderType == "Billboard Forward") { effectLayer.RenderType = 0; effectLayer.SpriteType = (int)Xft.STYPE.BILLBOARD_UP; } else if (renderType == "EntityWorld") { Debug.LogError(" Model Particle " + effectLayer.name); effectLayer.RenderType = 3; } else if (renderType == "RibbonTrail") { Debug.LogError("RibbomTrail"); effectLayer.RenderType = 1; } else if (renderType == "Sphere") { effectLayer.RenderType = 3; //effectLayer.CMesh = ; Debug.LogError("手动设置Sphere 粒子模型"); } var isLight = modData ["IS LIGHT"].AsBool; if (isLight) { effectLayer.gameObject.layer = (int)GameLayer.Light; } if (modData ["ORIGIN"].Value == "Bottom Center") { effectLayer.OriPoint = (int)ORIPOINT.BOTTOM_CENTER; } else if (modData ["ORIGIN"].Value == "Center Left") { effectLayer.OriPoint = (int)ORIPOINT.LEFT_CENTER; } if (modData ["POSITIONX"].Value != "") { var px = modData ["POSITIONX"].AsFloat; var py = modData ["POSITIONY"].AsFloat; var pz = modData ["POSITIONZ"].AsFloat; effectLayer.transform.localPosition = new Vector3(-px, py, pz); } var vs = modData ["VELOCITY SCALE"]; if (vs != null) { velScale = vs.AsFloat; } else { velScale = 1; } if (effectLayer.RenderType == 1) { var segments = modData ["SEGMENTS"]; var width = modData ["WIDTH"]; effectLayer.MaxRibbonElements = (int)segments.AsDouble; effectLayer.RibbonWidth = (float)width.AsDouble; } }
void SetScale(EffectLayer effectLayer, JSONClass modData) { bool fix = false; if (!string.IsNullOrEmpty(modData ["FIXED"].Value)) { fix = modData ["FIXED"].AsBool; } Debug.Log("SetScale: " + modData.ToString()); effectLayer.ScaleType = RSTYPE.CURVE01; if (string.IsNullOrEmpty(modData ["X"].Value)) { var f = new float[] { 2, 0, 1, 1, 1 }; SetScaleXCurve(effectLayer, f); } else { var scaleX = ConvertToFloat(modData ["X"].Value); SetScaleXCurve(effectLayer, scaleX); } //fix 确保XY 比例不变 if (!fix) { if (string.IsNullOrEmpty(modData ["Y"].Value)) { //var f = new float[]{ 2, 0, 1, 1, 1 }; //SetScaleYCurve(effectLayer, f); effectLayer.UseSameScaleCurve = true; } else { var scaleX = ConvertToFloat(modData ["X"].Value); var scaleY = ConvertToFloat(modData ["Y"].Value); SetScaleYCurve(effectLayer, scaleY, scaleX); } } else { effectLayer.UseSameScaleCurve = true; } /* * if (fix) * { * effectLayer.ScaleType = RSTYPE.CURVE01; * effectLayer.UseSameScaleCurve = true; * * var scale = ConvertToFloat(modData ["X"].Value); * int scaType = (int)scale [0]; * if (scaType == 4) * { * SetRandomScaleCurve(effectLayer, scale); * } else * { * //scale[0] 2 curve 3 straight * int count = (scale.Length - 1) / 2; * float x = 0; * float value = 0; * float max = 1; * for (int i = 1; i < scale.Length; i++) * { * if ((i - 1) % 2 == 0) * { * x = scale [i]; * } else * { * value = scale [i]; * if (Mathf.Abs(value) > max) * { * max = Mathf.Abs(value); * } * } * } * effectLayer.MaxScaleCalue = max; * var ks = new Keyframe[count]; * int c = 0; * for (int i = 1; i < scale.Length; i++) * { * if ((i - 1) % 2 == 0) * { * x = scale [i]; * } else * { * value = scale [i]; * Debug.Log("Add Scale Node " + value / max); * ks [c] = new Keyframe(x, value / max); * c++; * * } * } * effectLayer.ScaleXCurveNew = new AnimationCurve(ks); * effectLayer.ScaleWrapMode = WRAP_TYPE.LOOP; * } * } */ }
public void Serialize(JSONClass cls) { cls.Add("OutputIdentifier", OutputIdentifier ?? string.Empty); cls.Add("InputIdentifier", InputIdentifier ?? string.Empty); }
private JSONNode CreateStatement(string trace) { string[] parts = Utils.parseCSV(trace); string timestamp = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc).AddMilliseconds(long.Parse(parts[0])).ToString("yyyy-MM-ddTHH:mm:ss.fffZ"); JSONNode statement = JSONNode.Parse("{\"timestamp\": \"" + timestamp + "\"}"); if (actor != null) { statement.Add("actor", actor); } statement.Add("verb", CreateVerb(parts[1])); statement.Add("object", CreateObject(parts)); if (parts.Length > 4) { // Parse extensions int extCount = parts.Length - 4; if (extCount > 0 && extCount % 2 == 0) { // Extensions come in <key, value> pairs JSONClass extensions = new JSONClass(); JSONNode extensionsChild = null; for (int i = 4; i < parts.Length; i += 2) { string key = parts[i]; string value = parts[i + 1]; if (key.Equals("") || value.Equals("")) { continue; } if (key.Equals(Tracker.Extension.Score.ToString().ToLower())) { JSONClass score = new JSONClass(); float valueResult = 0f; string msg = "Tracker-xAPI: Score isn't a number, ignoring.", smsg = "Tracker-xAPI: Score isn't a number."; if (Utils.check <ExtensionXApiException> (value, msg, smsg) && Utils.isFloat <ExtensionXApiException>(value, msg, smsg, out valueResult)) { score.Add("raw", new JSONData(valueResult)); extensions.Add("score", score); } } else if (key.Equals(Tracker.Extension.Success.ToString().ToLower())) { bool valueResult = false; string msg = "Tracker-xAPI: Success isn't a bool value, ignoring.", smsg = "Tracker-xAPI: Success isn't a bool value."; if (Utils.check <ExtensionXApiException> (value, msg, smsg) && Utils.isBool <ExtensionXApiException> (value, msg, smsg, out valueResult)) { extensions.Add("success", new JSONData(valueResult)); } } else if (key.Equals(Tracker.Extension.Completion.ToString().ToLower())) { bool valueResult = false; string msg = "Tracker-xAPI: Completion isn't a bool value, ignoring.", smsg = "Tracker-xAPI: Completion isn't a bool value."; if (Utils.check <ExtensionXApiException> (value, msg, smsg) && Utils.isBool <ExtensionXApiException> (value, msg, smsg, out valueResult)) { extensions.Add("completion", new JSONData(valueResult)); } } else if (key.Equals(Tracker.Extension.Response.ToString().ToLower())) { extensions.Add("response", new JSONData(value)); } else { if (extensionsChild == null) { extensionsChild = JSONNode.Parse("{}"); extensions.Add("extensions", extensionsChild); } string id = key; bool tbool; int tint; float tfloat; double tdouble; if (extensionIds.ContainsKey(key)) { id = extensionIds [key]; } if (int.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out tint)) { extensionsChild.Add(id, new JSONData(tint)); } else if (float.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out tfloat)) { extensionsChild.Add(id, new JSONData(tfloat)); } else if (double.TryParse(value, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out tdouble)) { extensionsChild.Add(id, new JSONData(tdouble)); } else if (bool.TryParse(value, out tbool)) { extensionsChild.Add(id, new JSONData(tbool)); } else { extensionsChild.Add(id, new JSONData(value)); } } } statement.Add("result", extensions); } } return(statement); }
private void SendAbilities(List <DevAbility> abilities, List <DevPAPerk> perks) { JSONNode node = new JSONClass(); for (int i = 0; i < abilities.Count; i++) { node["talents"][i]["ability"] = abilities[i].Key; for (int a = 0; a < abilities[i].Perks.Count; a++) { node["talents"][i]["perks"][a]["atLeastLvl"] = abilities[i].Perks[a].MinLevel.ToString(); node["talents"][i]["perks"][a]["perksOffered"] = abilities[i].Perks[a].PerksOffered.ToString(); for (int b = 0; b < abilities[i].Perks[a].AddToPool.Count; b++) { node["talents"][i]["perks"][a]["addToPool"][b] = abilities[i].Perks[a].AddToPool[b].ToString(); } } for (int a = 0; a < abilities[i].Spells.Count; a++) { node["talents"][i]["spells"][a]["key"] = abilities[i].Spells[a].Key.ToString(); node["talents"][i]["spells"][a]["level"] = abilities[i].Spells[a].Level.ToString(); node["talents"][i]["spells"][a]["mana"] = abilities[i].Spells[a].Mana.ToString(); node["talents"][i]["spells"][a]["cooldown"] = abilities[i].Spells[a].Cooldown.ToString(); for (int b = 0; b < abilities[i].Spells[a].Perks.Count; b++) { node["talents"][i]["spells"][a]["perks"][b]["key"] = abilities[i].Spells[a].Perks[b].Key.ToString(); node["talents"][i]["spells"][a]["perks"][b]["value"] = abilities[i].Spells[a].Perks[b].Value.ToString(); } for (int b = 0; b < abilities[i].Spells[a].HitIfTargetHasBuff.Count; b++) { node["talents"][i]["spells"][a]["hitIfTargetHasBuff"][b] = abilities[i].Spells[a].HitIfTargetHasBuff[b].ToString(); } for (int b = 0; b < abilities[i].Spells[a].ClearTargetBuffs.Count; b++) { node["talents"][i]["spells"][a]["clearTargetBuffs"][b] = abilities[i].Spells[a].ClearTargetBuffs[b].ToString(); } } for (int a = 0; a < abilities[i].InitialPerks.Count; a++) { node["talents"][i]["initialPerks"][a]["key"] = abilities[i].InitialPerks[a].Key.ToString(); node["talents"][i]["initialPerks"][a]["value"] = abilities[i].InitialPerks[a].Level.ToString(); } node["talents"][i]["hitType"] = abilities[i].HitType; node["talents"][i]["powerType"] = abilities[i].PowerType; node["talents"][i]["manaCost"] = abilities[i].ManaCost.ToString(); } for (int i = 0; i < perks.Count; i++) { node["perkCollection"][i]["key"] = perks[i].Key; node["perkCollection"][i]["value"] = perks[i].PrecentPerUpgrade.ToString(); node["perkCollection"][i]["max"] = perks[i].UpgradeCap.ToString(); node["perkCollection"][i]["default"] = perks[i].StartingValue.ToString(); node["perkCollection"][i]["client"].AsBool = perks[i].IsClient; node["perkCollection"][i]["type"] = perks[i].Type; for (int a = 0; a < perks[i].Buff.BonusPerks.Count; a++) { node["perkCollection"][i]["bonusPerks"][a]["key"] = perks[i].Buff.BonusPerks[a].Key.ToString(); node["perkCollection"][i]["bonusPerks"][a]["value"] = perks[i].Buff.BonusPerks[a].Value.ToString(); } node["perkCollection"][i]["party"].AsBool = perks[i].Buff.PartyBuff; node["perkCollection"][i]["acc"] = "0";//perks[i].PrecentAccelerationPerUpgrade.ToString(); } UpdateContent(node, "/talents/generate"); }
private void RestartServer() { JSONNode node = new JSONClass(); UpdateContent(node, "/restart"); }
// Use this for initialization void Awake() { ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; //Use UtilScript to write to a file in one line UtilScript.WriteStringToFile(Application.dataPath, "hello.txt", "hi!"); //Use UtilScript to clone and mod a Vector3 transform.position = UtilScript.CloneModVector3(transform.position, 1, 0, 0); //Use UtilScript to clone a Vector3 Vector3 pos = UtilScript.CloneVector3(transform.position); //Create a JSONClass object JSONClass subClass = new JSONClass(); //Add a value to subClass subClass["test"] = "value"; //Create another JSONClass object, must include "using SimpleJSON" above JSONClass json = new JSONClass(); //Add floats, strings, bools, even other classes to our json object json["x"].AsFloat = 7; json["y"].AsFloat = 0; json["z"].AsFloat = 2; json["name"] = "Matt"; json["Alt Facts"].AsBool = false; json["sub"] = subClass; //Write "json" to a file using UtilScript UtilScript.WriteStringToFile(Application.dataPath, "file.json", json.ToString()); //print out the string value of "json" Debug.Log(json); //Read in a file into a string using UtilScript string result = UtilScript.ReadStringFromFile(Application.dataPath, "file.json"); //Parse string we read in from a file into a JSONNode JSONNode readJSON = JSON.Parse(result); //print out a value from the JSONNode Debug.Log(readJSON["z"].AsFloat); //Get the content from a webpage, in this case, a json value for the sunset time in Hawaii string content = WeatherFromCity(city, state); //content = "What"; //turn string into a JSONNode WeatherData = JSON.Parse(content); //Get the sunset time from the JSONNode //Change making: Change ["Astronomy"]["sunset"] to ["item"]["condition"]["text"] DataTime = WeatherData["query"]["results"]["channel"]["lastBuildDate"]; //Shelley, Add Weather by the same way getting the Time weather = WeatherData["query"]["results"]["channel"]["item"]["condition"]["text"]; print(weather); print(DataTime); Debug.Log("START END"); }
private void RequestConnection() { try { //make handshake with TCP_client, and the port is set to be 4444 var client = new TcpClient(CommandSet.IP, CommandSet.DISCOVERY_PORT); var stream = new NetworkStream(client.Client); //initialize reader and writer var streamWriter = new StreamWriter(stream); var streamReader = new StreamReader(stream); //when the drone receive the message bellow, it will return the confirmation var handshake = new JSONClass(); handshake["controller_type"] = "computer"; handshake["controller_name"] = "oyo"; handshake["d2c_port"] = new JSONData(43210); // "43210" handshake["arstream2_client_stream_port"] = new JSONData(55004); handshake["arstream2_client_control_port"] = new JSONData(55005); streamWriter.WriteLine(handshake.ToString()); streamWriter.Flush(); var message = streamReader.ReadLine(); if (message == null) { throw new Exception(message); } //initialize this.GenerateAllStates(); this.GenerateAllSettings(); //enable video streaming //this.EnableVideoStream(); if (this._d2c.Connect() == false) { return; } this.Connected = true; this._commandThread = new Thread(this.commandThreadRoutine); this._commandThread.Start(); this._streamingThread = new Thread(this.streamingThreadRoutine); this._streamingThread.Start(); if (this.OnConnected != null) { this.OnConnected.Invoke(this); } } catch (Exception e) { if (this.OnError != null) { this.OnError.Invoke(this, e.Message); } } }
public void Deserialize(JSONClass cls) { foreach (KeyValuePair<string, JSONNode> cl in cls) { Add(cl.Key, DeserializeValue(cl.Value)); } }
public void BulkUpdate(JSONClass data) { PopulateFromJSON(data); }
private void UpdateValues(string[] lines) { // EWUnityExtensions.Log("Update values: " + lines[0]); // TODO: actually only one line is needed ... // for (int i=0; i < lines.Length ; i++) { string line = lines [0]; if (debugShowData) { EWUnityExtensions.Log("Line to parse is '" + line + "'"); } JSONNode rootNode = JSON.Parse(line); // EWUnityExtensions.Log ("input interpreted as Json has values # " + rootNode.Count); JSONNode values = (JSONNode)rootNode ["values"]; if (values != null) { // EWUnityExtensions.Log ("=> values has => # " + values.Count); } for (int j = 0; j < inNames.Length; j++) { string inValName = inNames [j]; JSONNode valueArray = values [j]; // TODO: parse the values and split them appropriately. inputs can be look: // [[], [], [], [], [0.990325079762794], [-0.2852937250435257]] // OR [[0.990325079762794,0.123], [], [], [], [], [-0.2852937250435257]] // OR [[], [], [], [], [], []] // OR [[0.123], [0.123], [0.123], [0.123], [0.123], [0.123]] bool foundFitting = false; if (this.debugShowData) { // EWUnityExtensions.Log("# controlInputs to update: " + ControlInput.allControlsList.Count); } foreach (ControlInput ci in ControlInput.allControlsList) { if (ci.controlName == inValName) { float avg_val = 0; for (int ik = 0; ik < valueArray.Count; ik++) { JSONNode val = valueArray [ik]; bool isJsonClass = val is JSONClass; bool isJsonData = val is SimpleJSON.JSONData; if (debugShowData) { EWUnityExtensions.Log("val has count # " + val.Count + " and is json class ? " + isJsonClass); } if (isJsonClass && ci.isMultiInput) { JSONClass valDict = (JSONClass)val; if (debugShowData) { EWUnityExtensions.Log("valDict has children: #" + valDict.Count); } foreach (string key in valDict.GetKeys()) { float childVal = float.Parse(valDict [key]); if (debugShowData) { EWUnityExtensions.Log("=> found key " + key + " with value " + childVal); } string multiFullName = ControlInputMulti.MakeMultiValueName(ci.controlName, key); ControlInputMulti ciChild = null; if (ControlInputMulti.allMultiControls.ContainsKey(multiFullName) == false) { CreateQueueEntry entry = new CreateQueueEntry(); entry.ciParent = ci; entry.multiId = key; entry.name = multiFullName; entry.initVal = childVal; createQueue.Add(entry); } else { ciChild = ControlInputMulti.allMultiControls [multiFullName]; ciChild.SetCurrentValue(childVal); } } } else if (isJsonData) { avg_val += val.AsFloat; } else { EWUnityExtensions.LogWarning("Unknown json type" + val.ToString() + " " + val.GetType() + ", isMulti ? " + ci.isMultiInput); } } ci.SetCurrentValue(avg_val); foundFitting = true; break; } } if (foundFitting) { // EWUnityExtensions.Log("Found fitting control!"); } else { // EWUnityExtensions.Log("Found NOOOO fitting control!"); } } }
public GetElementTextRequest(JSONClass json) : base(json) { }
void Update() { if (dummyMessageTimer >= 0) { if(Mathf.Abs(dummyMessageTimer - Time.time) >= 0.3f) { string msgJson = "MESG{\"channel_id\": \"0\", \"message\": \"Dummy Text on Editor Mode - " + Time.time + "\", \"user\": {\"image\": \"http://url\", \"name\": \"Sender\"}, \"ts\": 1418979273365, \"scrap_id\": \"\"}"; _OnMessageReceived(msgJson); dummyMessageTimer = Time.time; } } if (dummyChannelListFlag) { dummyChannelListFlag = false; JSONArray channels = new JSONArray(); JSONClass channel = new JSONClass(); channel.Add ("id", new JSONData(1)); channel.Add ("channel_url", new JSONData("app_prefix.channel_url")); channel.Add ("name", new JSONData("Sample")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(2)); channel.Add ("channel_url", new JSONData("app_prefix.Unity3d")); channel.Add ("name", new JSONData("Unity3d")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(3)); channel.Add ("channel_url", new JSONData("app_prefix.Lobby")); channel.Add ("name", new JSONData("Lobby")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(4)); channel.Add ("channel_url", new JSONData("app_prefix.Cocos2d")); channel.Add ("name", new JSONData("Cocos2d")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(5)); channel.Add ("channel_url", new JSONData("app_prefix.GameInsight")); channel.Add ("name", new JSONData("GameInsight")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(6)); channel.Add ("channel_url", new JSONData("app_prefix.iOS")); channel.Add ("name", new JSONData("iOS")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(7)); channel.Add ("channel_url", new JSONData("app_prefix.Android")); channel.Add ("name", new JSONData("Android")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(8)); channel.Add ("channel_url", new JSONData("app_prefix.News")); channel.Add ("name", new JSONData("News")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(9)); channel.Add ("channel_url", new JSONData("app_prefix.Lobby")); channel.Add ("name", new JSONData("Lobby")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); channel.Add ("id", new JSONData(10)); channel.Add ("channel_url", new JSONData("app_prefix.iPad")); channel.Add ("name", new JSONData("iPad")); channel.Add ("cover_img_url", new JSONData("http://localhost/image.jpg")); channel.Add ("member_count", new JSONData(999)); channels.Add(channel.ToString()); _OnQueryChannelList(channels.ToString()); } }
public static Vector4 ConvertVector4(JSONClass convert) { Vector4 vector = Vector4.zero; vector.w = convert["w"].AsFloat; vector.x = convert["x"].AsFloat; vector.y = convert["y"].AsFloat; vector.z = convert["z"].AsFloat; return vector; }
private void socketReceiveWork(object accept) { Socket s = accept as Socket; string json = ""; Request request = new Request(); request.DeviceId = ""; try { while (true) { //通过clientSocket接收数据 s.ReceiveTimeout = -1; int receiveNumber = s.Receive(buffer); if (receiveNumber == 1 && buffer[0] == HeartBeat.ASK) { mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, Receive: HeartBeat.ASK, ByteCount:{2}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, receiveNumber); s.Send(new byte[] { HeartBeat.ANS }); mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, response: HeartBeat.ANS", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId); continue; } if (receiveNumber <= 0) { mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, Receive: null, ByteCount:{3}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, json, receiveNumber); break; } json = Encoding.UTF8.GetString(buffer, 0, receiveNumber); mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, Receive:{2}, ByteCount:{3}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, json, receiveNumber); request.Code = -1; try { JSONNode node = JSON.Parse(json); request.Code = int.Parse(node[RequestKey.Code]); request.Args = (node[RequestKey.Args] as JSONArray).Childs.Select((m) => ((string)m)).ToArray(); request.RequestId = node[RequestKey.RequestId]; if (request.RequestId == null) { request.RequestId = ""; } string deviceId = node[RequestKey.DeviceId]; if (!string.IsNullOrEmpty(deviceId)) { request.DeviceId = deviceId; } } catch { request.Args = new string[0]; } if (request.Code == (int)RequestCode.DisConnect) { break; } string end; try { end = handleCommand(s, json, request); } catch (Exception ex) { end = ex.Message; Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } if (end != null) { JSONClass response = new JSONClass(); response.Add(ResponseKey.Code, "0"); response.Add(ResponseKey.Data, end); response.Add(ResponseKey.RequestId, request.RequestId); string responseJson = response.ToString(); mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, response:{2}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, responseJson); s.Send(Encoding.UTF8.GetBytes(responseJson)); } else { mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, no response", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId); } } } catch (Exception ex) { mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, while Receivere Exception:{2}", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId, ex.Message); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } finally { mLogHelper.InfoFormat("addr:{0}, deviceId:{1}, socket close", ((IPEndPoint)s.RemoteEndPoint).Address.ToString(), request.DeviceId); s.Shutdown(SocketShutdown.Both); s.Disconnect(true); s.Close(); } }
public ComplexTapRequest(JSONClass json) : base(json) { }
public InAppMessageModal(JSONClass json) : base(json) { }
public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { var tmp = new JSONClass(); tmp.Add(aKey, value); Set(tmp); } }
public static JSONClass GetFields(MonoHelper source, JSONClass fieldArray) { System.Type t = source.GetType(); BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy; FieldInfo[] fields = t.GetFields(flags); FieldInfo[] badFieldArray = typeof(MonoHelper).GetFields(flags); List<string> badFields = new List<string>(); foreach (FieldInfo field in badFieldArray) { badFields.Add(field.Name); } foreach (FieldInfo field in fields) { object fieldObj = field.GetValue(source); if (fieldObj == null) { continue; } string fieldName = field.Name; if (badFields.Contains(fieldName) || System.Attribute.IsDefined(field, typeof(DontSave))) { continue; } JSONClass fieldData = SaveGame.SaveField(fieldObj, fieldName); if (fieldData == null) { continue; } fieldArray.Add(fieldName, fieldData); } return fieldArray; }
public static JSONNode Deserialize(System.IO.BinaryReader aReader) { JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte(); switch (type) { case JSONBinaryTag.Array: { int count = aReader.ReadInt32(); JSONArray tmp = new JSONArray(); for (int i = 0; i < count; i++) tmp.Add(Deserialize(aReader)); return tmp; } case JSONBinaryTag.Class: { int count = aReader.ReadInt32(); JSONClass tmp = new JSONClass(); for (int i = 0; i < count; i++) { string key = aReader.ReadString(); var val = Deserialize(aReader); tmp.Add(key, val); } return tmp; } case JSONBinaryTag.Value: { return new JSONData(aReader.ReadString()); } case JSONBinaryTag.IntValue: { return new JSONData(aReader.ReadInt32()); } case JSONBinaryTag.DoubleValue: { return new JSONData(aReader.ReadDouble()); } case JSONBinaryTag.BoolValue: { return new JSONData(aReader.ReadBoolean()); } case JSONBinaryTag.FloatValue: { return new JSONData(aReader.ReadSingle()); } default: { throw new Exception("Error deserializing JSON. Unknown tag: " + type); } } }
public KeyValuePair <EGAHTTPApiResponse, JSONClass> RequestInitReturningDict() #endif { JSONClass json; EGAHTTPApiResponse result = EGAHTTPApiResponse.NoResponse; string gameKey = GAState.GameKey; // Generate URL string url = baseUrl + "/" + gameKey + "/" + initializeUrlPath; GALogger.D("Sending 'init' URL: " + url); JSONClass initAnnotations = GAState.GetInitAnnotations(); // make JSON string from data string JSONstring = initAnnotations.ToString(); if (string.IsNullOrEmpty(JSONstring)) { result = EGAHTTPApiResponse.JsonEncodeFailed; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } string body = ""; HttpStatusCode responseCode = (HttpStatusCode)0; string responseDescription = ""; string authorization = ""; try { byte[] payloadData = CreatePayloadData(JSONstring, useGzip); HttpWebRequest request = CreateRequest(url, payloadData, useGzip); authorization = request.Headers[HttpRequestHeader.Authorization]; #if WINDOWS_UWP || WINDOWS_WSA using (Stream dataStream = await request.GetRequestStreamAsync()) #elif WINDOWS_PHONE using (Stream dataStream = await Task.Factory.FromAsync <Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)) #else using (Stream dataStream = request.GetRequestStream()) #endif { dataStream.Write(payloadData, 0, payloadData.Length); } #if WINDOWS_UWP || WINDOWS_WSA using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse) #elif WINDOWS_PHONE using (WebResponse response = await Task.Factory.FromAsync <WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)) #else using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) #endif { using (Stream dataStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(dataStream)) { string responseString = reader.ReadToEnd(); responseCode = ((HttpWebResponse)response).StatusCode; responseDescription = ((HttpWebResponse)response).StatusDescription; // print result body = responseString; } } } } catch (WebException e) { if (e.Response != null) { using (HttpWebResponse response = (HttpWebResponse)e.Response) { using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(streamResponse)) { string responseString = streamRead.ReadToEnd(); responseCode = response.StatusCode; responseDescription = response.StatusDescription; body = responseString; } } } } } catch (Exception e) { GALogger.E(e.ToString()); } // process the response GALogger.D("init request content : " + body); JSONNode requestJsonDict = JSON.Parse(body); EGAHTTPApiResponse requestResponseEnum = ProcessRequestResponse(responseCode, responseDescription, body, "Init"); // if not 200 result if (requestResponseEnum != EGAHTTPApiResponse.Ok && requestResponseEnum != EGAHTTPApiResponse.BadRequest) { GALogger.D("Failed Init Call. URL: " + url + ", Authorization: " + authorization + ", JSONString: " + JSONstring); result = requestResponseEnum; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } if (requestJsonDict == null) { GALogger.D("Failed Init Call. Json decoding failed"); result = EGAHTTPApiResponse.JsonDecodeFailed; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } // print reason if bad request if (requestResponseEnum == EGAHTTPApiResponse.BadRequest) { GALogger.D("Failed Init Call. Bad request. Response: " + requestJsonDict.AsObject.ToString()); // return bad request result result = requestResponseEnum; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } // validate Init call values JSONClass validatedInitValues = GAValidator.ValidateAndCleanInitRequestResponse(requestJsonDict); if (validatedInitValues == null) { result = EGAHTTPApiResponse.BadResponse; json = null; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); } // all ok result = EGAHTTPApiResponse.Ok; json = validatedInitValues; return(new KeyValuePair <EGAHTTPApiResponse, JSONClass>(result, json)); }
protected override void DoLoadJson(JSONClass jsonClass) { LoadJsonField(jsonClass, "radius", val => Collider.radius = val); LoadJsonField(jsonClass, "height", val => Collider.height = val); LoadJsonField(jsonClass, "center", val => Collider.center = val); }
// TODO: Finish Build Tray /* * Takes a Tray Node and builds it * @Param: tray, type JSONClass, the tray to build * @Param: parent, type is Transform, the parent object for this tray */ void BuildTray(JSONClass node, Transform parent) { }
public void Test() { var N = JSONNode.Parse("{\"name\":\"test\", \"array\":[1,{\"data\":\"value\"}]}"); print(N["array"].Count); N["array"][1]["Foo"] = "Bar"; P("'nice formatted' string representation of the JSON tree:"); P(N.ToString("")); P(""); P("'normal' string representation of the JSON tree:"); P(N.ToString()); P(""); P("content of member 'name':"); P(N["name"]); P(""); P("content of member 'array':"); P(N["array"].ToString("")); P(""); P("first element of member 'array': " + N["array"][0]); P(""); N["array"][0].AsInt = 10; P("value of the first element set to: " + N["array"][0]); P("The value of the first element as integer: " + N["array"][0].AsInt); P(""); P("N[\"array\"][1][\"data\"] == " + N["array"][1]["data"]); P(""); var data = N.SaveToBase64(); /*var data2 = N.SaveToCompressedBase64(); * N = null; * P("Serialized to Base64 string:"); * P(data); * P("Serialized to Base64 string (compressed):"); * P(data2); * P(""); * * N = JSONNode.LoadFromBase64(data); * P("Deserialized from Base64 string:"); * P(N.ToString()); * P(""); */ var I = new JSONClass(); I["version"].AsInt = 5; I["author"]["name"] = "Bunny83"; I["author"]["phone"] = "0123456789"; I["data"][-1] = "First item\twith tab"; I["data"][-1] = "Second item"; I["data"][-1]["value"] = "class item"; I["data"].Add("Forth item"); I["data"][1] = I["data"][1] + " 'addition to the second item'"; I.Add("version", "1.0"); P("Second example:"); P(I.ToString()); P(""); P("I[\"data\"][0] : " + I["data"][0]); P("I[\"data\"][0].ToString() : " + I["data"][0].ToString()); P("I[\"data\"][0].Value : " + I["data"][0].Value); P(I.ToString()); }
void SetEmit(EffectLayer effectLayer, JSONClass modData) { Log.Sys("SetEmit " + effectLayer.name + " modData " + modData.ToString()); var forever = modData ["NO EXPIRATION"].AsBool; var rateStr = modData ["EMIT RATE"].Value; var rate = new float[] { 0, 15 };//有15个 虫子在水面 waterskip if (string.IsNullOrEmpty(rateStr)) { } else { rate = ConvertToFloat(rateStr.Split(',')); } int rateType = (int)rate [0]; int rateMin = (int)rate [1]; int rateNum = 1; if (rateType == 0) { effectLayer.EmitRate = rateMin; effectLayer.MaxENodes = rateMin; rateNum = rateMin; /* * if (rateMin == 1) * { * effectLayer.IsBurstEmit = true; * } else * { * } */ } else { int rateMax = (int)rate [2]; effectLayer.EmitRate = rateMax; effectLayer.MaxENodes = rateMax; rateNum = rateMax; } if (forever) { effectLayer.IsNodeLifeLoop = true; effectLayer.IsBurstEmit = true; } else if (rateType == 0 && rateMin == 1) { effectLayer.IsNodeLifeLoop = true; effectLayer.IsBurstEmit = true; } else { effectLayer.IsNodeLifeLoop = false; effectLayer.IsBurstEmit = false; } var numLoops = modData ["NUM LOOPS"]; bool hasLoops = false; if (modData ["NUM LOOPS"] == null) { effectLayer.IsBurstEmit = false; effectLayer.EmitLoop = -1; } else if (modData ["NUM LOOPS"].AsInt == 1) { effectLayer.IsBurstEmit = true; effectLayer.EmitLoop = 1; } else if (numLoops.AsInt == 0) { hasLoops = true; effectLayer.IsBurstEmit = false; effectLayer.EmitLoop = 1; } { Log.Sys("Particle Life:"); float[] life; if (string.IsNullOrEmpty(modData ["PARTICLE LIFE"])) { life = new float[] { 1, 5, 10 }; } else { life = ConvertToFloat(modData ["PARTICLE LIFE"].Value); } int lifeType = (int)life [0]; float lifeTime = 1; if (lifeType == 1) { effectLayer.NodeLifeMin = life [1]; effectLayer.NodeLifeMax = life [2]; effectLayer.EmitDuration = 1; effectLayer.EmitLoop = -1; effectLayer.EmitDelay = 0; } else if (lifeType == 0) { effectLayer.NodeLifeMin = life [1]; effectLayer.NodeLifeMax = life [1]; effectLayer.EmitDuration = 1; effectLayer.EmitLoop = -1; effectLayer.EmitDelay = 0; } Log.Sys("NumLoops " + numLoops); lifeTime = effectLayer.NodeLifeMax; effectLayer.MaxENodes = (int)Mathf.Max(rateNum, rateNum * lifeTime); } if (hasLoops && numLoops.AsInt == 0) { effectLayer.IsBurstEmit = false; effectLayer.EmitLoop = 1; } var duration = modData ["EMIT DURATION"]; if (duration == null) { } else { var dur = ConvertToFloat(duration.Value); if (dur [0] == 0) { if (dur [1] == 0) { effectLayer.IsBurstEmit = true; } else { effectLayer.EmitDuration = dur [1]; } } else { } } if (rateMin == 1 && forever) { effectLayer.IsBurstEmit = true; } var emitType = modData ["TYPE OF EMITTER"].Value; if (emitType == "Circle") { effectLayer.EmitType = 3; effectLayer.UseRandomCircle = true; float[] maxRadius; if (string.IsNullOrEmpty(modData ["MAX RADIUS"])) { maxRadius = new float[] { 0, 3 }; } else { maxRadius = ConvertToFloat(modData ["MAX RADIUS"].Value.Split(',')); } effectLayer.CircleRadiusMax = maxRadius [1]; if (modData ["MIN RADIUS"].Value == "") { effectLayer.CircleRadiusMin = effectLayer.CircleRadiusMax; } else { effectLayer.CircleRadiusMin = ConvertToFloat(modData ["MIN RADIUS"].Value.Split(',')) [1]; } } else if (emitType == "SphereSurface") { effectLayer.EmitType = 2; effectLayer.Radius = modData ["RADIUS"].AsFloat; effectLayer.DirType = DIRECTION_TYPE.Sphere; } else if (emitType == "Box") { effectLayer.EmitType = 1; var width = modData ["WIDTH_"].AsFloat; var height = modData ["HEIGHT_"].AsFloat; var depth = modData ["DEPTH_"].AsFloat; effectLayer.BoxSize = new Vector3(width, height, depth); } var scaleModData = modData ["SCALE ON LAUNCH"].Value; Debug.Log("scale mod data " + scaleModData); float[] scaleData = new float[] { 0, 1 }; if (scaleModData == "") { } else { scaleData = ConvertToFloat(scaleModData); //Avoid Start Scale 0 if (scaleData [1] == 0) { scaleData [1] = 1; } } var vs = modData ["VISUAL SCALE"].Value; float vscale = 1; if (vs != "") { vscale = Convert.ToSingle(vs); } var scaType = (int)scaleData [0]; if (scaType == 1) { effectLayer.RandomOriScale = true; effectLayer.OriScaleXMin = scaleData [1] * vscale; effectLayer.OriScaleXMax = scaleData [2] * vscale; effectLayer.OriScaleYMin = scaleData [1] * vscale; effectLayer.OriScaleYMax = scaleData [2] * vscale; } else if (scaType == 0) { effectLayer.RandomOriScale = false; effectLayer.OriScaleXMin = effectLayer.OriScaleXMax = scaleData [1] * vscale; effectLayer.OriScaleYMin = effectLayer.OriScaleYMax = scaleData [1] * vscale; } Log.Sys("scaleData is type " + scaType + " vscale " + vscale + " scaleData " + scaleData [1] + " res " + effectLayer.OriScaleXMin); var posx = modData ["POSITIONX"].AsFloat; var posy = modData ["POSITIONY"].AsFloat; var posz = modData ["POSITIONZ"].AsFloat; var pos = modData ["POSITION"]; if (pos != null) { var p = ConvertToFloat(pos.Value); effectLayer.EmitPoint = new Vector3(p [0], p [1], p [2]); } else { effectLayer.EmitPoint = new Vector3(posx, posy, posz); } //Width * Height if (modData ["WIDTH"].Value != "") { var width = ConvertToFloat(modData ["WIDTH"].Value); if ((int)width [0] == 0) { effectLayer.SpriteWidth = width [1]; } } if (modData ["HEIGHT"].Value != "") { var width = ConvertToFloat(modData ["HEIGHT"].Value); if ((int)width [0] == 0) { effectLayer.SpriteHeight = width [1]; } } float[] velocity; if (string.IsNullOrEmpty(modData ["VELOCITY"])) { velocity = new float[] { 0, 15 }; } else { velocity = ConvertToFloat(modData ["VELOCITY"].Value); } var vtype = (int)velocity [0]; if (vtype == 0) { effectLayer.OriSpeed = velocity [1] * velScale; effectLayer.OriVelocityAxis = Vector3.up; } else if (vtype == 1) { effectLayer.OriSpeed = velocity [1] * velScale; effectLayer.SpeedMin = velocity [1] * velScale; effectLayer.SpeedMax = velocity [2] * velScale; effectLayer.IsRandomSpeed = true; effectLayer.OriVelocityAxis = Vector3.up; } if (modData ["ANGLE"].Value != "") { var angle = ConvertToFloat(modData ["ANGLE"].Value); if (angle.Length > 0) { if ((int)angle [0] == 1) { var minDeg = angle [1]; var maxDeg = angle [2]; effectLayer.DirType = DIRECTION_TYPE.Cone; effectLayer.UseRandomDirAngle = true; effectLayer.AngleAroundAxis = (int)minDeg; effectLayer.AngleAroundAxisMax = (int)maxDeg; effectLayer.SpriteType = (int)Xft.STYPE.BILLBOARD_SELF; } else if ((int)(angle [0]) == 0) { var minDeg = angle [1]; if (minDeg > 0) { effectLayer.DirType = DIRECTION_TYPE.Cone; effectLayer.UseRandomDirAngle = false; effectLayer.AngleAroundAxis = (int)0; effectLayer.AngleAroundAxisMax = (int)minDeg; effectLayer.SpriteType = (int)Xft.STYPE.BILLBOARD_SELF; effectLayer.UseRandomDirAngle = true; } } } } }
void OnMouseDown() { GetComponent <AudioSource> ().Play(); indicatorFunction.hasCancelMark = false; StoreTruckClick.hasCancelMark = false; int[] arr = StoreTruckClick.arrayForChosenPath.ToArray(); float[] arr1 = StoreTruckClick.arrayForTruckCap.ToArray(); //Debug.Log ("test time" + StoreTruckClick.numForTime); if (StoreTruckClick.red) { //Node.redAl.Remove (StoreTruckClick.arrayForChosenPath); Node.redAl.RemoveAt(StoreTruckClick.theTruckNum); StoreTruckClick.arrayForChosenPath.Clear(); //Node.redTruckCap.Remove (StoreTruckClick.arrayForTruckCap); Node.redTruckCap.RemoveAt(StoreTruckClick.theTruckNum); StoreTruckClick.arrayForTruckCap.Clear(); Node.redProfitAl.Remove(StoreTruckClick.numForProfit); Node.redTimeAl.Remove(StoreTruckClick.numForTime); gameControll.redProfitTotal -= StoreTruckClick.numForProfit; decimal.Round((decimal)gameControll.redProfitTotal); if (Mathf.Abs(gameControll.redProfitTotal) < 0.01f) { gameControll.redProfitTotal = 0f; } //Debug.Log ("redtime" + gameControll.redTimeTotal); gameControll.redTimeTotal -= StoreTruckClick.numForTime; decimal.Round((decimal)gameControll.redTimeTotal); if (gameControll.redTimeTotal < 0.01f) { gameControll.redTimeTotal = 0f; } panelController.redText.text = gameControll.redProfitTotal.ToString(); panelController.redTime.text = gameControll.redTimeTotal.ToString(); JSONClass details = new JSONClass(); string s = "remove red truck " + StoreTruckClick.theTruckNum; details ["ClickCancelMark"] = s; TheLogger.instance.TakeAction(7, details); } else if (StoreTruckClick.green) { Node.greenAl.RemoveAt(StoreTruckClick.theTruckNum); StoreTruckClick.arrayForChosenPath.Clear(); Node.greenTruckCap.RemoveAt(StoreTruckClick.theTruckNum); StoreTruckClick.arrayForTruckCap.Clear(); Node.greenProfitAl.Remove(StoreTruckClick.numForProfit); Node.greenTimeAl.Remove(StoreTruckClick.numForTime); gameControll.greenProfitTotal -= StoreTruckClick.numForProfit; decimal.Round((decimal)gameControll.greenProfitTotal); if (Mathf.Abs(gameControll.greenProfitTotal) < 0.01f) { gameControll.greenProfitTotal = 0; } //Debug.Log ("greentime" + gameControll.greenTimeTotal); gameControll.greenTimeTotal -= StoreTruckClick.numForTime; decimal.Round((decimal)gameControll.greenTimeTotal); if (gameControll.greenTimeTotal < 0.01f) { gameControll.greenTimeTotal = 0f; } //Debug.Log ("greentime" + gameControll.greenTimeTotal); panelController.greenText.text = gameControll.greenProfitTotal.ToString(); panelController.greenTime.text = gameControll.greenTimeTotal.ToString(); JSONClass details = new JSONClass(); string s = "remove green truck " + StoreTruckClick.theTruckNum; details ["ClickCancelMark"] = s; TheLogger.instance.TakeAction(7, details); } else if (StoreTruckClick.blue) { Node.blueAl.RemoveAt(StoreTruckClick.theTruckNum); StoreTruckClick.arrayForChosenPath.Clear(); Node.blueTruckCap.RemoveAt(StoreTruckClick.theTruckNum); StoreTruckClick.arrayForTruckCap.Clear(); Node.blueProfitAl.Remove(StoreTruckClick.numForProfit); Node.blueTimeAl.Remove(StoreTruckClick.numForTime); gameControll.blueProfitTotal -= StoreTruckClick.numForProfit; decimal.Round((decimal)gameControll.blueProfitTotal); if (Mathf.Abs(gameControll.blueProfitTotal) < 0.01f) { gameControll.blueProfitTotal = 0f; } //Debug.Log ("bluetime" + gameControll.blueTimeTotal); gameControll.blueTimeTotal -= StoreTruckClick.numForTime; decimal.Round((decimal)gameControll.blueTimeTotal); if (gameControll.blueTimeTotal < 0.01f) { gameControll.blueTimeTotal = 0; } //Debug.Log ("bluetime" + gameControll.blueTimeTotal); panelController.blueText.text = gameControll.blueProfitTotal.ToString(); panelController.blueTime.text = gameControll.blueTimeTotal.ToString(); JSONClass details = new JSONClass(); string s = "remove blue truck " + StoreTruckClick.theTruckNum; details ["ClickCancelMark"] = s; TheLogger.instance.TakeAction(7, details); } for (int j = 0; j < arr.Length - 1; j++) { int num1 = arr [j]; int num2 = arr [j + 1]; gameControll.capArray [num1, num2] += (int)arr1 [j]; gameControll.capArray [num2, num1] += (int)arr1 [j]; string capTruck1 = "capPath" + num1.ToString() + num2.ToString(); string capTruck2 = "capPath" + num2.ToString() + num1.ToString(); if (GameObject.Find(capTruck1) != null) { GameObject.Find(capTruck1).GetComponentInChildren <Text> ().text = gameControll.capArray [num1, num2].ToString(); } else if (GameObject.Find(capTruck2) != null) { GameObject.Find(capTruck2).GetComponentInChildren <Text> ().text = gameControll.capArray [num1, num2].ToString(); } string pathString = "pathAnim" + num1.ToString() + num2.ToString(); GameObject obj = GameObject.Find(pathString); // obj.GetComponent<LineRenderer> ().material = Resources.Load<Material> ("Materials/greenAnim") as Material; // obj.GetComponent<LineRenderer> ().SetWidth (0.25f, 0.25f); //string materialName=StoreTruckClick.materialQueue.Dequeue(); obj.GetComponent <LineRenderer> ().startWidth = .15f; obj.GetComponent <LineRenderer>().endWidth = .15f; string truckText1 = "truckCap" + num1.ToString() + num2.ToString(); string truckText2 = "truckCap" + num2.ToString() + num1.ToString(); GameObject truckCap = new GameObject(); if (GameObject.Find(truckText1) != null) { truckCap = GameObject.Find(truckText1); } else if (GameObject.Find(truckText2) != null) { truckCap = GameObject.Find(truckText2); } Text t = truckCap.GetComponent <Text> (); t.enabled = false; removeIndicatorAndPath(num1, num2, StoreTruckClick.red, StoreTruckClick.green, StoreTruckClick.blue); } removeNodeColor(StoreTruckClick.red, StoreTruckClick.green, StoreTruckClick.blue); if (StoreTruckClick.red) { string goName = "redTruckImage" + (gameControll.redTruckNum - 1).ToString(); //string goText = "redTruckText" + gameControll.redTruckNum.ToString (); Destroy(GameObject.Find(goName)); StoreTruckClick.red = false; gameControll.redTruckNum--; } if (StoreTruckClick.green) { string goName = "greenTruckImage" + (gameControll.greenTruckNum - 1).ToString(); //string goText = "redTruckText" + gameControll.redTruckNum.ToString (); Destroy(GameObject.Find(goName)); StoreTruckClick.green = false; gameControll.greenTruckNum--; } if (StoreTruckClick.blue) { string goName = "blueTruckImage" + (gameControll.blueTruckNum - 1).ToString(); //string goText = "redTruckText" + gameControll.redTruckNum.ToString (); Destroy(GameObject.Find(goName)); StoreTruckClick.blue = false; gameControll.blueTruckNum--; } Destroy(this.gameObject); }
public JSONClass Serialize() { JSONClass cls = new JSONClass(); for (int index = 0; index < _keys.Count; index++) { var key = _keys[index]; var value = _values[index]; cls.Add(key, SerializeValue(value)); } return cls; }
/// <summary> /// Initializes a new instance of the <see cref="Score"/> class. /// </summary> /// <param name="data">API JSON data.</param> public Score(JSONClass data) { PopulateFromJson(data); }
private static string GetDefaultBindings() { JSONClass bindings = new JSONClass(); KeyCode[] keys = Globals.instance.keys; InputCommandName[] actionNames = Globals.instance.actions; InputCommand[] actions = new InputCommand[actionNames.Length]; for (int i = 0; i < actionNames.Length; i++) { actions[i] = InputCommand.FromEnum(actionNames[i]); } for (int i = 0; i < keys.Length; i++) { bindings.Add(keys[i].ToString().ToLower(), new JSONData(actions[i].ToString())); } return bindings.ToString(); }
/// <summary> /// Performs the actual deserialization. We do it here so we can abstract it some /// </summary> /// <param name="rType"></param> /// <param name="rValue"></param> /// <returns></returns> private static object DeserializeValue(Type rType, JSONNode rValue) { if (rValue == null) { return(ReflectionHelper.GetDefaultValue(rType)); } else if (rType == typeof(string)) { return(rValue.Value); } else if (rType == typeof(int)) { return(rValue.AsInt); } else if (rType == typeof(float)) { return(rValue.AsFloat); } else if (rType == typeof(bool)) { return(rValue.AsBool); } else if (rType == typeof(Vector2)) { Vector2 lValue = Vector2.zero; lValue = lValue.FromString(rValue.Value); return(lValue); } else if (rType == typeof(Vector3)) { Vector3 lValue = Vector3.zero; lValue = lValue.FromString(rValue.Value); return(lValue); } else if (rType == typeof(Vector4)) { Vector4 lValue = Vector4.zero; lValue = lValue.FromString(rValue.Value); return(lValue); } else if (rType == typeof(Quaternion)) { Quaternion lValue = Quaternion.identity; lValue = lValue.FromString(rValue.Value); return(lValue); } else if (rType == typeof(HumanBodyBones)) { return((HumanBodyBones)rValue.AsInt); } else if (rType == typeof(Transform)) { string lName = rValue.Value; Transform lValue = null; if (lName.Contains(RootObjectID) && RootObject != null) { lName = rValue.Value.Replace(RootObjectID, ""); if (lName.Length > 0 && lName.Substring(0, 1) == "/") { lName = lName.Substring(1); } lValue = (lName.Length == 0 ? RootObject.transform : RootObject.transform.Find(lName)); } else { GameObject lGameObject = GameObject.Find(lName); if (lGameObject != null) { lValue = lGameObject.transform; } } if (lValue == null) { UnityEngine.Debug.LogWarning("ootii.JSONSerializer.DeserializeValue - Transform name '" + lName + "' not found, resulting in null"); return(null); } return(lValue); } else if (rType == typeof(GameObject)) { string lName = rValue.Value; Transform lValue = null; if (lName.Contains(RootObjectID) && RootObject != null) { lName = rValue.Value.Replace(RootObjectID, ""); if (lName.Length > 0 && lName.Substring(0, 1) == "/") { lName = lName.Substring(1); } lValue = (lName.Length == 0 ? RootObject.transform : RootObject.transform.Find(lName)); } else { GameObject lGameObject = GameObject.Find(lName); if (lGameObject != null) { lValue = lGameObject.transform; } } if (lValue == null) { UnityEngine.Debug.LogWarning("ootii.JSONSerializer.DeserializeValue - GameObject name '" + lName + "' not found, resulting in null"); return(null); } return(lValue.gameObject); } else if (ReflectionHelper.IsAssignableFrom(typeof(Component), rType)) { string lName = rValue.Value; Transform lValue = null; if (lName.Contains(RootObjectID) && RootObject != null) { lName = rValue.Value.Replace(RootObjectID, ""); if (lName.Length > 0 && lName.Substring(0, 1) == "/") { lName = lName.Substring(1); } lValue = (lName.Length == 0 ? RootObject.transform : RootObject.transform.Find(lName)); } else { GameObject lGameObject = GameObject.Find(lName); if (lGameObject != null) { lValue = lGameObject.transform; } } if (lValue == null) { UnityEngine.Debug.LogWarning("ootii.JSONSerializer.DeserializeValue - Component name '" + lName + "' not found, resulting in null"); return(null); } return(lValue.gameObject.GetComponent(rType)); } else if (typeof(IList).IsAssignableFrom(rType)) { IList lList = null; Type lItemType = rType; JSONArray lItems = rValue.AsArray; //if (rType.IsGenericType) if (ReflectionHelper.IsGenericType(rType)) { lItemType = rType.GetGenericArguments()[0]; lList = Activator.CreateInstance(rType) as IList; } else if (rType.IsArray) { lItemType = rType.GetElementType(); lList = Array.CreateInstance(lItemType, lItems.Count) as IList; } for (int i = 0; i < lItems.Count; i++) { JSONNode lItem = lItems[i]; object lItemValue = DeserializeValue(lItemType, lItem); if (lList.Count > i) { lList[i] = lItemValue; } else { lList.Add(lItemValue); } } return(lList); } else if (typeof(IDictionary).IsAssignableFrom(rType)) { //if (!rType.IsGenericType) { return null; } if (!ReflectionHelper.IsGenericType(rType)) { return(null); } Type lKeyType = rType.GetGenericArguments()[0]; Type lItemType = rType.GetGenericArguments()[1]; IDictionary lDictionary = Activator.CreateInstance(rType) as IDictionary; JSONArray lItems = rValue.AsArray; for (int i = 0; i < lItems.Count; i++) { JSONNode lItem = lItems[i]; JSONClass lObject = lItem.AsObject; foreach (string lKeyString in lObject.Dictionary.Keys) { object lKeyValue = DeserializeValue(lKeyType, lKeyString); object lItemValue = DeserializeValue(lItemType, lItem[lKeyString]); if (lDictionary.Contains(lKeyValue)) { lDictionary[lKeyValue] = lItemValue; } else { lDictionary.Add(lKeyValue, lItemValue); } } } return(lDictionary); } else if (rType == typeof(AnimationCurve)) { if (rValue.Value.Length > 0) { AnimationCurve lCurve = new AnimationCurve(); string[] lItems = rValue.Value.Split(';'); for (int i = 0; i < lItems.Length; i++) { string[] lElements = lItems[i].Split('|'); if (lElements.Length == 5) { int lIntValue = 0; float lFloatValue = 0f; Keyframe lKey = new Keyframe(); if (float.TryParse(lElements[0], out lFloatValue)) { lKey.time = lFloatValue; } if (float.TryParse(lElements[1], out lFloatValue)) { lKey.value = lFloatValue; } if (int.TryParse(lElements[2], out lIntValue)) { lKey.tangentMode = lIntValue; } if (float.TryParse(lElements[3], out lFloatValue)) { lKey.inTangent = lFloatValue; } if (float.TryParse(lElements[4], out lFloatValue)) { lKey.outTangent = lFloatValue; } lCurve.AddKey(lKey); } } return(lCurve); } } //else if (rType == typeof(AnimationCurve)) //{ // AnimationCurve lCurve = new AnimationCurve(); // JSONArray lItems = rValue.AsArray; // for (int i = 0; i < lItems.Count; i++) // { // object lItem = DeserializeValue(typeof(Keyframe), lItems[i]); // if (lItem is Keyframe) { lCurve.AddKey((Keyframe)lItem); } // } // return lCurve; //} // Activator won't let me create a Keyframe using no constructors. So, // we need this special case else if (rType == typeof(Keyframe)) { Keyframe lKeyframe = new Keyframe(rValue["time"].AsFloat, rValue["value"].AsFloat, rValue["inTangent"].AsFloat, rValue["outTangent"].AsFloat); return(lKeyframe); } // As a default, simply try to deserialize the string return(Deserialize(rValue.ToString())); }
public void Deserialize(JSONClass cls) { if (cls["InputIdentifier"] != null) { InputIdentifier = cls["InputIdentifier"].Value; } if (cls["OutputIdentifier"] != null) { OutputIdentifier = cls["OutputIdentifier"].Value; } }
public Object() : base(new JSONClass()) { c_ = node_ as JSONClass; }
public override void Add(string aKey, JSONNode aItem) { var tmp = new JSONClass(); tmp.Add(aKey, aItem); Set(tmp); }
private Object(JSONClass c) : base(c) { c_ = c; }
private static bool TryParseUpdateInfo(JSONClass response, out UpdateInfo updateInfo) { string status = response["status"]; if (status != "OK") { Log.e("Unexpected response 'status': {0}", status); updateInfo = default(UpdateInfo); return false; } string version = response["version"]; if (version == null) { Log.e("Missing response 'version' string"); updateInfo = default(UpdateInfo); return false; } string url = response["url"]; if (url == null) { Log.e("Missing response 'url' string"); updateInfo = default(UpdateInfo); return false; } string message = response["message"]; if (message == null) { Log.e("Missing response 'message'"); updateInfo = default(UpdateInfo); return false; } updateInfo = new UpdateInfo(version, url, message); return true; }
public static Object Wrap(JSONClass c) { return(new Object(c)); }