Inheritance: JSONNode, IEnumerable
示例#1
0
    public override SimpleJSON.JSONClass GetProperties()
    {
        // return the properties
        SimpleJSON.JSONClass N = base.GetProperties();        // new SimpleJSON.JSONClass();
//		Debug.Log("Matrix floor Get prop:"+N.ToString());
//		SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
        N[JsonUtil.dimensionsKey][JsonUtil.sizeXkey].AsInt = sizeX;
        N[JsonUtil.dimensionsKey][JsonUtil.sizeZkey].AsInt = sizeZ;
        N[plantedArrayKey] = new SimpleJSON.JSONArray();
        for (int i = 0; i < sizeX; i++)
        {
            for (int j = 0; j < sizeZ; j++)
            {
                if (squares[i, j].planted)
                {
                    SimpleJSON.JSONClass planted = new SimpleJSON.JSONClass();
                    planted[posX].AsInt           = i;
                    planted[posZ].AsInt           = j;
                    planted[color]                = JsonUtil.ConvertColorToJson(squares[i, j].targetColor);
                    planted[plantPrefabKey].AsInt = squares[i, j].flowerIndex;
                    N[plantedArrayKey].Add(planted);
                }
            }
        }
        return(N);
    }
    public void VecIn(SpacebrewClient.SpacebrewMessage message)
    {
        Debug.Log("got message");
        Debug.Log(message.valueNode);
        SimpleJSON.JSONArray arr = message.valueNode.AsArray;
        //switching from Z up to Unity's Y up
        prevDir.x = arr[0].AsFloat;
        prevDir.z = arr[1].AsFloat;
        prevDir.y = arr[2].AsFloat;
        if (applyTransform)
        {
            if (!invTransform)
            {
                prevDir = transform.rotation * prevDir;
            }
            else
            {
                prevDir = Quaternion.Inverse(transform.rotation) * prevDir;
            }
        }
        //lets assume sounds happen 1m above the ground
        Plane plane = new Plane(Vector3.up, Vector3.up);
        Ray   ray   = new Ray(transform.position, prevDir);
        float hitAt = 0;

        if (plane.Raycast(ray, out hitAt))
        {
            hit = ray.origin + ray.direction * hitAt;
            onLocalized.Invoke(hit);
        }
    }
示例#3
0
    IEnumerator DownloadList(WebRequest wr)
    {
        while (!wr.POSTcomplete && wr.busy)
        {
            yield return(new WaitForSeconds(0.5f));
        }

        if (wr.data != string.Empty)
        {
            if (SimpleJSON.JSON.Parse(wr.data)["status"].Value == "200")
            {
                var data = SimpleJSON.JSON.Parse(wr.data);

                SimpleJSON.JSONArray j = data["data"].AsArray;
                foreach (SimpleJSON.JSONNode n in j)
                {
                    list.Add(new Shelter(n["id"].Value, n["name"].Value, n["location"].Value, n["longitude"].Value, n["latitude"].Value, n["distance"].Value, n["units"].Value, Instantiate(instanca), n["numbergoingto"].Value, n["numberthere"].Value));
                    //list[n].instance.transform.GetComponent<Location>().latitude = n["latitude"].Value;
                    //list[n].instance.transform.GetComponent<Location>().longitude = n["longitude"].Value;
                }
                foreach (Shelter s in list)
                {
                    s.instance.transform.SetParent(parent.transform);
                    s.instance.transform.localScale = Vector3.one;
                    Text[] text = s.instance.transform.GetComponentsInChildren <Text>();
                    text[0].text = s.name;
                    text[1].text = "Location:" + s.location;
                    text[2].text = "Dis.:" + s.distance + " " + s.units + "\n(" + s.numbergoingto + "/" + s.numberthere + ") on way/in";
                    //s.instance.transform.GetComponent<Location>().latitude = s.latitude;
                    //s.instance.transform.GetComponent<Location>().longitude = s.longitude;
                }
            }
        }
    }
示例#4
0
    public string Deserialize(Stopwatch timer)
    {
        string notes;

        using (System.IO.FileStream inStream = new System.IO.FileStream(jsonPath, System.IO.FileMode.Open))
        {
            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(inStream))
            {
                timer.Start();
                SimpleJSON.JSONNode  node = SimpleJSON.JSONNode.DeserializeBinary(reader);
                SimpleJSON.JSONArray arr  = node["junkList"].AsArray;
                Holder list = new Holder();
                list.junkList = new Junk[arr.Count];

                int i = 0;
                foreach (var n in arr)
                {
                    list.junkList[i] = new Junk();
                    list.junkList[i].SimpleJSONParse(n);
                    i++;
                }

                notes = "Parsed list is " + list.junkList.Length + " entries long, and we parsed " + i + " entries";
            }
        }
        return(notes);
    }
示例#5
0
    public SimpleJSON.JSONArray GetProperties()
    {
        CleanGroups();
        SimpleJSON.JSONArray allGroups = new SimpleJSON.JSONArray();

//		SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
        foreach (List <UserEditableObject> gr in groups)
        {
            SimpleJSON.JSONArray uuids = new SimpleJSON.JSONArray();
//			List<int> uuids = new List<int>();
            foreach (UserEditableObject ueo in gr)
            {
                SimpleJSON.JSONClass n = new SimpleJSON.JSONClass();
//				Debug.Log("adding;"+ueo.GetUuid());
//				n["uuid"] = new SimpleJSON.JSONClass();
                n["uuid"].AsInt = ueo.GetUuid();
                uuids.Add(n);
            }

//			SimpleJSON.JSONClass item = new SimpleJSON.JSONClass();
            allGroups.Add(uuids);
        }

        if (debug)
        {
            Debug.Log("allgrou:" + allGroups.ToString());
        }
        return(allGroups);
    }
