GetField() публичный Метод

public GetField ( string name ) : JSONObject,
name string
Результат JSONObject,
 public MovementDown(JSONObject js) : base()
 {
     _id = (int)js.GetField(js.keys[0]).n;
     _movement = (int)js.GetField(js.keys[1]).n;
     NbTurn = (int)js.GetField("nbTurn").n;
     ApplyReverseEffect = true;
 }
        private static void ProcessMyGameStateResponse(JSONObject jsonData)
        {
            if (jsonData.GetField ("gameStates")) {
                JSONObject gameStateData = jsonData.GetField ("gameStates");

                for (int i = 0; i < gameStateData.list.Count; i++) {
                    JSONObject gameState = gameStateData.list [i];

                    string access = null;
                    if (gameState.HasField ("access")) {
                        access = gameState.GetField ("access").str;
                    }

                    string data = null;
                    if (gameState.HasField ("data")) {
                        data = gameState.GetField ("data").str;
                    }

                    if (access != null && data != null) {
                        if (access.Equals ("private")) {
                            PrivateGameStateData = data;
                            SpilUnityImplementationBase.fireGameStateUpdated ("private");
                        } else if (access.Equals ("public")) {
                            PublicGameStateData = data;
                            SpilUnityImplementationBase.fireGameStateUpdated ("public");
                        }
                    }
                }
            }
        }
	public static bool ParseUnitObject( JSONObject _UnitNode , 
										ref string _UnitName ,
										ref string _PrefabName ,
										ref Vector3 _InitPosition ,
										ref Quaternion _InitQuaternion )
	{
		if( true == _UnitNode.HasField( "name" ) && 
			true == _UnitNode.HasField( "prefabName" ) 
			)
		{
			
			_UnitName = _UnitNode.GetField( "name" ).str ;
			
			Debug.Log( "JSonParseUtility01:ParseUnitObject() _UnitName=" + _UnitName) ;
			
			_PrefabName = _UnitNode.GetField( "prefabName" ).str ;
			
			if( true == _UnitNode.HasField( "position3D" )  )
			{
				JSONObject positione3DNode = _UnitNode.GetField( "position3D" ) ;
				ParsePosition( positione3DNode , 
							   ref _InitPosition ) ;
			}
			
			if( true == _UnitNode.HasField( "orientationEuler" ) )
			{
				JSONObject orientationNode = _UnitNode.GetField( "orientationEuler" ) ;
				ParseQuaternion( orientationNode , 
								 ref _InitQuaternion ) ;					
			}	
			return true ;
		}
		return false ;
	}	
Пример #4
0
 public virtual void InitializeFromView(JSONObject view)
 {
     Name = view.GetField("name").ToString();
     InstanceId = Convert.ToInt32(view.GetField("id").ToString());
     transform.position = HelperMethods.PositionFromJSONArray(view.GetField("position"));
     Prefab = view.GetField("prefab").ToString();
 }
Пример #5
0
 // Network call completed
 private void callback(JSONObject result) {
     if (final == null) {
         // Create Result container
         final = new SuperCookResult();
         final.total_can_make_right_now = int.Parse(result.GetField("total_can_make_right_now").ToString());
         final.results = new List<SuperCookRecipe>();
     }
     // Convert results
     JSONArray arr = JSON.Parse(result.GetField("results").ToString()).AsArray;
     foreach (JSONNode jn in arr) {
         SuperCookRecipe scRecipe = new SuperCookRecipe();
         scRecipe.title = jn["title"];
         scRecipe.url = jn["url"];
         scRecipe.uses = jn["uses"];
         scRecipe.id = jn["id"].AsInt;
         final.results.Add(scRecipe);
     }
     if (final.results.Count >= final.total_can_make_right_now)
         finished(final);
     else
     {
         skip += 40;
         getRecipes(ingredients, finished);
     }
 }
Пример #6
0
    public WorldObject InstantiateObject(JSONObject view)
    {
        var prefabName = view.GetField("prefab").ToString();
        var instanceId = Convert.ToInt32(view.GetField("id").ToString());

        var newObject = TryGetPrefab(prefabName);

        if (newObject == null)
        {
            var prefab = Resources.Load("prefabs/" + prefabName);
            if (prefab == null)
            {
                return null;
            }
            var obj = (GameObject)Instantiate(prefab, new Vector3(), Quaternion.identity);
            newObject = obj.GetComponent<WorldObject>();
        }

        newObject.InitializeFromView(view);
        AddObject(newObject, prefabName);
        newObject.transform.parent = transform;

        if (!_entities.ContainsKey(instanceId))
        {
            _entities.Add(instanceId, newObject);
        }

        return newObject;
    }
Пример #7
0
    public static JSONAble UnSerialize(JSONObject jsonObject)
    {
        JSONAble r = null;

        if (jsonObject.HasField("_class") && jsonObject.HasField("_data"))
        {
            string c = jsonObject.GetField("_class").str;
            Type t = Type.GetType(c);
            if (t.IsSubclassOf(typeof(JSONAble)))
            {
                if (t.IsSubclassOf(typeof(ScriptableObject)))
                {
                    r = ScriptableObject.CreateInstance(t) as JSONAble;
                    r.fromJSONObject(jsonObject.GetField("_data"));
                }
            }
        }
        else if (jsonObject.IsArray)
        {
            r = ScriptableObject.CreateInstance<IsoUnityCollectionType>();
            r.fromJSONObject(jsonObject);
        }
        else if (jsonObject.IsString || jsonObject.IsNumber || jsonObject.IsBool)
        {
            r = ScriptableObject.CreateInstance<IsoUnityBasicType>();
            r.fromJSONObject(jsonObject);
        }

        return r;
    }
Пример #8
0
 public HealUp(JSONObject js) : base()
 {
     _id = (int)js.GetField(js.keys[0]).n;
     _heal = (int)js.GetField(js.keys[1]).n;
     NbTurn = (int)js.GetField("nbTurn").n;
     ApplyReverseEffect = true;
 }