示例#6
0
    public void LoadAreaResource()
    {
        PomeloSocket.Inst.Request("area.resourceHandler.loadAreaResource", (data) => {
            Debug.Log("LoadAreaResource:" + data.ToString());
            SimpleJSON.JSONNode jsondata    = SimpleJSON.JSON.Parse(data.ToString());
            SimpleJSON.JSONArray players    = jsondata["players"].AsArray;
            SimpleJSON.JSONArray mobs       = jsondata["mobs"].AsArray;
            SimpleJSON.JSONArray npcs       = jsondata["npcs"].AsArray;
            SimpleJSON.JSONArray items      = jsondata["items"].AsArray;
            SimpleJSON.JSONArray equipments = jsondata["equipments"].AsArray;

            view.SetTotalCount(1 + 1 + (players.Count + mobs.Count) * 16 + npcs.Count + items.Count + equipments.Count);

            LoadJsonResource(() =>
            {
                //预加载所有资源到内存一遍
                view.SetLoadedCount(1);
                view.LoadMap(data["mapName"].ToString());
                view.LoadCharacter(players, "player");
                view.LoadCharacter(mobs, "mob");
                view.LoadNpc(npcs);
                view.LoadItem(items);
                view.LoadEquipment(equipments);
                view.InitObjectPools(mobs, "mob");
                view.InitObjectPools(players, "player");

                Resources.UnloadUnusedAssets();
                System.GC.Collect();

                EnterScene();
            });
        });
    }
示例#7
0
    public virtual void SetAmmoJson(SimpleJSON.JSONArray N)
    {
//		Debug.Log("setamo:"+N.ToString());
        foreach (SimpleJSON.JSONClass item in N.AsArray.Childs)
        {
            GameObject ammoObj = NumberManager.inst.CreateNumber(new Fraction(item[Fraction.numeratorKey].AsFloat, item[Fraction.denominatorKey].AsFloat), Vector3.zero);
            OnCollectNumber(ammoObj.GetComponent <NumberInfo>());
        }
    }
				public static JSONArray convertPersistentListToJSONArray (List<JSONPersistent> list)
				{		
						JSONArray jArray = new JSONArray ();
		
						foreach (JSONPersistent persist in list) {
								jArray.Add (persist.getDataClass ());
						}

						return jArray;
				}
    public override void SetAmmoJson(SimpleJSON.JSONArray N)
    {
//		Debug.Log("setting ammo json:"+N.AsArray.Count);
        foreach (SimpleJSON.JSONClass item in N.AsArray.Childs)
        {
            GameObject ammoObj = NumberManager.inst.CreateNumber(new Fraction(item[Fraction.numeratorKey].AsFloat, item[Fraction.denominatorKey].AsFloat), Vector3.zero);
            OnCollectNumber(ammoObj.GetComponent <NumberInfo>(), N.AsArray.Count);           // just collect N times the first one, since multiblaster multiplies the ammo by 10 when it loads.
            return;
        }
    }
示例#10
0
 public static string[] AsStringArray(JSONArray arrayJson)
 {
     string[] array = new string[arrayJson.Count];
     int index = 0;
     foreach(JSONNode node in arrayJson){
         array[index] = (string)node.ToString();
         index+=1;
     }
     return array;
 }
示例#11
0
    void SetFloorPlantedStates(SimpleJSON.JSONArray PA)
    {
        foreach (SimpleJSON.JSONClass s in PA.AsArray.Childs)
        {
            // The planted square were saved in the properties
            // Iterate through these planted squares and plant them as well as set their color.
//			squares[s[posX],s[posZ]].targetColor = s[color];
            squares[s[posX].AsInt, s[posZ].AsInt].Plant(s[plantPrefabKey].AsInt, JsonUtil.ConvertJsonToColor((SimpleJSON.JSONClass)s[color]));
        }
    }
示例#12
0
    public void WriteJson(SimpleJSON.JSONClass jobj)
    {
        var abPath = path.Replace("/", "_");
        var ls     = new SimpleJSON.JSONArray();

        foreach (var dep in dependency)
        {
            ls.Add(dep.Replace("/", "_"));
        }
        jobj.Add(abPath, ls);
    }
    public SimpleJSON.JSONNode SimpleJSONPopulateNode()
    {
        SimpleJSON.JSONArray arr = new SimpleJSON.JSONArray();

        for (int i = 0; i < junkList.Length; i++)
        {
            arr[i] = junkList[i].SimpleJSONPopulateNode();
        }

        return(arr);
    }
 int GetFirstAvailableClipboardSlot()
 {
     for (int i = 0; i < clipboardSnips.Length; i++)
     {
         SimpleJSON.JSONArray n = clipboardSnips[i];
         if (n == null)
         {
             return(i);
         }
     }
     return(-1);
 }
示例#15
0
 public virtual SimpleJSON.JSONArray GetAmmoJson()
 {
     // (most) gadgets do not serialize their ammo in inventory so this function is needed for them to preserve ammo during level instance loads
     SimpleJSON.JSONArray N = new SimpleJSON.JSONArray();
     foreach (Ammo a in GetAmmo())
     {
         SimpleJSON.JSONClass item = new SimpleJSON.JSONClass();
         item[Fraction.numeratorKey].AsInt   = a.ammoValue.numerator;
         item[Fraction.denominatorKey].AsInt = a.ammoValue.denominator;
         N.Add(item);
     }
     return(N);
 }
				public static List<JSONPersistent> convertJSONArrayToPersistentList (JSONArray jArray, Type persistentType)
				{
						List<JSONPersistent> list = new List<JSONPersistent> ();

						for (int i = 0; i < jArray.Count; i++) {

								JSONPersistent persist = Activator.CreateInstance (persistentType) as JSONPersistent;
								persist.setClassData (jArray [i].AsObject);
								list.Add (persist);
						}

						return list;
				}
    // Helper for the SimpleJSON lib
    public void SimpleJSONParse(SimpleJSON.JSONNode node)
    {
        SimpleJSON.JSONArray arr = node.AsArray;
        junkList = new Junk[arr.Count];
        int i = 0;

        foreach (var n in arr)
        {
            junkList[i] = new Junk();
            junkList[i].SimpleJSONParse(n);
            i++;
        }
    }
示例#18
0
    public void SetProperties(SimpleJSON.JSONArray allGroups)
    {
        ClearGroups();
        UserEditableObject[] allObjs = FindObjectsOfType <UserEditableObject>();
        foreach (SimpleJSON.JSONArray gr in allGroups.AsArray.Childs)
        {
            List <UserEditableObject> ueoGroup = new List <UserEditableObject>();
            foreach (SimpleJSON.JSONNode j in gr)
            {
                int uuid = -1;
                if (j["uuid"] != null)
                {
                    uuid = j["uuid"].AsInt;
                }

                if (debug)
                {
                    Debug.Log("checking for a match of uuid;" + uuid);
                }
                foreach (UserEditableObject u in allObjs)
                {
                    if (u.GetUuid() == uuid)
                    {
                        ueoGroup.Add(u);
                        if (debug)
                        {
                            Debug.Log("Found match!");
                        }
                        break;
                    }
                    else
                    {
//						Debug.Log("sadly, uuid did not match:"+u.GetUuid()+" and "+uuid);
                    }
                }
//				gr.Add(ueoGroup);
            }
            if (debug)
            {
                Debug.Log("ueo count:" + ueoGroup.Count);
            }
            if (ueoGroup.Count > 0)
            {
                groups.Add(ueoGroup);
            }
        }
        if (debug)
        {
            Debug.Log("whew! groups:" + groups.Count);
        }
    }
示例#19
0
    IEnumerator Co_RequestUser(string inUserName, string inUserScore)
    {
        string url = string.Format("{0}/RegistScore.php?name={1}&score={2}", _serverURL, inUserName, inUserScore);

        using (UnityWebRequest www = UnityWebRequest.Get(url))
        {
            yield return(www.Send());

            if (www.isNetworkError)
            {
                Debug.LogError(www.error);
            }
        }

        using (UnityWebRequest www = UnityWebRequest.Get(string.Format("{0}/index.php", _serverURL)))
        {
            yield return(www.Send());

            if (www.isNetworkError)
            {
                Debug.LogError(www.error);
            }
            else
            {
                string data                = www.downloadHandler.text;
                SimpleJSON.JSONNode  jn    = SimpleJSON.JSONNode.Parse(data);
                SimpleJSON.JSONArray array = jn.AsArray;

                List <ServerModel> modelList = new List <ServerModel>();
                for (int i = 0; i < array.Count; i++)
                {
                    modelList.Add(new ServerModel()
                    {
                        name  = array[i]["name"],
                        score = array[i]["score"].AsInt,
                    });
                }

                modelList = modelList.OrderByDescending(x => x.score).ToList();
                for (int i = 0; i < modelList.Count; i++)
                {
                    if (_cells.Length <= i)
                    {
                        break;
                    }

                    _cells[i].Bind(modelList[i]);
                }
            }
        }
    }
    public SimpleJSON.JSONArray SerializeUserEditableObjects(List <UserEditableObject> ueos, SceneSerializationType serializationType = SceneSerializationType.Class)
    {
        WebGLComm.inst.Debug("<color=#09f>Saver:</color>.SerializeUserEditableObjects()");
        SimpleJSON.JSONArray objs = new SimpleJSON.JSONArray();         // Will be a list of objects

        foreach (UserEditableObject ueo in ueos)
        {
            SimpleJSON.JSONClass obj = new SimpleJSON.JSONClass();             // Create a separate json sub-tree of user placed objects, which will be added to the main json after it's populated.
            obj = JsonUtil.GetUeoBaseProps(obj, ueo, serializationType);
            objs.Add(obj);
        }

        return(objs);
    }
    public SimpleJSON.JSONNode SimpleJSONPopulateNode()
    {
        SimpleJSON.JSONNode n = new SimpleJSON.JSONObject();
        n["BitsName"] = BitsName;

        SimpleJSON.JSONArray arr = new SimpleJSON.JSONArray();
        for (int i = 0; i < SomeBits.Length; i++)
        {
            arr[i] = SomeBits[i];
        }
        n["SomeBits"] = arr;

        return(n);
    }
示例#22
0
    public static void SimulateSave()
    {
        var j = new SimpleJSON.JSONArray();

        foreach (var atom in SuperController.singleton.GetAtoms())
        {
            if (!atom.name.Contains("Mirror") && !atom.name.Contains("Glass"))
            {
                continue;
            }

            try
            {
                // atom.GetJSON(true, true, true);
                foreach (var id in atom.GetStorableIDs())
                {
                    var stor = atom.GetStorableByID(id);
                    if (stor.gameObject == null)
                    {
                        throw new NullReferenceException("123");
                    }
                    try
                    {
                        if (stor == null)
                        {
                            throw new Exception("Case 1");
                        }
                        if (stor.enabled == false)
                        {
                            throw new Exception("Case 2");
                        }
                        SuperController.LogMessage("Storage" + atom.name + "/" + stor.name + " (" + stor.storeId + ")");
                        string[] value = stor.GetAllFloatAndColorParamNames().ToArray();
                        SuperController.LogMessage(" -" + string.Join(", ", value));
                        // var x = stor.name;
                        // stor.GetJSON();
                    }
                    catch (Exception se)
                    {
                        SuperController.LogMessage("Error with " + atom.name + "/" + stor.name + ": " + se);
                    }
                }
                // atom.Store(j);
            }
            catch (Exception je)
            {
                SuperController.LogMessage("Error with " + GetHierarchy(atom.gameObject) + " " + atom + ": " + je);
            }
        }
    }
    SimpleJSON.JSONArray GetListOfDeactivatedCubesAsArray()
    {
        int i = 0;

        SimpleJSON.JSONArray ar = new SimpleJSON.JSONArray();
        foreach (DanMeyerCube dmc in cubes)
        {
            if (dmc.cubeActive == false)
            {
                ar.Add(JsonUtil.IntVector3ToString(dmc.indexedPosition));
            }
        }
        return(ar);
    }