Пример #9
0
 void parseData(string data)
 {
     JSONObject json = new JSONObject (data);
     string action = json.GetField ("action").str;
     print(action + "parse data" + data);
     JSONObject pos = json.GetField("position");
     Single pX = Convert.ToSingle (pos.GetField ("X").str);
     Single pY = Convert.ToSingle (pos.GetField ("Y").str);
     Single pZ = Convert.ToSingle (pos.GetField ("Z").str);
     Vector3 position = new Vector3 (pX, pY, pZ);
     print ("new vector = x-" + pos.GetField ("X").str + " y-" + pos.GetField ("Y").str);
     JSONObject rot = json.GetField("rotation");
     Single rX = Convert.ToSingle (rot.GetField ("X").str);
     Single rY = Convert.ToSingle (rot.GetField ("Y").str);
     Single rZ = Convert.ToSingle (rot.GetField ("Z").str);
     Single rW = Convert.ToSingle (rot.GetField ("W").str);
     Quaternion rotation = new Quaternion (rX, rY, rZ, rW);
     switch (action) {
         case "start":
             this.id = json.GetField ("id").str;
             createPlayer ();
             break;
         case "newPlayer":
             createNewClient (json.GetField ("id").str, position, rotation);
             break;
         case "move":
             moveClient (json.GetField ("id").str, position, rotation);
             break;
     }
 }
Пример #10
0
    public void shootRope(JSONObject rope)
    {
        GameObject.Find ("JumpButton").GetComponent<JumpButtonController> ().currentControl = "rope";

        hinge.enabled = true;
        line.enabled = true;
        playerHinge.enabled = true;

        RaycastHit2D hit = Physics2D.Raycast(ropeInitialTransform.position,new Vector2(rope.GetField("shootVectorX").f,rope.GetField("shootVectorY").f));

        if(hit.collider.tag == "Ground"){

            line.SetVertexCount(2);
            line.SetPosition(0,new Vector3(hit.point.x,hit.point.y,-10));
            line.SetPosition(1,bodyTransform.position);

            hinge.connectedBody = hit.collider.GetComponent<Rigidbody2D>();

            //접착지점에 게임 오브젝트 생성.
            hitPosition.transform.position = hit.point;
            hitPosition.transform.SetParent(hit.collider.transform);

            hinge.connectedAnchor = hitPosition.transform.localPosition;
            hinge.anchor = new Vector2(new Vector2(bodyTransform.position.x-hit.point.x,bodyTransform.position.y-hit.point.y).magnitude,0);
            //hinge.anchor = new Vector2(hit.point.x - bodyTransform.position.x,hit.point.y-bodyTransform.position.y);

            playerHinge.enabled =true;
            playerHinge.connectedBody = this.GetComponent<Rigidbody2D>();

        }
    }
    public static void initialize() {
        JSON = new JSONObject(GameManager.SongList.text);
        version = JSON.GetField("version").str;
        songList = JSON.GetField("songs").list;

        nextSong();
    }
Пример #12
0
    public void DestroyGround(JSONObject coll)
    {
        V2int c = World2Pixel(coll.GetField("centerX").f, coll.GetField("centerY").f);

        int r = Mathf.RoundToInt(coll.GetField("sizeX").f*widthPixel/widthWorld);

        Debug.Log (c);
        Debug.Log (r);
        int x, y, px, nx, py, ny, d;

        for (x = 0; x <= r; x++)
        {
            d = (int)Mathf.RoundToInt(Mathf.Sqrt(r * r - x * x));

            for (y = 0; y <= d; y++)
            {
                px = c.x + x;
                nx = c.x - x;
                py = c.y + y;
                ny = c.y - y;

                sr.sprite.texture.SetPixel(px, py, transp);
                sr.sprite.texture.SetPixel(nx, py, transp);
                sr.sprite.texture.SetPixel(px, ny, transp);
                sr.sprite.texture.SetPixel(nx, ny, transp);
            }
        }

        sr.sprite.texture.Apply();
        Destroy(GetComponent<PolygonCollider2D>());
        gameObject.AddComponent<PolygonCollider2D>();
    }
Пример #13
0
        public static void Deserialize(this Template template)
        {
            template.Clear();

            var tplJs = new JSONObject(template.JSON);

            // Discard templates without the Operators and Connections fields
            if (tplJs.HasField("Operators") && tplJs.HasField("Connections")) {
                var opsJs = tplJs.GetField("Operators");
                var connsJs = tplJs.GetField("Connections");
                foreach (var opJs in opsJs.list) {
                    var type = System.Type.GetType(opJs["Type"].str);
                    var op = (Operator) System.Activator.CreateInstance(type);
                    op.Deserialize(opJs);
                    template.AddOperator(op, false);
                }
                foreach (var connJs in connsJs.list) {

                    // Discard connections with invalid Operator GUIDs
                    if (!template.Operators.ContainsKey(connJs["From"].str) || !template.Operators.ContainsKey(connJs["To"].str)) {
                        Debug.LogWarning("Discarding connection in template due to an invalid Operator GUID");
                        continue;
                    }

                    Operator fromOp = template.Operators[connJs["From"].str];
                    IOOutlet output = fromOp.GetOutput(connJs["Output"].str);

                    Operator toOp = template.Operators[connJs["To"].str];
                    IOOutlet input = toOp.GetInput(connJs["Input"].str);

                    template.Connect(fromOp, output, toOp, input, false);
                }
            }
        }
Пример #14
0
    public static GameModeDescription CreateFromJson(JSONObject jsonObject)
    {
        if (jsonObject == null)
        {
            Debug.LogWarning("There is no gameMode");
            return new GameModeDescription()
            {
                Mode = "TargetScore",
                TargetScore = 3000,
                Turns = 40
            };
            /*return new GameModeDescription()
            {
                Mode = "TargetChuzzle",
                Turns = 30,
                Amount = 20
            };*/
            /*return new GameModeDescription()
            {
                Mode = "TargetPlace",
                Turns = 30
            };*/
        }

        var desc = new GameModeDescription
        {
            Mode = jsonObject.GetField("Mode").str,
            Turns = (int) jsonObject.GetField("Turns").n,
            TargetScore = jsonObject.HasField("TargetScore") ? (int) jsonObject.GetField("TargetScore").n : 0,
            Amount = jsonObject.HasField("Amount") ? (int) jsonObject.GetField("Amount").n : 0
        };
        return desc;
    }