示例#24
0
    void Start()
    {
        var proj = new SimpleJSON.JSONArray();
        var n    = new JSONData("item6");

        proj.Add(n);
        n = new JSONData("item18");
        proj.Add(n);
        n = new JSONData("item60");
        proj.Add(n);
        var str = proj.ToString();

        Debug.LogError(str);
        SimpleIAP.GetInstance().LoadProducst(str);
    }
示例#25
0
 public void LoadNpc(SimpleJSON.JSONArray ids)
 {
     if (ids == null || ids.Count == 0)
     {
         return;
     }
     for (int i = 0; i < ids.Count; i++)
     {
         SimpleJSON.JSONNode p = ids[i];
         string filepath       = "npc/" + p.AsInt;
         // Debug.Log(filepath);
         GameObject obj = (GameObject)Instantiate(Resources.Load(filepath));
         SetLoadedCount(1);
         // SceneManager.MoveGameObjectToScene(obj, SceneManager.GetSceneByName("desert"));
     }
 }
示例#26
0
    public void Init(JsonObject data)
    {
        // Debug.Log(data.ToString());
        object mapdata;
        bool   isok = data.TryGetValue("map", out mapdata);

        if (isok)
        {
            JsonObject _mapdata = mapdata as JsonObject;
            DataManager.Inst.mapdata.Clear();
            DataManager.Inst.mapdata.name   = _mapdata["name"].ToString();
            DataManager.Inst.mapdata.width  = Convert.ToInt32(_mapdata["width"]);
            DataManager.Inst.mapdata.height = Convert.ToInt32(_mapdata["height"]);
            DataManager.Inst.mapdata.tileW  = Convert.ToInt32(_mapdata["tileW"]);
            DataManager.Inst.mapdata.tileH  = Convert.ToInt32(_mapdata["tileH"]);

            Debug.Log("Enter Game Area Name: " + DataManager.Inst.mapdata.name);

            SimpleJSON.JSONNode  jsondata  = SimpleJSON.JSON.Parse(_mapdata["weightMap"].ToString());
            SimpleJSON.JSONArray weightmap = jsondata.AsArray;
            for (int i = 0; i < weightmap.Count; i++)
            {
                SimpleJSON.JSONArray collisions = weightmap[i]["collisions"].AsArray;

                WeightMapData _data = new WeightMapData(i, collisions.Count);
                for (int j = 0; j < collisions.Count; j++)
                {
                    CollisionData _col = new CollisionData();
                    _col.start  = collisions[j]["start"].AsInt;
                    _col.length = collisions[j]["length"].AsInt;
                    _data.Add(j, _col);
                }
                DataManager.Inst.mapdata.weightMap.Add(_data);
            }
        }
        Debug.Log("curPlayer Data:" + data["curPlayer"].ToString());
        DataManager.Inst.pomelodata.playerjsondata = data["curPlayer"] as JsonObject;
        DataManager.Inst.playerdata = JsonUtility.FromJson <PlayerData>(DataManager.Inst.pomelodata.playerjsondata.ToString());//DataManager.Inst.InitPlayerData(DataManager.Inst.pomelodata.playerjsondata);


        this.area = new Area(data, DataManager.Inst.mapdata);

        cursorServer = new CursorServer();
        cursorServer.OnMouseExit();
    }
    public void GetCostumeJsonArray()
    {
        SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
//		N["Hats"] = new SimpleJSON.JSONArray();
        N["Hair"]      = new SimpleJSON.JSONArray();
        N["Materials"] = new SimpleJSON.JSONArray();
//		foreach(Transform t in hats){
//			N["Hats"].Add(t.name);
//		}
        foreach (Transform t in hair)
        {
            N["Hair"].Add(t.name);
        }
        foreach (Material m in allMaterials)
        {
            N["Materials"].Add(m.name);
        }
        // commented Debug.Log(N.ToString());
    }
    public void PasteDraggingParentFromClipboard(int i)
    {
        // Ireally, really don't like how I'm accessing a bunch of LevelBuilder objects here like draggingparent and current piece and draggingpicesesbucket. Oh well.
        //		AudioManager.inst.LevelBuilderPreview();
        AudioManager.inst.PlayInventoryClose();
        // User saved smething on clipboard and now wants to instantiate it.
        if (clipboardSnips[i] == null)
        {
//			Debug.Log("<color=#f00>No snip </color>at i:"+i);
            return;
        }
        SimpleJSON.JSONArray      clipboardArray         = clipboardSnips[i];
        List <GameObject>         draggingPiecesToCreate = new List <GameObject>();
        List <UserEditableObject> ueos = new List <UserEditableObject>();

        foreach (SimpleJSON.JSONClass n in clipboardArray)
        {
            // Create the objects from string memory.
            UserEditableObject ueo = LevelBuilderObjectManager.inst.PlaceObject(n, SceneSerializationType.Class);
            ueos.Add(ueo);             // for group manager
            // Note that this creates the peice wherever it was in world space when the copy was made, so we'll reposition the items to current mouse pos after creation.
            draggingPiecesToCreate.Add(ueo.gameObject);
        }
        LevelBuilder.inst.draggingParent = LevelBuilder.inst.MakeDraggingParentWithPieces(draggingPiecesToCreate);         // group these objects together for selection nd select them
        RaycastHit hit = new RaycastHit();

        if (Physics.Raycast(LevelBuilder.inst.camSky.transform.position, LevelBuilder.inst.camSky.transform.forward, out hit))
        {
            //			Debug.Log("hitp:"+hit.point);
            LevelBuilder.inst.draggingParent.transform.position = hit.point;             // reposition drag parent
            LevelBuilder.inst.currentPiece = LevelBuilder.inst.draggingParent;
            LevelBuilder.inst.BeginMovingObject();
            LevelBuilderGroupManager.inst.MakeGroup(ueos);
            //			PlaceContextMenu(draggingParent);
        }
        else
        {
            //			Debug.Log("nohit");
            //			Finisheddr
            Destroy(LevelBuilder.inst.draggingParent);
        }
    }
 void SaveClipboardToServer()
 {
     SimpleJSON.JSONClass N = new SimpleJSON.JSONClass();
     N[clipboardKey] = new SimpleJSON.JSONArray();
     for (int i = 0; i < 9; i++)
     {
         if (clipboardSnips[i] != null)
         {
             SimpleJSON.JSONClass item = new SimpleJSON.JSONClass();
             item[clipboardIndexKey].AsInt = i;
             item[clipboardJsonKey]        = clipboardSnips[i];
             N[clipboardKey].Add(item);
         }
     }
             #if UNITY_EDITOR
     PlayerPrefs.SetString("Clipboard", N.ToString());
             #else
     WebGLComm.inst.SaveClipboard(N.ToString());
             #endif
 }
示例#30
0
    public void LoadEquipment(SimpleJSON.JSONArray ids)
    {
        if (ids == null || ids.Count == 0)
        {
            return;
        }
        var items = DataApi.Inst.equipment.All();

        for (int i = 0; i < ids.Count; i++)
        {
            SimpleJSON.JSONNode p    = ids[i];
            JsonObject          item = items[p.ToString()] as JsonObject;

            string filepath = "equipment/item_" + Convert.ToInt32(item["imgId"]);
            Debug.Log(filepath);
            //GameObject obj = (GameObject)Instantiate(Resources.Load(filepath));
            //SetLoadedCount(1);
            //SceneManager.MoveGameObjectToScene(obj, SceneManager.GetSceneByName("desert"));
        }
    }
    public string Deserialize(Stopwatch timer)
    {
        timer.Start();

        SimpleJSON.JSONNode node = SimpleJSON.JSON.Parse(jsonText);
        Holder list = new Holder();

        SimpleJSON.JSONArray arr = node["junkList"].AsArray;
        list.junkList = new Junk[arr.Count];

        int i = 0;

        foreach (var n in arr)
        {
            list.junkList[i] = new Junk();
            list.junkList[i].SimpleJSONParse(n);
            i++;
        }

        return("Parsed list is " + list.junkList.Length + " entries long, and we parsed " + i + " entries");
    }
示例#32
0
    /// <summary>
    /// 其它对象移动事件
    /// </summary>
    private void onMove()
    {
        PomeloSocket.Inst.On("onMove", (data) =>
        {
            Debug.Log("onMove:" + data);
            if (App.Inst.getArea() == null)
            {
                return;
            }
            var character = App.Inst.getArea().getEntity(Convert.ToInt32(data["entityId"]));
            if (character == null)
            {
                Debug.Log("no find Character " + data["entityId"]);
                return;
            }

            SimpleJSON.JSONNode jsondata = SimpleJSON.JSON.Parse(data["path"].ToString().Trim());
            SimpleJSON.JSONArray array   = jsondata.AsArray;
            if (array == null)
            {
                return;
            }
            List <Vector2Int> paths = new List <Vector2Int>(array.Count);

            for (int i = 0; i < array.Count; i++)
            {
                paths.Add(new Vector2Int(array[i]["x"].AsInt, array[i]["y"].AsInt));
            }

            var sprite  = character.getSprite();
            bool isleft = paths[0].x > paths[1].x;
            sprite.setDirection(isleft);

            var totalDistance = Utils.totalDistance(paths);
            //矫正延迟后的速度
            var needTime = Mathf.Floor(totalDistance / sprite.getSpeed() * 1000 - App.Inst.getDelayTime());
            var speed    = totalDistance / needTime * 1000;
            sprite.movePath(paths, speed);
        });
    }
示例#33
0
    //IEnumerator LoadAsyncScene()
    //{
    //    AsyncOperation asyncload = SceneManager.LoadSceneAsync("desert", LoadSceneMode.Additive);
    //    while (!asyncload.isDone)
    //    {
    //        yield return new WaitForEndOfFrame();
    //    }
    //}

    //private void onLoadingComplete(Scene scene, LoadSceneMode mode)
    //{
    //    Debug.Log("OnSceneLoaded: " + scene.name);
    //    Debug.Log(mode);
    //    SceneManager.sceneLoaded -= onLoadingComplete;

    //    //AppFacade.Instance.SendNotification(LoadingNotify.Open, true);

    //}


    public void InitObjectPools(SimpleJSON.JSONArray ids, string types)
    {
        if (ids == null || ids.Count == 0)
        {
            return;
        }

        var of = new ObjectPoolFactory();

        for (int i = 0; i < ids.Count; i++)
        {
            SimpleJSON.JSONNode p = ids[i];
            int kindId            = p.AsInt;

            string poolname = Utils.getPoolName(kindId, types);
            var    pool     = App.Inst.getObjectPoolManage().getPool(poolname);
            if (pool == null)
            {
                of.createPools(kindId, types);
            }
        }
    }