Пример #15
0
 public RangeDown(JSONObject js) : base()
 {
     _id = (int)js.GetField(js.keys[0]).n;
     _range = (int)js.GetField(js.keys[1]).n;
     NbTurn = (int)js.GetField("nbTurn").n;
     ApplyReverseEffect = true;
 }
 public DamageElement(JSONObject js) : base()
 {
     _id = (int)js.GetField(js.keys[0]).n;
     _min = (int)js.GetField(js.keys[1]).n;
     _max = (int)js.GetField(js.keys[2]).n;
     _element = Element.GetElement((int)js.GetField(js.keys[3]).n);
 }
 public ObstacleCreation(JSONObject js)
 {
     _id = (int)js.GetField("id").n;
     Life = (int)js.GetField("life").n;
     Name = js.GetField("name").str;
     _prefab = (GameObject)Resources.Load("Prefabs/" + Name, typeof(GameObject));
 }
Пример #18
0
 public Vampiric(JSONObject js)
 {
     _id = (int)js.GetField("id").n;
     _min = (int)js.GetField("minValue").n;
     _max = (int)js.GetField("maxValue").n;
     _element = Element.GetElement((int)js.GetField("element").n);
     _vampiricPercentage = (int)js.GetField("vampiricPercentage").n;
 }
	private void DataCallBack (JSONObject result)
	{	
		Debug.Log ("Result " + result.ToString ());
		id.text = "id " + result.GetField ("userid").ToString (); 
		name.text = "name " + result.GetField ("name").ToString ();
		username.text = "username " + result.GetField ("username").ToString ();
		position.text = "position " + result.GetField ("position").ToString ();
	}
Пример #20
0
 public Heal(JSONObject js)
 {
     _id = (int)js.GetField(js.keys[0]).n;
     _min = (int)js.GetField(js.keys[1]).n;
     _max = (int)js.GetField(js.keys[2]).n;
     //déccommenter pour les heals elems
     //_element = Element.GetElement((int)js.GetField(js.keys[3]).n);
 }
 public ProtectionNegativeElement(JSONObject js) : base()
 {
     _id = (int)js.GetField(js.keys[0]).n;
     _protection = (int)js.GetField(js.keys[1]).n;
     _element = Element.GetElement((int)js.GetField(js.keys[2]).n);
     NbTurn = (int)js.GetField("nbTurn").n;
     ApplyReverseEffect = true;
 }
    public TargetSpell(JSONObject js) : base(js)
    {
        Id = (int)js.GetField(js.keys[0]).n;
		AreaId = (int)js.GetField("areaId").n;
		EffectsArea = new Effects(js.GetField("effectsAreaIds"));
		EffectsAreaCrit = new Effects(js.GetField("effectsAreaCritIds"));
		_rangeId = (int)js.GetField("rangeId").n;
    }
	public override void Deserialize(ref JSONObject jsonObject)
	{
		m_HasBeenTriggered = (bool)jsonObject.GetField("m_HasBeenTriggered").b;

		JSONObject jTriggeredArr = jsonObject.GetField("m_Triggered");
		for(int i=0; i < jTriggeredArr.list.Count; ++i)
		{
			m_Triggered.Add(((int)jTriggeredArr.list[i].n));
		}
	}
Пример #24
0
 public static LevelInfo Unserialize(JSONObject jsonObject)
 {
     return new LevelInfo
     {
         BestScore = (int) jsonObject.GetField("BestScore").n,
         NumberOfAttempts = (int) jsonObject.GetField("NumberOfAttempts").n,
         Name = jsonObject.GetField("Name").str,
         IsCompleted = jsonObject.GetField("IsCompleted").b,
     };
 }
Пример #25
0
    public void Unserialize(JSONObject jsonObject)
    {
        Levels.Clear();
        var levelInfo = jsonObject.GetField("LevelInfo");
        foreach (var o in levelInfo.list)
        {
            Levels.Add(LevelInfo.Unserialize(o));
        }

        Lifes = LifeSystem.Unserialize(jsonObject.GetField("Lifes"));
    }
 void NextShape(JSONObject shapeJSON)
 {
     GameObject shape = NewObjectPoolerScript.current.Spawn("Sphere");
     if(!shape) return;
     JSONObject positionJSON = shapeJSON.GetField ("position");
     JSONObject rotationJSON = shapeJSON.GetField ("rotation");
     Debug.Log (rotationJSON);
     shape.transform.LookAt(new Vector3(positionJSON.GetField ("x").n, positionJSON.GetField ("y").n, positionJSON.GetField ("z").n), Vector3.up); // = Quaternion.Euler( rotationJSON.GetField("x").n, rotationJSON.GetField("y").n, 0.0F);
     shape.SetActive(true);
     shape.transform.parent = gameObject.transform;
 }
Пример #27
0
    private UserData CheckPlayer( JSONObject player )
    {
        UserData usr = null;
        if( player != null ){

            usr = new UserData();
            usr.ID = Converter.JsonToString(player.GetField("id").ToString());
            usr.UserName = Converter.JsonToString(player.GetField("name").ToString());
        }

        return usr;
    }