示例#34
0
        public static void DeserializeComponents(JSONArray components, GameObject obj)
        {
            foreach (JSONNode node in components.Childs)
            {
                string clsName = node["_meta_cls"];
                Type t = Type.GetType("AU." + clsName);
                IJSONSerializable s = obj.AddComponent(t) as IJSONSerializable;

                s.OnDeserialize(node);
            }
        }
示例#35
0
        /*
         * {
                "type": "group_info", //标记
                "group": //group 信息
                 {
                    "member":
                    [//成员
                        {
                            "uid": ""//用户id
                        },
                        ...
                    ],
                    "vid": "", //场馆id
                    "name": "",//..名字
                    "address": "",//..地址
                    "time": "",//..时间
                    "latitude": "",//..经度
                    "longtitude": "",//..纬度
                    "state": "",//..状态 3种状态 0 是未预订 2是预订 1是投票状态
                    "max": ""//..最大成员数 默认10
                }
            }
         */
        public string GetExtJson(string groupID)
        {
            Monitor.Enter(userGroupDict);
            try
            {
                SportMatchGroup group = groupList.Find(a => { return a.groupID == groupID; });
                Venue venue = group.venue;

                JSONClass jc = new JSONClass();
                jc.Add("type", new JSONData("group_info"));
                JSONClass jc_1 = new JSONClass();
                JSONArray ja_1_1 = new JSONArray();
                var itr = userGroupDict.GetEnumerator();
                while (itr.MoveNext())
                {
                    string groupid = itr.Current.Value;
                    if (groupid != groupID)
                        continue;
                    string uuid = itr.Current.Key;
                    JSONClass jc_1_1_i = new JSONClass();
                    jc_1_1_i.Add("uid", new JSONData(uuid));
                    ja_1_1.Add(jc_1_1_i);
                }
                jc_1.Add("member", ja_1_1);
                if (venue == null)
                {
                    jc_1.Add("vid", new JSONData(""));
                    jc_1.Add("name", new JSONData(""));
                    jc_1.Add("address", new JSONData(""));
                    jc_1.Add("time", new JSONData(""));
                    jc_1.Add("latitude", new JSONData(""));
                    jc_1.Add("longtitude", new JSONData(""));
                    jc_1.Add("state", new JSONData(0));
                }
                else
                {
                    jc_1.Add("vid", new JSONData(venue.id));
                    jc_1.Add("name", new JSONData(venue.name));
                    jc_1.Add("address", new JSONData(venue.address));
                    jc_1.Add("time", new JSONData(venue.time));
                    jc_1.Add("latitude", new JSONData(venue.latitude));
                    jc_1.Add("longtitude", new JSONData(venue.longitude));
                    jc_1.Add("state", new JSONData(2));
                }
                jc_1.Add("max", new JSONData(10));
                jc.Add("group", jc_1);
                return jc.ToJSON(0);
            }
            finally
            {
                Monitor.Exit(userGroupDict);
            }
        }
示例#36
0
		public override void Add (JSONNode aItem)
		{
			var tmp = new JSONArray ();
			tmp.Add (aItem);
			Set (tmp);
		}
示例#37
0
		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);
			}
			}
		}
示例#38
0
        private string ConvertListToJson(List<String> list)
        {
            if (list == null) {
                return null;
            }

            var jsonArray = new JSONArray ();

            foreach (var listItem in list) {
                jsonArray.Add (new JSONData (listItem));
            }

            return jsonArray.ToString ();
        }
示例#39
0
		public override JSONNode this [int aIndex]
		{
			get {
				return new JSONLazyCreator (this);
			}
			set {
				var tmp = new JSONArray ();
				tmp.Add (value);
				Set (tmp);
			}
		}
 //Helper function that gets a keymap from a JSON array (assumed to be 2D array of strings)
 public static List<string[]> getKeyMapStringArraysFromKeyMapJSON(JSONArray keyMap)
 {
     JSONArray keysJSON = keyMap[0].AsArray;
     JSONArray commandsJSON = keyMap[1].AsArray;
     string[] keys = new string[keysJSON.Count];
     for (int i = 0; i < keysJSON.Count; i++)
         keys[i] = keysJSON[i];
     string[] commands = new string[commandsJSON.Count];
     for (int i = 0; i < commandsJSON.Count; i++)
         commands[i] = commandsJSON[i];
     List<string[]> output = new List<string[]>();
     output.Add(keys);
     output.Add(commands);
     return output;
 }