Пример #28
0
	// Deserialize the class from JSON
	override public void Deserialize ( JSONObject input, Component output ) {
		MyClass myClass = output as MyClass;
	
		myClass.myInt = (int) input.GetField ( "myInt" ).n;
		myClass.myFloat = input.GetField ( "myFloat" ).n;
		myClass.myBool = input.GetField ( "myBool" ).b;
		myClass.myString = input.GetField ( "myString" ).str;
		
		// Assign the myObject variable only after all objects have been instantiated
		OFDeserializer.planner.DeferConnection ( ( OFSerializedObject so ) => { 
			myClass.myObject = so.gameObject;
		}, input.GetField ( "myObject" ).str );
	}
 public GroundOnTimeEffect(JSONObject js) :base()
 {
     _id = (int)js.GetField(js.keys[0]).n;
     try
     {
         _effect = SpellManager.GetInstance().GetDirectEffectById((int)js.GetField(js.keys[1]).n);
     }
     catch
     {
         Logger.Error("this is not a ontimeeffect (" + _id + ")");
         Logger.Error("Direct id : " + (int)js.GetField(js.keys[1]).n);
     }
     _nbTurn = (int)js.GetField(js.keys[2]).n;
 }
    // Use this for initialization
    void Start()
    {
        Debug.Log("GameManager Start");
        // Load JSON
        JSONObject j = new JSONObject(spheresJSON.ToString());
        spheres = j.GetField ("spheres").list;
        currentShapeIndex = 0;

        // Game Variables Init
        timer = 0.0F;
        gameAudio = gameObject.GetComponent<AudioSource>();
        gameAudio.clip = (AudioClip)Resources.Load (j.GetField ("song").str);
        songTime = j.GetField("time").n;
    }
Пример #31
0
    protected string getString(JSONObject jsonData, string id)
    {
        string result = "";

        if (!jsonData.HasField(id))
        {
            return(result);
        }

        JSONObject fieldData = jsonData.GetField(id);

        if (fieldData.IsString)
        {
            result = fieldData.str;
        }
        else if (fieldData.IsNumber)
        {
            result = Convert.ToString(fieldData.i);
        }

        return(result);
    }
Пример #32
0
    protected float getFloat(JSONObject jsonData, string id)
    {
        float result = 0;

        if (!jsonData.HasField(id))
        {
            return(result);
        }

        JSONObject fieldData = jsonData.GetField(id);

        if (fieldData.IsString)
        {
            result = (float)Convert.ToDouble(fieldData.str);
        }
        else if (fieldData.IsNumber)
        {
            result = (float)Convert.ToDouble(fieldData.f);
        }

        return(result);
    }
Пример #33
0
    protected int getInt32(JSONObject jsonData, string id)
    {
        int result = 0;

        if (!jsonData.HasField(id))
        {
            return(result);
        }

        JSONObject fieldData = jsonData.GetField(id);

        if (fieldData.IsString)
        {
            result = Convert.ToInt32(fieldData.str);
        }
        else if (fieldData.IsNumber)
        {
            result = Convert.ToInt32(fieldData.i);
        }

        return(result);
    }
    void Start()
    {
        serverController = FindObjectOfType <ServerController>();

        json = new JSONObject();

        path = Application.persistentDataPath + "/settings.json";
        //File.Delete(path);
        if (File.Exists(path))
        {
            string fileContents = File.ReadAllText(path);
            json = new JSONObject(fileContents);

            if (json.HasField(entry))
            {
                string data = json.GetField(entry).str;
                inputField.text = data;
            }
        }

        UpdateField();
    }
Пример #35
0
        public void GetPlugins()
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            Stellarium.GET(Path, "plugins", parameters, (result, error) => {
                if (error != null)
                {
                    Debug.LogError(string.Format("[{0}] {1}", Identifier, error)); return;
                }
                JSONObject json       = new JSONObject(result);
                PluginList pluginList = new PluginList();
                pluginList.plugins    = new Plugins();
                foreach (string pluginName in json.keys)
                {
                    pluginList.plugins.Add(pluginName, JsonUtility.FromJson <Plugin>(json.GetField(pluginName).ToString()));
                }
                if (OnGotPlugins != null)
                {
                    OnGotPlugins(pluginList);
                }
            });
        }
Пример #36
0
    IEnumerator LoadText()
    {
        string url = "";

#if UNITY_EDITOR
        url = MySettings.editorUrl + MySettings.urlText;
#elif UNITY_STANDALONE
        if (File.Exists(Application.dataPath + "/Resources" + MySettings.urlText))
        {
            url = "file://" + Application.dataPath + "/Resources" + MySettings.urlText;
        }
#else
        url = Application.dataPath + MySettings.urlText;
#endif

        WWW www = new WWW(url);
        yield return(www);

        if (www.error != null)
        {
            Debug.Log("ERROR getting " + url + " file!");
            Debug.Log(www.error);
        }
        else
        {
            try
            {
                JSONObject newText = new JSONObject(www.text);
                foreach (string key in newText.keys)
                {
                    text.Add(key, newText.GetField(key).str.Replace("\\n", System.Environment.NewLine));
                }
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
            }
        }
    }
Пример #37
0
    IEnumerator FetchConfig()
    {
        Debug.Log("FetchConfig");
        DebugInfoLabel = "FetchConfig from " + url_id;
        string ourPostData = "{\"user\":\"" + tracking_session_user + "\",\"version\":\"" + tracking_session_version + "\"}";
        Dictionary <string, string> headers = new Dictionary <string, string>();

        headers.Add("Content-Type", "application/json");
        byte[] pData = System.Text.Encoding.ASCII.GetBytes(ourPostData.ToCharArray());
        WWW    www   = new WWW(url_id, pData, headers);

        yield return(www);

        if (www.isDone && www.error == null && www.text != null && www.text.Trim() != "")
        {
            try{
                Debug.Log(www.text);
                JSONObject ob = new JSONObject(www.text.Trim());
                tracking_session_id = ob.GetField("id").ToString();
            } catch {
            }
            if (onSuccess != null)
            {
                onSuccess(www.text);
            }
        }
        else
        {
            if (onFail != null)
            {
                onFail();
            }
            Debug.Log(www.error);
            tracking_session_id = "NA";
        }
        //tracking_session_id = {"id": 11, "user": "******"}
        SetupTracking();
        yield return(null);
    }
Пример #38
0
        //JSONObject方式解析
        private IEnumerator ReadJsonFile(string path)
        {
            Debug.Log(path);
            string          jsonStr;
            UnityWebRequest request = UnityWebRequest.Get(path);

            yield return(request.SendWebRequest());

            jsonStr = request.downloadHandler.text;
            Debug.Log("jsonStr:" + jsonStr);
            JSONObject js = JSONObject.Create(jsonStr);
            JSONObject nowFiled;

            nowFiled = js.GetField("list");
            for (int i = 0; i < nowFiled.list.Count; i++)
            {
                string key      = nowFiled.list[i].keys[0];
                string strColor = nowFiled.list[i].GetField(key).str;
                Debug.Log("key = " + key);
                Debug.Log("strColor = " + strColor);
            }
        }
Пример #39
0
        public static string GetJSONValueAsString(JSONObject p_json, string p_key)
        {
            if (p_json.GetField(p_key).type == JSONObject.Type.NUMBER)
            {
                return(p_json.GetField(p_key).n.ToString());
            }
            if (p_json.GetField(p_key).type == JSONObject.Type.STRING)
            {
                return(p_json.GetField(p_key).str);
            }
            if (p_json.GetField(p_key).type == JSONObject.Type.BOOL)
            {
                return(p_json.GetField(p_key).b.ToString());
            }

            return("");
        }