示例#41
0
        /*
         *{
                "target_type":"users",     // users 给用户发消息。chatgroups 给群发消息,chatrooms 给聊天室发消息
                "target":["testb","testc"], // 注意这里需要用数组,数组长度建议不大于20,即使只有
                                            // 一个用户u1或者群组,也要用数组形式 ['u1'],给用户发
                                            // 送时数组元素是用户名,给群组发送时数组元素是groupid
                "msg":{  //消息内容
                    "type":"txt",  // 消息类型,不局限与文本消息。任何消息类型都可以加扩展消息
                    "msg":"消息"    // 随意传入都可以
                },
                "from":"testa",  //表示消息发送者。无此字段Server会默认设置为"from":"admin",有from字段但值为空串("")时请求失败
                "ext":{   //扩展属性,由APP自己定义。可以没有这个字段,但是如果有,值不能是"ext:null"这种形式,否则出错
                    "attr1":"v1"   // 消息的扩展内容,可以增加字段,扩展消息主要解析不分。
                }
            }
         */
        public string SendMessage(string targetType, string[] targetID, string msgType, string msgText, string fromUUID, string extJson = null)
        {
            JSONClass jc = new JSONClass();
            jc.Add("target_type", JD(targetType));
            JSONArray ja = new JSONArray();
            foreach (string tID in targetID)
            {
                ja.Add(JD(tID));
            }
            jc.Add("target", ja);
            JSONClass jmsg = new JSONClass();
            jmsg.Add("type", JD(msgType));
            jmsg.Add("msg", JD(msgText));
            jc.Add("msg", jmsg);
            if (fromUUID != null)
                jc.Add("from", fromUUID);
            if (extJson != null)
                jc.Add("ext", JSON.Parse(extJson));

            string postData = jc.ToJSON(0);
            string result = ReqUrl(easeMobUrl + "messages", "POST", postData, token);
            return result;
        }
        private static void Save(Assembly asm)
        {
            var mod = GetModFromAssembly(asm);
              if (mod == null)
              {
            throw new InvalidOperationException("Cannot save configuration: "
              + "Failed to determine mod");
              }

              var modName = mod.Mod.Name;

              if (!configs.ContainsKey(modName))
              {
            configs.Add(modName, new Dictionary<string, Value>());
              }

              var config = configs[modName];
              var keys = config.Keys.ToArray();
              var root = new JSONArray();
              for (int i = 0; i < keys.Length; i++)
              {
            var obj = new JSONClass();
            obj["key"] = keys[i];
            obj["value"]["type"] = config[keys[i]].type;
            obj["value"]["value"] = config[keys[i]].value.ToString();
            root[i] = obj;
              }

              var json = root.ToJSON(0);
              var path = Application.dataPath + "/Mods/Config/" + modName + ".json";

              Directory.CreateDirectory(Application.dataPath + "/Mods/Config/");

              using (var writer = new StreamWriter(File.Open(path, FileMode.Create)))
              {
            writer.Write(json);
              }
        }
示例#43
0
        public static JSONArray SerializeComponents(GameObject obj)
        {
            JSONArray a = new JSONArray();
            IJSONSerializable[] serializables = obj.GetInterfaces<IJSONSerializable>().ToArray();
            foreach (IJSONSerializable hs in serializables)
            {
                JSONClass hsNode = new JSONClass();

                hs.OnSerialize(hsNode);

                hsNode["_meta_cls"] = hs.GetType().Name;

                a.Add(hsNode);
            }
            return a;
        }
				/// <summary>
				/// replaces the existing JSONArray
				/// </summary>
				/// <param name="newArray">New array.</param>
				public void setJSONArray (JSONArray newArray)
				{
						persistentArray = newArray;
				}
示例#45
0
文件: Game1.cs 项目: Xivid/RhythmHit
        protected void StartGame()
        {
            mRoadY[0] = 0;
            mRoadY[1] = -1 * mRoad.Height;

            mScore = 0;
            mHazardsPerfect = mHazardsGood = mHazardsMiss = 0;
            mHazardsCombo = 0;
            mVelocityY = (1 + difficulty) * 300; // velocity increases with difficulty
            mCurrentRoadIndex = 0; // the scroll starts from the first road
            mHazards.Clear();

            // Read beatmap of the chosen music with the chosen difficulty
            String musicname = musicNames[musicChosen];
            beatmap = BeatmapJson[musicChosen];
            switch (difficulty)
            {
                case 0:
                    hitObjects = beatmap["GameObject"]["Easy"].AsArray;
                    break;
                case 1:
                    hitObjects = beatmap["GameObject"]["Normal"].AsArray;
                    break;
                case 2:
                    hitObjects = beatmap["GameObject"]["Hard"].AsArray;
                    break;
                default:
                    return;
            }

            try
            {
                hitSE = Content.Load<SoundEffect>("Music/" + musicname + "/hit");
            }
            catch (Exception e) // load fail
            {
                this.Exit();
            }

            mCurrentState = State.Running;

            noteCounter = 0;
            nowObject = hitObjects[0].AsArray;

            MediaPlayer.Play(mMusics[musicChosen]);
            MediaPlayer.Volume = 1.0f; // reset the volume to 1.0f, in case the player starts the game when the preview music is fading in or fading out
        }