Пример #40
0
    private float _YOffset;                                    // Distance between the first row and bottom side of the screen


    //==============================================
    // Unity Methods
    //==============================================

    void Awake()
    {
        Instance = this;

        // Get current level infomation from levelsInfo text file
        string     levelsInfoString = _levelsInfo.text;
        JSONObject levelsInfoJSON   = new JSONObject(levelsInfoString);
        JSONObject puzzleInfoJSON   = levelsInfoJSON.GetField(MadLevel.arguments);

        _rows           = (int)puzzleInfoJSON.GetField("rows").f;
        _columns        = (int)puzzleInfoJSON.GetField("columns").f;
        _unitTypesCount = (int)puzzleInfoJSON.GetField("unit types count").f;
        _turns          = (int)puzzleInfoJSON.GetField("turns").f;
        _1starPoint     = (int)puzzleInfoJSON.GetField("1 star point").f;
        _2starPoint     = (int)puzzleInfoJSON.GetField("2 star point").f;
        _3starPoint     = (int)puzzleInfoJSON.GetField("3 star point").f;

        // Set SFX and Music silder value
        _sfxSlider.value   = SoundController.Instance.sfxSource.volume;
        _musicSlider.value = SoundController.Instance.musicSource.volume;
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="PostboxResponse"/> class via JSONObject.
        /// </summary>
        /// <param name="localRequestId">localRequest identifier.</param>
        /// <param name="callName">callname of request</param>
        /// <param name="response">response object.</param>
        public PostboxGetFriendlistResponse(string localRequestId, PostboxCallName callName, JSONObject response) : base(localRequestId, callName, response)
        {
            if (response == null)
            {
                return;
            }

            JSONObject result = response.GetField("Result");

            if (result != null)
            {
                // --- Friends ---
                JSONObject requestsNode = result.GetField("Friends");

                if (requestsNode != null & requestsNode.IsArray)
                {
                    List <JSONObject> requestNodes = requestsNode.list;

                    if (requestNodes != null && requestNodes.Count > 0)
                    {
                        Friends = new PostboxDevicePackage[requestNodes.Count];

                        for (int i = 0; i < Friends.Length; i++)
                        {
                            JSONObject request = requestNodes[i].GetField("Friend");

                            // create object
                            Friends[i] = new PostboxDevicePackage(request.GetField("public_device_id").str,
                                                                  request.GetField("model").str,
                                                                  request.GetField("type").str,
                                                                  request.GetField("os").str,
                                                                  request.GetField("created_at").str,
                                                                  request.GetField("status").str);
                        }
                    }
                }
            }
        }
Пример #42
0
    void MatchmakerReceivedRequestLeaderboard(Notification n)
    {
        leaderboardMenu         = UI.Menu();
        leaderboardMenu.anchor  = MenuAnchor.TopCenter;
        leaderboardMenu.vMargin = 120f;

        var item = leaderboardMenu.AddNewText();

        item.innerMargins = new Vector2(0f, 0.5f);
        item.doesType     = true;
        item.SetText("top players:");
        item.rainbowCyclePeriod = 2f;
        //item.UseRainbowStyle();

        var pvpLeaders = pvpLadderResult.GetField("ladder").list;

        if (pvpLeaders.Count > 0)
        {
            item = leaderboardMenu.AddNewText();
            item.innerMargins = new Vector2(0f, 0.5f);
            item.doesType     = true;
            item.SetText(pvpLeaders[0].GetField("screenName").str + " (PVP)");
            item.UseRainbowStyle();
        }

        var pveLeaders = (n.data as JSONObject).list;

        if (pveLeaders.Count > 0)
        {
            item = leaderboardMenu.AddNewText();
            item.innerMargins = new Vector2(0f, 0.5f);
            item.doesType     = true;
            item.SetText(pveLeaders[0].GetField("screenName").str + " (PVE)");
            item.UseRainbowStyle();
        }

        leaderboardMenu.Show();
    }
Пример #43
0
    internal void onGetItemAllResponse(JSONObject data)
    {
        JSONObject jdata = data.GetField("adata");

        if (AllItemArray == null)
        {
            AllItemArray = new ArrayList();
        }

        for (int i = 0; i < jdata.Count; i++)
        {
            AllItemArray.Add(jdata [i]);
        }

//		InventoryArray
//		if (data.Count == InventoryArray.Count) {
//			for (int i = 0; i < jdata.Count; i++) {
//
//				InventoryCellBtn cell = InventoryArray [i] as InventoryCellBtn;
//				cell.ItemId = jdata [i].GetField ("id").ToString ().Trim ('"');
//				string url = jdata [i].GetField ("graphics").ToString ().Trim ('"');
//				StartCoroutine (cell.LoadImg (url));
//			}
//		} else {
//
////			OnRemoveAllObjects ();
//			InventoryArray = new ArrayList ();
//			for (int i = 0; i < jdata.Count; i++) {
//
//				InventoryCellBtn cell = Instantiate (itemPrefeb, ScrollPanel.transform, false);
//				cell.ItemId = jdata [i].GetField ("id").ToString ().Trim ('"');
//				string url = jdata [i].GetField ("graphics").ToString ().Trim ('"');
//				StartCoroutine (cell.LoadImg (url));
//				InventoryArray.Add (cell);
//			}
//		}
//		OnSetFirstPosition ();
    }
Пример #44
0
        void OnCarConfig(JSONObject json)
        {
            Debug.Log("Got car config message");

            string body_style = json.GetField("body_style").str;
            int    body_r     = int.Parse(json.GetField("body_r").str);
            int    body_g     = int.Parse(json.GetField("body_g").str);
            int    body_b     = int.Parse(json.GetField("body_b").str);
            string car_name   = json.GetField("car_name").str;
            int    font_size  = 100;

            if (json.GetField("font_size") != null)
            {
                font_size = int.Parse(json.GetField("font_size").str);
            }

            if (carObj != null)
            {
                UnityMainThreadDispatcher.Instance().Enqueue(SetCarConfig(body_style, body_r, body_g, body_b, car_name, font_size));
            }
        }
Пример #45
0
    public static string GetData(string type)
    {
        string  data = "";
        WWWForm form = GetFormData();

        form.AddField("name", type);
        WWW request = new WWW("https://apptracker.spilgames.com/v1/native-events/event/android/" + bundleIdentifier + "/" + type, form);

        while (!request.isDone)
        {
            ;
        }
        if (request.error != null && !request.error.Equals(""))
        {
            SpilLogging.Error("Error getting game data: " + request.error);
        }
        else
        {
            JSONObject serverResponse = new JSONObject(request.text);
            data = serverResponse.GetField("data").ToString();
        }
        return(data);
    }
Пример #46
0
        public override List <ISocialUser> ParseUsers(string inputData)
        {
            var result = new List <ISocialUser>();

            var data = new JSONObject(inputData);

            var field = data.GetField("response");

            if (field.IsArray == true)
            {
                foreach (var item in field.list)
                {
                    var user = new VKLocalUser();
                    user.socialModule = this.socialModule;
                    user.userData     = item.ToString();
                    user.ParseData(item);

                    result.Add(user);
                }
            }

            return(result);
        }
Пример #47
0
    public void Load()
    {
        Record.record.recordindex = 0;
        Move.move.moveIndex       = 0;

        if (File.Exists(filepath))
        {
            JSONObject jSONObject = new JSONObject(File.ReadAllText(filepath));
            Record.record.jSONObject = jSONObject;

            Record.record.recordindex = jSONObject.Count;
            if (Record.record.isRecord)
            {
                GameObject[] gameObject = GameObject.FindGameObjectsWithTag("Sphere");

                for (int j = 0; j < gameObject.Length; j++)
                {
                    Vector3 vector3 = new Vector3(float.Parse(jSONObject.GetField("1").GetField(j.ToString()).GetField("x").ToString().Replace("\"", ""))
                                                  , float.Parse(jSONObject.GetField("1").GetField(j.ToString()).GetField("y").ToString().Replace("\"", ""))
                                                  , float.Parse(jSONObject.GetField("1").GetField(j.ToString()).GetField("z").ToString().Replace("\"", "")));

                    gameObject[j].transform.localPosition = vector3;
                }
                return;
            }

            for (int i = 0; i < jSONObject.GetField("1").Count; i++)
            {
                GameObject gameObject = ButtonAction.buttonAction.CreatePrefabsReturn();

                Vector3 vector3 = new Vector3(float.Parse(jSONObject.GetField("1").GetField(i.ToString()).GetField("x").ToString().Replace("\"", ""))
                                              , float.Parse(jSONObject.GetField("1").GetField(i.ToString()).GetField("y").ToString().Replace("\"", ""))
                                              , float.Parse(jSONObject.GetField("1").GetField(i.ToString()).GetField("z").ToString().Replace("\"", "")));

                gameObject.transform.localPosition = vector3;
            }

            Record.record.isRecord = true;
        }
    }
Пример #48
0
    void OnSteer(SocketIOEvent obj)
    {
        if (!startedYet)
        {
            InvokeRepeating("RecordData", 0.0f, 0.1f);
            startTime  = Time.time;
            startedYet = true;
        }

//	    Debug.Log(string.Format("Steering data event, startedYet set to {0}", startedYet));
        JSONObject jsonObject = obj.data;

        CarRemoteControl.SteeringAngle = float.Parse(jsonObject.GetField("steering_angle").ToString());
        CarRemoteControl.Acceleration  = float.Parse(jsonObject.GetField("throttle").ToString());

        //string next_x = jsonObject.GetField ("next_x").ToString ();
        //string next_y = jsonObject.GetField ("next_y").ToString ();

        var          next_x    = jsonObject.GetField("next_x");
        var          next_y    = jsonObject.GetField("next_y");
        List <float> my_next_x = new List <float> ();
        List <float> my_next_y = new List <float> ();

        for (int i = 0; i < next_x.Count; i++)
        {
            my_next_x.Add(float.Parse((next_x [i]).ToString()));
            my_next_y.Add(float.Parse((next_y [i]).ToString()));
        }
        point_path.setNextPoint(my_next_x, my_next_y);

        var          mpc_x    = jsonObject.GetField("mpc_x");
        var          mpc_y    = jsonObject.GetField("mpc_y");
        List <float> my_mpc_x = new List <float> ();
        List <float> my_mpc_y = new List <float> ();

        for (int i = 0; i < mpc_x.Count; i++)
        {
            my_mpc_x.Add(float.Parse((mpc_x [i]).ToString()));
            my_mpc_y.Add(float.Parse((mpc_y [i]).ToString()));
        }

        point_path.setMpcPoint(my_mpc_x, my_mpc_y);

        EmitTelemetry(obj);
    }
Пример #49
0
    void Update()
    {
        //Work only if is activate
        if (!isActivate)
        {
            return;
        }

        if (countDown >= rebornTime)
        {
            int        randomCarIndex = Random.Range(0, carTypesList.Count);
            string     carID          = carTypesList[randomCarIndex].str;
            JSONObject carComp        = GameManager.instance.GetJSONComponent(carID);
            rebornTime = carComp.GetField("spawn_time").num;

            GameObject carPrefab = Resources.Load <GameObject>("Prefab/Vehicle/" + carID);

            CarBase carBase = GameObject.Instantiate(carPrefab, transform.position, transform.rotation, transform).GetComponent <CarBase>();
            carBase.init(carID, direct, carComp);
            countDown = 0;
        }
        countDown += Time.deltaTime;
    }
Пример #50
0
    void OnLoadScene(SocketIOEvent obj)
    {
        JSONObject jsonObject = obj.data;

        //Set these flags to trigger an auto reconnect when we load the new scene.
        GlobalState.bAutoConnectToWebSocket = true;
        GlobalState.bAutoHideSceneMenu      = true;

        string scene_name = jsonObject.GetField("scene_name").str;

        if (scene_name == "generated_road")
        {
            loader.LoadGenerateRoadScene();
        }
        else if (scene_name == "warehouse")
        {
            loader.LoadWarehouseScene();
        }
        else if (scene_name == "sparkfun_avc")
        {
            loader.LoadAVCScene();
        }
    }
Пример #51
0
 public void LoadFromJSON(JSONObject json)
 {
     if (json.HasField("Blocks"))
     {
         Transform blockContainer = ARBindingManager.Instance.BlockContainer;
         blockContainer.DestroyChildrenImmediate();
         List <JSONObject> list = json.GetField("Blocks").list;
         foreach (JSONObject item in list)
         {
             string     text          = item.asString("Type", () => string.Empty);
             int        num           = item.asInt("Size", () => 0);
             Vector3    localPosition = new Vector3(item.asFloat("X", () => 0f), item.asFloat("Y", () => 0f), item.asFloat("Z", () => 0f));
             Quaternion rotation      = ARBindingManager.Instance.World.transform.rotation;
             GameObject gameObject    = GameObjectExtensions.InstantiateFromResources("Blocks/AR/" + text + "Cube_" + num + "x" + num, Vector3.zero, rotation);
             Transform  transform     = gameObject.transform;
             Vector3    one           = Vector3.one;
             Vector3    localScale    = ARBindingManager.Instance.World.transform.localScale;
             transform.localScale = one * localScale.x;
             gameObject.transform.SetParent(blockContainer);
             gameObject.transform.localPosition = localPosition;
         }
     }
 }
Пример #52
0
        //

        /// <summary>
        /// 필요한 오디오클립 이름들을 모두 가져온다.
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string[] GatherRequiredClips(JSONObject json)
        {
            HashSet <string> clipnames = new HashSet <string>();

            json.GetField("sections", (sectionarr) =>
            {
                foreach (var section in sectionarr.list)
                {
                    section.GetField("layers", (layerarr) =>
                    {
                        foreach (var layer in layerarr.list)
                        {
                            clipnames.Add(layer.GetField("clip").str);
                        }
                    });
                }
            });

            var arr = new string[clipnames.Count];

            clipnames.CopyTo(arr);
            return(arr);
        }
Пример #53
0
    public void loadJson(string path)
    {
        foreach (Transform child in menuObjects.transform)
        {
            child.GetComponent <FadeMaterial>().toggleFade();
        }
        Destroy(menuObjects, 2);

        state = ManagerState.Visualizating;

        string     sjson      = File.ReadAllText(path);
        JSONObject jsonObject = new JSONObject(sjson);

        string cityPath = jsonObject.GetField("marketMesh").ToString().Replace("\"", "");

        print(cityPath);
        loadCity(cityPath);
        foreach (FadeMaterial fader in FindObjectsOfType <FadeMaterial>())
        {
            fader.toggleFade();
        }
        simulationReady(path);
    }
Пример #54
0
    /*
     * GetStudentData
     * Obtiene la información del estudiante con el nombre de usuario
     * y almacena la profesión.
     *
     *{
     *	"EDAD": 15,
     *	"GRADO_COD": 2,
     *	"NUI": "ERMBUT1117414070",
     *	"estado": { // Estado en el que está en cada juego.
     *		"Game_01": { //Identificador del juego por localidad
     *			"grado": 1, //Grado del juego en el que está
     *			"nivel": 2 //Nivel máximo superada
     *		}
     *	},
     *	"progresos": { //Puntaje acumulado
     *		"C-1": { //Ciclo C-1(0 a 3°) C-2(4° a 5°) C-3(6° a 9°)
     *			"Game_01": 5 //Puntaje total por juego
     *		},
     *		"total": {
     *			"C-1": {
     *				"MAT": 5 //Puntaje total por materia
     *			}
     *		}
     *	}
     *}
     */
    public static JSONObject GetStudentData(string user, string profession)
    {
        Request.user       = user;
        Request.profession = profession;

        if (!init)
        {
            InitSession(profession);
            Request.init = true;
        }

        //Consulta HTTPS GET
        string response = DoRequest(url + "alias/" + user + ".json", "GET");

        if (response == "ERROR")
        {
            Debug.Log("Error GetStudentData");
            try{
                JSONObject data = new JSONObject(File.ReadAllText(fileName));
                if (data != null && data.type != JSONObject.Type.NULL)
                {
                    return(data.GetField(user));
                }
            }catch (Exception error) {
                Debug.Log("Error Catch GetStudentData");
            }
            return(null);
        }
        else
        {
            Debug.Log("GetStudentData Done");
            JSONObject json = new JSONObject(response);
            Debug.Log(response);
            Request.student = json;
            return(json);
        }
    }
Пример #55
0
            public List <int> GetRemoveTokenIds()
            {
                Debug.Assert(type == Type.CHARACTER_GET_OUT || type == Type.REMOVE_TOKENS);
                var tokensField = "";

                if (type == Type.CHARACTER_GET_OUT)
                {
                    tokensField = "remove_tokens";
                }
                else if (type == Type.REMOVE_TOKENS)
                {
                    tokensField = "tokens";
                }
                else
                {
                    Debug.Assert(false);
                }
                List <int> ids = new List <int>();
                JSONObject arg = GetArg(0);

                Debug.Assert(JSONTools.HasFieldOfTypeArray(arg, tokensField));
                foreach (var obj in arg.GetField(tokensField).list)
                {
                    int id = 0;
                    if (obj.IsString)
                    {
                        int.TryParse(obj.str, out id);
                    }
                    else if (obj.IsNumber)
                    {
                        id = Mathf.RoundToInt(obj.n);
                    }
                    Debug.Assert(id > 0);
                    ids.Add(id);
                }
                return(ids);
            }
Пример #56
0
    //---------------------------------------------------------------------------------------------------------------------
    void LoadLevels()
    {
        //load
        var path = System.IO.Path.Combine(Application.persistentDataPath, "Game.json");

        if (!System.IO.File.Exists(path))
        {
            Db.Init();
            return;
        }

        System.IO.StreamReader r = new System.IO.StreamReader(path);
        var js = r.ReadToEnd();

        r.Close();

        //make json
        var jo      = new JSONObject(js);
        var jLevels = jo.GetField("levels").list;

        if (jLevels == null)
        {
            EditorUtility.DisplayDialog("Default", "Levels not found. using default values", "اوکی 2کی");
            Db.Init();
        }
        else
        {
            Db.Majors = new Major[jLevels.Count];
            for (int i = 0; i < jLevels.Count; i++)
            {
                Db.Majors[i] = new Major(jLevels[i]);
            }
        }


        refreshBlocks();
    }
Пример #57
0
        internal bool FromJSON(JSONObject json)
        {
            string authorId_str  = string.Empty;
            string timestamp_str = string.Empty;

            json.GetField(ref authorId_str, JSON_AUTHOR_ID);
            json.GetField(ref timestamp_str, JSON_TIMESTAMP);
            json.GetField(ref ImageURL, JSON_IMAGE_URL);
            bool success = json.GetField(ref Id, JSON_ID) && json.GetField(ref MessageContent, JSON_CONTENT) && ulong.TryParse(authorId_str, out AuthorId) && json.GetField(ref AuthorName, JSON_AUTHOR_NAME) &&
                           json.GetField(ref MessageURL, JSON_MESSAGE_URL) && DateTime.TryParse(timestamp_str, Var.Culture, System.Globalization.DateTimeStyles.AssumeUniversal, out Timestamp) && json.GetField(ref ChannelName, JSON_CHANNEL_NAME);

            if (success)
            {
                Timestamp      = DateTime.SpecifyKind(Timestamp, DateTimeKind.Utc);
                MessageContent = JSONObject.ReturnToUnsafeJSONString(MessageContent);
            }
            return(success);
        }
    public AnimationData(JSONObject j)
    {
        var duration = j.GetField("duration").n;

        name = j.GetField("name").str;

        var tgtPosAry = j.GetField("tgtPos");

        tgtPos = new Vector3(
            tgtPosAry[0].n,
            tgtPosAry[1].n,
            tgtPosAry[2].n
            );

        speed     = j.GetField("speed").n;
        startTime = j.GetField("startTime").n;
        endTime   = j.GetField("endTime").n;
    }
Пример #59
0
            private List <PacketData> ParseData(JSONObject json)
            {
                List <PacketData> newPackets = new List <PacketData>();

                if (json.HasField("status"))
                {
                    if (json.GetField("status").type == JSONObject.Type.NUMBER && json.GetField("status").n == 1 && json.HasField("data"))
                    {
                        json = json.GetField("data");
                    }
                    else
                    {
                        Logger.Instance.Log("WARNING", "GameData Parse Errror");
                        return(newPackets);
                    }
                }

                if (json.HasField("valid"))
                {
                    if (json.GetField("valid").type == JSONObject.Type.NUMBER && json.GetField("valid").n == 1 && json.HasField("data"))
                    {
                        json = json.GetField("data");
                    }
                    else
                    {
                        Logger.Instance.Log("WARNING", "GameData Parse Errror");
                        return(newPackets);
                    }
                }

                if (json.type == JSONObject.Type.ARRAY)
                {
                    for (int i = 0; i < json.Count; ++i)
                    {
                        newPackets.Add(new PacketData(json[i]));
                    }
                }
                else
                {
                    newPackets.Add(new PacketData(json));
                }

                return(newPackets);
            }
Пример #60
0
    public void ClientRunner(TcpClient client)
    {
        NetworkStream ns = client.GetStream();
        StreamReader  sr = new StreamReader(ns);

        Queue <string> messageQueue = new Queue <string>();

        messageQueues.Add(messageQueue);
        messageQueue.Enqueue(CreateItemListMessage());
        new Thread(() => OutRunner(client, messageQueue)).Start();

        while (running && client.Connected)
        {
            string jMessage = sr.ReadLine();
            if (jMessage.Length == 0)
            {
                break;
            }

            JSONObject serializedObject = new JSONObject(jMessage);
            int        messageType      = -1;
            serializedObject.GetField(out messageType, "mtype", -1);
            Debug.Log("Type: " + messageType + " Message: " + serializedObject);

            if (messageType == 1)
            {
                messageQueue.Enqueue(CreateItemListMessage());
            }
        }

        if (client.Connected)
        {
            client.Close();
        }
        Debug.Log("Client disconnected");
    }