示例#46
0
文件: Game1.cs 项目: Xivid/RhythmHit
 private void UpdateHazards()
 {
     if (nowObject[1].AsDouble <= MediaPlayer.PlayPosition.TotalSeconds + ((mCarPosition.Y + mHazard.Height * 0.7) / mVelocityY))
     { // time for a new hazard to enter the stage
         if (noteCounter < hitObjects.Count)
         {
             AddHazard();
             noteCounter++;
             if (noteCounter == hitObjects.Count)
                 return;
             nowObject = hitObjects[noteCounter].AsArray; // nowObject = next note
         }
     }
 }
    protected IEnumerator SetListStart()
    {
        string aLink;
        WWW aWWW;
        string aResponse;
        SimpleJSON.JSONClass aJsonClass;

        aLink = "https://goo.gl/...ID...";
        aWWW = new WWW(aLink);
        yield return aWWW;

        if (aWWW.error == null)
        {
            aResponse = aWWW.text;
        /*
         * Hard-coded JSON data feed example
         *
         * {"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended","id":{"$t":"https://spreadsheets.google.com/feeds/list/.../od6/public/values"},"updated":{"$t":"2015-07-12T00:00:00.000Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"Sheet1"},"link":[{"rel":"alternate","type":"application/atom+xml","href":"https://docs.google.com/spreadsheets/d/.../pubhtml"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/.../od6/public/values"},{"rel":"http://schemas.google.com/g/2005#post","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/.../od6/public/values"},{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/.../od6/public/values?alt\u003djson"}],"author":[{"name":{"$t":"spreadsheet2app"},"email":{"$t":"*****@*****.**"}}],"openSearch$totalResults":{"$t":"2"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"https://spreadsheets.google.com/feeds/list/.../od6/public/values/cokwr"},"updated":{"$t":"2015-07-12T00:00:00.000Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"1"},"content":{"type":"text","$t":"title: Item One T, description: Item One D, imagelink: http://drive.google.com/uc?export\u003dview\u0026id\u003d__ID__\u0026, lastupdated: 7/13/2015"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/.../od6/public/values/cokwr"}],"gsx$id":{"$t":"1"},"gsx$title":{"$t":"Item One T"},"gsx$description":{"$t":"Item One D"},"gsx$imagelink":{"$t":"http://drive.google.com/uc?export\u003dview\u0026id\u003d__ID__\u0026"},"gsx$lastupdated":{"$t":"7/13/2015"}},{"id":{"$t":"https://spreadsheets.google.com/feeds/list/.../od6/public/values/cpzh4"},"updated":{"$t":"2015-07-12T00:00:00.000Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#list"}],"title":{"type":"text","$t":"2"},"content":{"type":"text","$t":"title: Item Two T, description: Item Two D, imagelink: http://drive.google.com/uc?export\u003dview\u0026id\u003d__ID__\u0026, lastupdated: 7/13/2015"},"link":[{"rel":"self","type":"application/atom+xml","href":"https://spreadsheets.google.com/feeds/list/.../od6/public/values/cpzh4"}],"gsx$id":{"$t":"2"},"gsx$title":{"$t":"Item Two T"},"gsx$description":{"$t":"Item Two D"},"gsx$imagelink":{"$t":"http://drive.google.com/uc?export\u003dview\u0026id\u003d__ID__\u0026"},"gsx$lastupdated":{"$t":"7/13/2015"}}]}}
         *
         */
            aJsonClass = (SimpleJSON.JSONNode.Parse (""+aResponse) as SimpleJSON.JSONClass);
            MyList = aJsonClass["feed"]["entry"].AsArray;
            SetButtons();
        }
        else
        {
            aResponse = aWWW.error;
            MyList = (SimpleJSON.JSONNode.Parse ("[]") as SimpleJSON.JSONArray);
        }
        aWWW.Dispose();
        yield return null;
    }
示例#48
0
        public static void Serialize(JSONClass jc, object obj, bool serializeStatic = false)
        {
            foreach (FieldInfo mi in obj.GetType().GetFields())
            {
                if (mi.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length > 0)
                    continue;

                if (!serializeStatic && mi.IsStatic)
                    continue;

                if (mi.FieldType.IsArray)
                {
                    IEnumerable arrobjs = (IEnumerable)mi.GetValue(obj);

                    JSONArray arr = new JSONArray();

                    if (typeof(IJSONSerializable).IsAssignableFrom(mi.FieldType.GetElementType()))
                    {
                        foreach (object aobj in arrobjs)
                        {
                            JSONClass cls = new JSONClass();
                            ((IJSONSerializable)aobj).OnSerialize(cls);
                            arr.Add(cls);
                        }
                    }
                    else
                    {
                        if (mi.FieldType.GetElementType() == typeof(GameObject))
                        {
                            foreach (object aobj in arrobjs)
                            {
                                arr.Add(AssetUtility.GetAssetPath((GameObject)aobj));
                            }
                        }
                        else
                        {
                            foreach (object aobj in arrobjs)
                            {
                                arr.Add(aobj.ToString());
                            }
                        }
                    }
                    jc[mi.Name] = arr;

                }
                else
                {
                    if (typeof(IJSONSerializable).IsAssignableFrom(mi.FieldType))
                    {
                        JSONClass cls = new JSONClass();
                        (mi.GetValue(obj) as IJSONSerializable).OnSerialize(cls);
                        jc[mi.Name] = cls;
                    }
                    else
                    {
                        if (mi.FieldType == typeof(GameObject))
                        {
                            jc[mi.Name] = AssetUtility.GetAssetPath((GameObject)mi.GetValue(obj));
                        }
                        else if (mi.FieldType == typeof(Color))
                        {
                            Color c = (Color)mi.GetValue(obj);
                            jc[mi.Name] = SerializeColor(c);
                        }
                        else if (mi.FieldType == typeof(Vector4))
                        {
                            Vector4 c = (Vector4)mi.GetValue(obj);
                            jc[mi.Name] = SerializeVector4(c);
                        }
                        else if (mi.FieldType == typeof(Vector3))
                        {
                            Vector3 c = (Vector3)mi.GetValue(obj);
                            jc[mi.Name] = SerializeVector3(c);
                        }
                        else if (mi.FieldType == typeof(Vector2))
                        {
                            Vector2 c = (Vector2)mi.GetValue(obj);
                            jc[mi.Name] = SerializeVector2(c);
                        }
                        else if (mi.FieldType == typeof(TimeSpan))
                        {
                            jc[mi.Name] = ((TimeSpan)mi.GetValue(obj)).ToString();
                        }
                        else if(mi.FieldType.IsEnum)
                        {
                            Enum v = (Enum)mi.GetValue(obj);
                            jc[mi.Name] = string.Format("{0} {1}", v.GetType().Name, v.ToString());
                        }
                        else
                        {
                            object v = mi.GetValue(obj);
                            if (mi.FieldType == typeof(string))
                                v = "";

                            if (v != null)
                                jc[mi.Name] = mi.GetValue(obj).ToString();
                            else
                                Debug.LogError("[JSONSerialization] Cannot save field: " + mi.Name + " due to its (null)");
                        }
                    }
                }
            }
        }