HasField() 공개 메소드

public HasField ( string name ) : bool
name string
리턴 bool
예제 #1
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;
    }
예제 #2
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;
    }
예제 #3
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);
                }
            }
        }
	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 ;
	}	
예제 #5
0
 /// <summary>
 /// Merge object right into left recursively
 /// </summary>
 /// <param name="left">The left (base) object</param>
 /// <param name="right">The right (new) object</param>
 static void MergeRecur(JSONObject left, JSONObject right)
 {
     if (left.type == JSONObject.Type.NULL)
     {
         left.Absorb(right);
     }
     else if (left.type == Type.OBJECT && right.type == Type.OBJECT)
     {
         for (int i = 0; i < right.list.Count; i++)
         {
             string key = (string)right.keys[i];
             if (right[i].isContainer)
             {
                 if (left.HasField(key))
                 {
                     MergeRecur(left[key], right[i]);
                 }
                 else
                 {
                     left.AddField(key, right[i]);
                 }
             }
             else
             {
                 if (left.HasField(key))
                 {
                     left.SetField(key, right[i]);
                 }
                 else
                 {
                     left.AddField(key, right[i]);
                 }
             }
         }
     }
     else if (left.type == Type.ARRAY && right.type == Type.ARRAY)
     {
         if (right.Count > left.Count)
         {
             Debug.LogError("Cannot merge arrays when right object has more elements");
             return;
         }
         for (int i = 0; i < right.list.Count; i++)
         {
             if (left[i].type == right[i].type)                                      //Only overwrite with the same type
             {
                 if (left[i].isContainer)
                 {
                     MergeRecur(left[i], right[i]);
                 }
                 else
                 {
                     left[i] = right[i];
                 }
             }
         }
     }
 }
예제 #6
0
 /// <summary>
 /// Merge object right into left recursively
 /// </summary>
 /// <param name="left">The left (base) object</param>
 /// <param name="right">The right (new) object</param>
 static void MergeRecur(JSONObject left, JSONObject right)
 {
     if (left.type == Type.NULL)
     {
         left.Absorb(right);
     }
     else if (left.type == Type.OBJECT && right.type == Type.OBJECT)
     {
         for (int i = 0; i < right.list.Count; i++)
         {
             string key = right.keys[i];
             if (right[i].isContainer)
             {
                 if (left.HasField(key))
                 {
                     MergeRecur(left[key], right[i]);
                 }
                 else
                 {
                     left.AddField(key, right[i]);
                 }
             }
             else
             {
                 if (left.HasField(key))
                 {
                     left.SetField(key, right[i]);
                 }
                 else
                 {
                     left.AddField(key, right[i]);
                 }
             }
         }
     }
     else if (left.type == Type.ARRAY && right.type == Type.ARRAY)
     {
         if (right.Count > left.Count)
         {
             return;
         }
         for (int i = 0; i < right.list.Count; i++)
         {
             if (left[i].type == right[i].type)
             {           //Only overwrite with the same type
                 if (left[i].isContainer)
                 {
                     MergeRecur(left[i], right[i]);
                 }
                 else
                 {
                     left[i] = right[i];
                 }
             }
         }
     }
 }
예제 #7
0
    internal static void createDialogNode(Sequence seq, JSONObject jsonObj, IState variables, string nodeId, string key)
    {
        JSONObject node = jsonObj.GetField(nodeId);

        if (!node.HasField(FRAGMENTS_FIELD))
        {
            throw new Exception("The node " + key + "->" + nodeId + " need a " + FRAGMENTS_FIELD + " field");
        }
        List <JSONObject> fragmentList = node.GetField(FRAGMENTS_FIELD).list;

        List <Fragment> fragments = new List <Fragment>();

        foreach (JSONObject j in fragmentList)
        {
            if (j.HasField(TAG_FIELD) && j.HasField(MESSAGE_FIELD))
            {
                string character = "";
                if (j.HasField(CHARACTER_FIELD))
                {
                    character = j.GetField(CHARACTER_FIELD).ToString().Replace("\"", "");
                }
                fragments.Add(new Fragment(j.GetField(TAG_FIELD).ToString().Replace("\"", ""), j.GetField(MESSAGE_FIELD).ToString().Replace("\"", ""), character));
            }
            else
            {
                throw new Exception("The node " + key + "->" + nodeId + " need a " + TAG_FIELD + " and " + MESSAGE_FIELD + " field");
            }
        }

        SequenceNode newNode = seq[nodeId];

        newNode.Content = Dialog.Create(fragments);

        //Assign content if root
        if (nodeId == "root")
        {
            seq.Root = newNode;
        }

        //Create child
        if (node.HasField(NEXT_FIELD))
        {
            string nextNodeId = node.GetField(NEXT_FIELD).ToString().Replace("\"", "");
            if (nodeId == "root")
            {
                seq.Root.Childs[0] = seq[nextNodeId];
            }
            else
            {
                seq[nodeId][0] = seq[nextNodeId];
            }
            createNode(seq, jsonObj, variables, nextNodeId, key);
        }
    }
예제 #8
0
    internal static void createSetterNode(Sequence seq, JSONObject jsonObj, IState variables, string nodeId, string key)
    {
        JSONObject node = jsonObj.GetField(nodeId);

        if (!node.HasField(SETTER_FIELD))
        {
            throw new Exception("The node " + key + "->" + nodeId + " setter need a " + SETTER_FIELD + " field");
        }
        JSONObject   setterNode = node.GetField(SETTER_FIELD);
        SequenceNode newNode    = seq[nodeId];

        if (setterNode.HasField(SETTER_VARIABLE_FIELD))
        {
            string variable = setterNode.GetField(SETTER_VARIABLE_FIELD).ToString().Replace("\"", "");
            string value    = "false";
            if (!setterNode.HasField(SETTER_VALUE_FIELD))
            {
                throw new Exception("The variable " + variable + " in node " + key + "->" + nodeId + " need a " + SETTER_VALUE_FIELD + " field");
            }
            else
            {
                value = setterNode.GetField(SETTER_VALUE_FIELD).ToString().Replace("\"", "");
            }

            FormulaSetter fSetter = FormulaSetter.Create(variable, value);
            newNode.Content = fSetter;

            //Assign content if root
            if (nodeId == "root")
            {
                seq.Root = newNode;
            }

            //Create child
            if (node.HasField(NEXT_FIELD))
            {
                string nextNodeId = node.GetField(NEXT_FIELD).ToString().Replace("\"", "");
                if (nodeId == "root")
                {
                    seq.Root.Childs[0] = seq[nextNodeId];
                }
                else
                {
                    seq[nodeId][0] = seq[nextNodeId];
                }
                createNode(seq, jsonObj, variables, nextNodeId, key);
            }
        }
        else
        {
            throw new Exception("The node " + key + "->" + nodeId + " setter need a " + SETTER_VARIABLE_FIELD + " field");
        }
    }
예제 #9
0
    public static SerializedLevel FromJson(JSONObject jsonObject)
    {
        Debug.Log("Print: \n" + jsonObject);
        var serializedLevel = new SerializedLevel();
        serializedLevel.Name = jsonObject.GetField("name").str;

        serializedLevel.Width = (int) jsonObject.GetField("width").n;
        serializedLevel.Height = (int) jsonObject.GetField("height").n;
        serializedLevel.NumberOfColors = jsonObject.HasField("numberOfColors")
            ? (int) jsonObject.GetField("numberOfColors").n
            : 6;
        serializedLevel.Seed = jsonObject.HasField("seed") ? (int) jsonObject.GetField("seed").n : 1;

        serializedLevel.GameMode = GameModeDescription.CreateFromJson(jsonObject.GetField("gameMode"));

        var array = jsonObject.GetField("map").list;
        foreach (var tile in array)
        {
            var x = array.IndexOf(tile)%serializedLevel.Width;
            var y = serializedLevel.Height - (array.IndexOf(tile)/serializedLevel.Width) - 1;

            var tileType = (int) tile.n;
            switch (tileType)
            {
                case (0): //empty
                    break;
                case (2): // place
                    serializedLevel.SpecialCells.Add(new Cell(x, y) {HasPlace = true});
                    break;
                case (3): //counter
                    serializedLevel.SpecialCells.Add(new Cell(x, y) {HasCounter = true});
                    break;
                default: // block
                    serializedLevel.SpecialCells.Add(new Cell(x, y, CellTypes.Block));
                    break;
            }
        }

        serializedLevel.Stages = CreateStagesFromJsonObject(jsonObject.GetField("stages"));

        serializedLevel.Star1Score = jsonObject.HasField("Star1Score")
            ? (int) jsonObject.GetField("Star1Score").n
            : 1000;
        serializedLevel.Star2Score = jsonObject.HasField("Star2Score")
            ? (int) jsonObject.GetField("Star2Score").n
            : 2000;
        serializedLevel.Star3Score = jsonObject.HasField("Star3Score")
            ? (int) jsonObject.GetField("Star3Score").n
            : 3000;

        return serializedLevel;
    }
예제 #10
0
        public static WsControllerMessage FromJson(string json)
        {
            var jobject = new JSONObject(json);

            var msg = new WsControllerMessage
            {
                AckId  = jobject.HasField("ackId") ? jobject["ackId"].Int : -1,
                OpCode = jobject.HasField("opcode") ? jobject["opcode"].String : string.Empty,
                Data   = jobject.HasField("data") ? jobject["data"] : JSONObject.Null
            };

            return(msg);
        }
예제 #11
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");

                // Operators
                foreach (var opJs in opsJs.list)
                {
                    var type = System.Type.GetType(opJs["Type"].str);
                    if (type != null)
                    {
                        var op = (Operator)System.Activator.CreateInstance(type);
                        op.Deserialize(opJs);
                        template.Operators.Add(op.GUID, op);
                    }
                    else
                    {
                        Debug.LogWarningFormat("Discarding unknown serialized operator `{0}`", opJs["Type"].str);
                    }
                }

                // Connections
                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.Connections.Add(new IOConnection()
                    {
                        From = fromOp, Output = output, To = toOp, Input = input
                    });
                }
            }
        }
예제 #12
0
    void LoadTiles()
    {
        this.atlasWidth  = this.tilesTexture.width / SettingsManager.shared.tileResolution;
        this.atlasHeight = this.tilesTexture.height / SettingsManager.shared.tileResolution;
        JSONObject root = new JSONObject(this.tilesDatabase.text);

        // Переберем тайлы
        for (int k = 0; k < root.list.Count; k++)
        {
            JSONObject jsonTile = root.list[k];
            GDTile[]   textures = new GDTile[jsonTile.list.Count];
            string     name     = root.keys[k];
            tiles[name] = textures;

            // Переберем варианты текстур тайла
            for (int t = 0; t < jsonTile.list.Count; t++)
            {
                JSONObject jsonTexture = jsonTile.list[t];

                // Если текстура анимированая, переберем координаты кадров и добавим в массив разверток
                if (jsonTexture.HasField(jAnimation))
                {
                    JSONObject  jsonFrames = jsonTexture.GetField(jAnimation);
                    Vector2[][] uvs        = new Vector2[jsonFrames.list.Count][];
                    for (int f = 0; f < jsonFrames.list.Count; f++)
                    {
                        JSONObject jsonFrame = jsonFrames.list[t];
                        uvs[f] = GetUV(jsonFrame.GetField(jX).f, jsonFrame.GetField(jY).f);
                    }
                    GDTile texture = new GDTile(uvs);
                    if (jsonTexture.HasField(jSync))
                    {
                        texture.sync = jsonTexture.GetField(jSync).b;
                    }
                    textures[t] = texture;

                    // Иначе текстура не анимированая, просто добавим координату одной развертки
                }
                else
                {
                    Vector2[] uv      = GetUV(jsonTile.GetField(jX).f, jsonTile.GetField(jY).f);
                    GDTile    texture = new GDTile(uv);
                    if (jsonTile.HasField(jWeight))
                    {
                        texture.weight = (int)jsonTile.GetField(jWeight).f;
                    }
                    textures[t] = texture;
                }
            }
        }
    }
예제 #13
0
    public static Keyframe ToKeyframe(JSONObject obj)
    {
        Keyframe k = new Keyframe(obj.HasField("time")? obj.GetField("time").n : 0, obj.HasField("value")? obj.GetField("value").n : 0);

        if (obj.HasField("inTangent"))
        {
            k.inTangent = obj.GetField("inTangent").n;
        }
        if (obj.HasField("outTangent"))
        {
            k.outTangent = obj.GetField("outTangent").n;
        }

        return(k);
    }
예제 #14
0
    IEnumerator Login(string usrn, string pswd)
    {
        JSONObject js = new JSONObject();

        js.AddField("user_name", usrn);
        js.AddField("password", pswd);

        using (UnityWebRequest webRequest = new UnityWebRequest("http://127.0.0.1:5000/user-verify", "POST"))
        {
            byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(js.ToString());
            webRequest.uploadHandler   = (UploadHandler) new UploadHandlerRaw(jsonToSend);
            webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            webRequest.SetRequestHeader("Content-Type", "application/json");

            //Send the request then wait here until it returns
            yield return(webRequest.SendWebRequest());

            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.LogError(webRequest.error);
                infoText.text = webRequest.error;
                anim_search.SetBool("showpanel", true);
            }
            else
            {
                JSONObject response = new JSONObject(webRequest.downloadHandler.text);
                Debug.Log("Received: " + response.ToString());

                if (response.HasField("uID") && response.HasField("password"))
                {
                    Debug.Log("Login");

                    PlayerPrefs.SetString("username", response.GetField("uID").str);
                    PlayerPrefs.SetString("password", response.GetField("password").str);
                    PlayerPrefs.SetInt("coins", (int)response.GetField("coins").n);
                    PlayerPrefs.SetInt("weekly_rounds", (int)response.GetField("weekly_rounds").n);
                    PlayerPrefs.SetInt("xp", (int)response.GetField("xp").n);

                    SceneManager.LoadScene(1);
                }
                else
                {
                    infoText.text = Reverse("Please write down your correct credentials"); //Please write down your correct credentials
                    anim_search.SetBool("showpanel", true);
                }
            }
        }
    }
예제 #15
0
    IEnumerator WaitForTurn(WWW www)
    {
        yield return(www);

        // check for errors
        if (www.error == null)
        {
            Debug.Log("WaitForTurnResponse:" + www.text);
            JSONObject j = new JSONObject(www.text);
            if (j.HasField("data") && DataCallback != null)
            {
                JSONObject data = j ["data"];
                Debug.Log("Calling data back");
                DataCallback(data[data.Count - 1]);
            }

            if (j ["status"].i == 0)
            {
                WWW www1 = new WWW(waitForTurnUrl);
                getInstance().StartCoroutine(WaitForTurn(www1));
            }
            else if (j["status"].i == 1)
            {
                TurnCallback();
            }
        }
        else
        {
            Debug.Log("WWW Error: " + www.error);
        }
    }
예제 #16
0
    private static void addAdDealsSDKWithJson(string projectJson)
    {
        if (!System.IO.File.Exists(projectJson))
        {
            Debug.Log("ERROR! Project nuget json not exist:" + projectJson);
            return;
        }

        string     jsonString = System.IO.File.ReadAllText(projectJson);
        JSONObject j          = new JSONObject(jsonString);
        JSONObject dep        = j.GetField("dependencies");

        if (null != dep && dep.HasField("AdDealsUniversalSDKW81"))
        {
            return;
        }
        if (null == dep)
        {
            dep = new JSONObject();
            j.AddField("dependencies", dep);
        }
        dep.AddField("AdDealsUniversalSDKW81", "4.6.0");
        string newJsonString = j.Print(true);

        System.IO.File.WriteAllText(projectJson, newJsonString);
    }
예제 #17
0
    public static Sequence createSimplyDialog(string key, JSONObject json, IState variablesObject)
    {
        Sequence seq = ScriptableObject.CreateInstance <Sequence>();

        if (variablesObject && seq.GetObject(LOCAL_STATE) == null)
        {
            seq.SetObject(LOCAL_STATE, variablesObject);
        }
        if (seq.GetObject(GLOBAL_STATE) == null)
        {
            seq.SetObject(GLOBAL_STATE, GlobalState.Instance);
        }

        if (!json.HasField(key))
        {
            throw new Exception("Not found the key " + key + " in json " + json);
        }

        JSONObject jsonObj = json.GetField(key);

        string nodeId = "root";

        createNode(seq, jsonObj, variablesObject, nodeId, key);

        return(seq);
    }
예제 #18
0
        private static void FollowingUserFriendsFBResult(FBResult result)
        {
            if (string.IsNullOrEmpty(result.Error))
            {
                Debug.Log("Error!");
            }
            else
            {
                Dictionary <long, string> usuarioFriendsFacebook = new Dictionary <long, string>();
                var json = new JSONObject(result.Text);
                if (json.HasField("data"))
                {
                    var data = json.GetField("data");
                    foreach (var item in data.list)
                    {
                        var id   = 0L;
                        var name = string.Empty;

                        if (item.HasField("id"))
                        {
                            id = Convert.ToInt64(item.GetField("id").str);
                        }

                        if (item.HasField("name"))
                        {
                            name = item.GetField("name").str;
                        }

                        usuarioFriendsFacebook.Add(id, name);
                    }
                }

                //WebService.Instance.GetUserFriendsForFollow(usuarioFriendsFacebook);
            }
        }
예제 #19
0
    public ProgressModel(string messageJson)
    {
        JSONObject j = new JSONObject(messageJson);

        mProgressType = (ProgressType)j.GetField("mProgressType").i;
        mProgress     = (int)j.GetField("mProgress").i;
        mFile         = new FileModel(j.GetField("mFile").ToString());
        if (j.HasField("mGroupSize"))
        {
            mGroupSize = (int)j.GetField("mGroupSize").i;
        }
        if (j.HasField("mGroupPosition"))
        {
            mGroupPosition = (int)j.GetField("mGroupPosition").i;
        }
    }
예제 #20
0
    public void ExecuteCommand(JSONObject Command)
    {
        lastPos = new Vector2((float)Command.GetField("posX").n, (float)Command.GetField("posY").n);

        if (Command.HasField("move"))
        {
            body.AddForce(new Vector2(direction.x * moveSpeed, direction.y * moveSpeed), ForceMode2D.Force);
            body.velocity = Vector2.ClampMagnitude(body.velocity, moveSpeed);
        }

        // Failsafe against missync
        if (Command.HasField("destroy"))
        {
            ThisDestroy();
        }
    }
예제 #21
0
        private void RunFactories(JSONObject mapData)
        {
            foreach (var factory in _factories)
            {
                if (_settings.UseLayers)
                {
                    if (!mapData.HasField(factory.XmlTag))
                    {
                        continue;
                    }

                    var b = factory.CreateLayer(_settings.TileCenter, mapData[factory.XmlTag]["features"].list);
                    if (b) //getting a weird error without this, no idea really
                    {
                        b.transform.SetParent(transform, false);
                    }
                }
                else
                {
                    var fac = factory;
                    foreach (var entity in mapData[factory.XmlTag]["features"].list.Where(x => fac.Query(x)).SelectMany(geo => fac.Create(_settings.TileCenter, geo)))
                    {
                        if (entity != null)
                        {
                            entity.transform.SetParent(transform, false);
                        }
                        //I'm not keeping these anywhere for now but you can always create a list or something here and save them
                    }
                }
            }
        }
예제 #22
0
        // -----------------------------------------------------------------------------------
        /// <summary>
        /// Load every ISaveable object registered with Add()
        /// </summary>
        /// <returns> true, if the file was loaded, false if it doesn't exist </returns>
        public bool Load(string filename)
        {
            if (!Exists(filename))
            {
                return(false);
            }

            JSONObject json = EncryptedFile.ReadJSONObject(filename);

            foreach (KeyValuePair <string, ISaveable> kvp in _list)
            {
                if (json.HasField(kvp.Key))
                {
                    kvp.Value.OnLoad(json[kvp.Key]);
                }
#if !RELEASE
                else
                {
                    Debug.LogWarning("Found id " + kvp.Key + " in save file, but no object to load it");
                }
#endif
            }

            return(true);
        }
예제 #23
0
        /// <summary>
        /// Constructor.
        /// Generates an instance of <c>MarketItem</c> from a <c>JSONObject<c>.
        /// </summary>
        /// <param name="jsonObject">A <c>JSONObject</c> representation of the wanted
        /// <c>MarketItem</c>.</param>
        public MarketItem(JSONObject jsonObject)
        {
            string keyToLook = "";

#if UNITY_IOS && !UNITY_EDITOR
            keyToLook = JSONConsts.MARKETITEM_IOS_ID;
#elif UNITY_ANDROID && !UNITY_EDITOR
            keyToLook = JSONConsts.MARKETITEM_ANDROID_ID;
#endif
            if (!string.IsNullOrEmpty(keyToLook) && jsonObject.HasField(keyToLook))
            {
                ProductId = jsonObject[keyToLook].str;
            }
            else
            {
                ProductId = jsonObject[JSONConsts.MARKETITEM_PRODUCT_ID].str;
            }
            Price = jsonObject[JSONConsts.MARKETITEM_PRICE].n;
            int cOrdinal = System.Convert.ToInt32(((JSONObject)jsonObject[JSONConsts.MARKETITEM_CONSUMABLE]).n);
            if (cOrdinal == 0)
            {
                this.consumable = Consumable.NONCONSUMABLE;
            }
            else if (cOrdinal == 1)
            {
                this.consumable = Consumable.CONSUMABLE;
            }
            else
            {
                this.consumable = Consumable.SUBSCRIPTION;
            }
        }
예제 #24
0
        private IEnumerator DisplayChoirGroups()
        {
            JSONObject choirGroupData = null;

            yield return(StartCoroutine(serviceManager.MakeRequest(RequestType.ChoirGroups, value => choirGroupData = value as JSONObject)));

            if (!choirGroupData.IsNull && choirGroupData.HasField("Records") && choirGroupData["Records"].Count > 0)
            {
                responsePanel.visible = false;

                int iColor = 0;
                for (int i = 0; i < choirGroupData["Records"].Count; i++)
                {
                    GameObject obj = Instantiate(templateChoirGroup, choirGroupsRootObj.transform);

                    obj.GetComponent <RectTransform>().position = obj.GetComponent <RectTransform>().position + new Vector3((obj.GetComponent <RectTransform>().rect.size.y *(i + 1)), 0, 0);
                    obj.GetComponent <ChoirGroup>().SetupSession(this, choirGroupData["Records"][i], colors[iColor].background, colors[iColor].font);
                    iColor = iColor + 1 < colors.Length ? iColor + 1 : 0;

                    sessionsSet = true;
                    yield return(null);
                }
            }
            else
            {
                responsePanel.response = "NO CHOIRS AVAILABLE";
            }


            anim.SetBool("Loading", false);
            isSliding = false;
        }
예제 #25
0
    public static Keyframe ToKeyframe(JSONObject obj)
    {
        Keyframe k = new Keyframe((float)(obj.HasField("time")? obj.GetField("time").n : 0), (float)(obj.HasField("value")? obj.GetField("value").n : 0));

        if (obj.HasField("inTangent"))
        {
            k.inTangent = (float)obj.GetField("inTangent").n;
        }
        if (obj.HasField("outTangent"))
        {
            k.outTangent = (float)obj.GetField("outTangent").n;
        }
        //if(obj.HasField("tangentMode")) k.tangentMode = (int)obj.GetField("tangentMode").n;

        return(k);
    }
예제 #26
0
 public void SpawnData(JSONObject dataIn)
 {
     if (dataIn == null)
     {
         DeleteSpawn(); return;
     }
     _id  = dataIn["_id"] != null ? dataIn["_id"].ToString().Replace("\"", "") : _id;
     user = dataIn["user"] != null ? dataIn["user"].ToString().Replace("\"", "") : _id;
     if (dataIn["energy"])
     {
         int e = Int32.Parse(dataIn["energy"].ToString());
         if (e != 0 || e != energy)
         {
             if (energyCapacity == 0 && dataIn["energyCapacity"])
             {
                 energyCapacity = Int32.Parse(dataIn["energyCapacity"].ToString());
             }
             SetEnergy(e);
         }
     }
     if (dataIn.HasField("power"))
     {
         Debug.Log("powerchange");
         int p = 0;
         dataIn.GetField(ref p, "power");
         if (powerCapacity == 0 && dataIn["powerCapacity"])
         {
             powerCapacity = Int32.Parse(dataIn["powerCapacity"].ToString());
         }
         SetPower(p);
     }
 }
    private void Awake()
    {
        uiCircleSlider.onValueChange.AddListener(UpdateTime);

        uiCircleSlider.minValue = minTime;
        uiCircleSlider.maxValue = maxTime;

        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))
            {
                float data = json.GetField(entry).f;
                uiCircleSlider.currentValue = data;
            }
        }

        UpdateField();
    }
예제 #28
0
    public void RpcSendSquadToOpponent(string squadsJsonString)
    {
        JSONObject squadsJson = new JSONObject(squadsJsonString);

        if (squadsJson.HasField("Server"))
        {
            JSONObject squadJson = squadsJson["Server"];
            RosterBuilder.SetPlayerSquadFromImportedJson(squadJson, Players.PlayerNo.Player1, delegate { });
        }

        if (squadsJson.HasField("Client"))
        {
            JSONObject squadJson = squadsJson["Client"];
            RosterBuilder.SetPlayerSquadFromImportedJson(squadJson, Players.PlayerNo.Player2, Network.FinishTask);
        }
    }
예제 #29
0
    IEnumerator CreateAccount(string username, string password, string email)
    {
        WWWForm registerForm = new WWWForm();

        registerForm.AddField("username", username);
        registerForm.AddField("email", email);
        registerForm.AddField("password", password);
        registerForm.AddField("submitted", 1);
        WWW www = new WWW(REGISTER_URL, registerForm);

        yield return(www);

        if (www.error != null)
        {
            Debug.Log("ERROR ON REGISTRATION: " + www.error);
        }
        else
        {
            string encodedString = www.data;
            Debug.Log(encodedString);
            JSONObject j = new JSONObject(encodedString);
            // Debug.Log(j.list);
            // Debug.Log(j.HasField("id_u"));
            if (j.HasField("id_u"))
            {
                string uID = j.GetField("id_u").str;
                Debug.Log(uID);
                userID = int.Parse(uID);
                Debug.Log(userID + ": Registered and Logged In");
                loginStatus = LoginStatus.LoggedIn;
            }
        }

        yield return(0);
    }
예제 #30
0
        public void onGoodUpgrade(string message, bool alsoPush)
        {
            SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGoodUpgrade:" + message);

            var eventJSON = new JSONObject(message);

            VirtualGood vg  = (VirtualGood)StoreInfo.GetItemByItemId(eventJSON["itemId"].str);
            UpgradeVG   vgu = null;

            if (eventJSON.HasField("upgradeItemId") && !string.IsNullOrEmpty(eventJSON["upgradeItemId"].str))
            {
                vgu = (UpgradeVG)StoreInfo.GetItemByItemId(eventJSON["upgradeItemId"].str);
            }

            StoreInventory.RefreshOnGoodUpgrade(vg, vgu);

            StoreEvents.OnGoodUpgrade(vg, vgu);

            if (alsoPush)
            {
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
                sep.PushEventOnGoodUpgrade(vg, vgu);
#endif
            }
        }
예제 #31
0
 public void LoadARLevel()
 {
     if (File.Exists(PersistentDataPath.Get() + "/ARLevel.idl"))
     {
         string     cipherText = File.ReadAllText(PersistentDataPath.Get() + "/ARLevel.idl");
         string     str        = Encryptor.Decrypt(cipherText);
         JSONObject jSONObject = new JSONObject(str);
         if (jSONObject.HasField("Blocks"))
         {
             Transform blockContainer = ARBindingManager.Instance.BlockContainer;
             blockContainer.DestroyChildrenImmediate();
             List <JSONObject> list = jSONObject.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;
             }
         }
     }
 }
예제 #32
0
        private IEnumerator ProcessScans()
        {
            bool cleanSession = true;

            for (int i = 0; i < scans.Count; i++)
            {
                JSONObject response = null;
                yield return(StartCoroutine(serviceManager.MakeRequest(RequestType.Create, value => response = value as JSONObject, new string[] { SaveData.saveData.choirGroupSessionId, SaveData.saveData.scans[i] })));

                if (response != null)
                {
                    if (response.HasField("BadToken"))
                    {
                        GetComponent <SwitchView>().ChangeView(View.Login);
                        GetComponent <Login>().Message("LOGIN REQUIRED");
                        cleanSession = false;
                    }

                    scans[i].GetComponent <Animator>().SetTrigger("Success");
                }
            }

            if (cleanSession)
            {
                scans.Clear();
                SaveData.saveData.ClearSavedData();
            }
        }
예제 #33
0
파일: MarketItem.cs 프로젝트: umardev0/Six
        /// <summary>
        /// Constructor.
        /// Generates an instance of <c>MarketItem</c> from a <c>JSONObject<c>.
        /// </summary>
        /// <param name="jsonObject">A <c>JSONObject</c> representation of the wanted
        /// <c>MarketItem</c>.</param>
        public MarketItem(JSONObject jsonObject)
        {
            string keyToLook = "";

#if UNITY_IOS && !UNITY_EDITOR
            keyToLook = StoreJSONConsts.MARKETITEM_IOS_ID;
#elif UNITY_ANDROID && !UNITY_EDITOR
            keyToLook = StoreJSONConsts.MARKETITEM_ANDROID_ID;
#endif
            if (!string.IsNullOrEmpty(keyToLook) && jsonObject.HasField(keyToLook))
            {
                ProductId = jsonObject[keyToLook].str;
            }
            else
            {
                ProductId = jsonObject[StoreJSONConsts.MARKETITEM_PRODUCT_ID].str;
            }
            Price = jsonObject[StoreJSONConsts.MARKETITEM_PRICE].n;

            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICE])
            {
                this.MarketPriceAndCurrency = jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICE].str;
            }
            else
            {
                this.MarketPriceAndCurrency = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETTITLE])
            {
                this.MarketTitle = jsonObject[StoreJSONConsts.MARKETITEM_MARKETTITLE].str;
            }
            else
            {
                this.MarketTitle = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETDESC])
            {
                this.MarketDescription = jsonObject[StoreJSONConsts.MARKETITEM_MARKETDESC].str;
            }
            else
            {
                this.MarketDescription = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETCURRENCYCODE])
            {
                this.MarketCurrencyCode = jsonObject[StoreJSONConsts.MARKETITEM_MARKETCURRENCYCODE].str;
            }
            else
            {
                this.MarketCurrencyCode = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICEMICROS])
            {
                this.MarketPriceMicros = System.Convert.ToInt64(jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICEMICROS].n);
            }
            else
            {
                this.MarketPriceMicros = 0;
            }
        }
예제 #34
0
    public void SetStoryByIndex(int p_index)
    {
        currentIndex = p_index;
        JSONObject cStoryJSON = storyBoardJSONList[currentIndex];

        Text  s_text      = transform.Find("dialogue_panel/description").GetComponent <Text>();
        Image avatarImage = transform.Find("dialogue_panel/avatar").GetComponent <Image>();

        Image backgroundImage = GetComponent <Image>();

        //Set text
        s_text.text = cStoryJSON.GetField("text").str;

        //Set background
        Sprite bg_sprite = Resources.Load <Sprite>("Sprite/Background/" + cStoryJSON.GetField("background").str);

        backgroundImage.sprite = bg_sprite;

        //Set avatar
        if (cStoryJSON.HasField("avatar") && cStoryJSON.GetField("avatar").str != "")
        {
            Sprite avatar_sprite = Resources.Load <Sprite>("Sprite/Avatar/" + cStoryJSON.GetField("avatar").str);
            avatarImage.enabled = (avatar_sprite != null);
            avatarImage.sprite  = avatar_sprite;
        }
        else
        {
            avatarImage.enabled = false;
        }
    }
예제 #35
0
        private IEnumerator DisplaySongs()
        {
            loadedSongs = true;
            JSONObject response = null;

            yield return(StartCoroutine(serviceManager.MakeRequest(RequestType.SongList, value => response = value as JSONObject)));

            if (response != null && response.Count > 0)
            {
                if (!response.HasField("CustomError"))
                {
                    responsePanel.visible = false;

                    int iColor = 0;
                    for (int i = 0; i < response.Count; i++)
                    {
                        GameObject obj = Instantiate(downloadableObjTemplate, rootDownloadsObj);
                        obj.GetComponent <DownloadableSong>().SetSong(response[i], colors[iColor].background, colors[iColor].font);
                        iColor = iColor + 1 < colors.Length ? iColor + 1 : 0;
                        yield return(new WaitForFixedUpdate());
                    }
                }
                else
                {
                    responsePanel.response = "NO INTERNET CONNECTION";
                }
            }
            else
            {
                responsePanel.response = "NO SONGS AVAILABLE";
            }

            TopMenuManager.managerInstance.loadingAnimation = false;
        }
예제 #36
0
 public string GetErrorMessage(JSONObject json)
 {
     if (json.HasField(((int) ParameterCode.Error).ToString()))
     {
         return json.GetField(((int) ParameterCode.Error).ToString()).str;
     }
     return null;
 }
	// 分析位置 包含座標及位置物件
	public static bool ParsePosition( JSONObject _PositionNode , 
									  ref Vector3 _Pos )
	{
		if( true == _PositionNode.HasField( "x" ) &&
			true == _PositionNode.HasField( "y" ) &&
			true == _PositionNode.HasField( "z" ) )
		{
			string strx = _PositionNode.GetField("x").str ;
			string stry = _PositionNode.GetField("y").str ;
			string strz = _PositionNode.GetField("z").str ;
			float x , y , z ;
			float.TryParse( strx , out x ) ;
			float.TryParse( stry , out y ) ;
			float.TryParse( strz , out z ) ;
			_Pos = new Vector3( x , y , z ) ;			
			return true ;
		}
		return false ;
	}
        public static string getConfigValue(string key)
        {
            JSONObject config = new JSONObject(GameConfigData);

            if(config.HasField("key")){
                return config.GetField(key).Print(false);
            }

            return null;
        }
	// 分析旋轉
	public static bool ParseQuaternion( JSONObject _OrientationNode , 
						  				ref Quaternion _Orientation )
	{
		if( true == _OrientationNode.HasField( "x" ) &&
			true == _OrientationNode.HasField( "y" ) &&
			true == _OrientationNode.HasField( "z" ) )
		{		
			string strx = _OrientationNode.GetField("x").str ;
			string stry = _OrientationNode.GetField("y").str ;
			string strz = _OrientationNode.GetField("z").str ;
			float x , y , z ;
			float.TryParse( strx , out x ) ;
			float.TryParse( stry , out y ) ;
			float.TryParse( strz , out z ) ;									
			_Orientation = Quaternion.Euler( -x , -y , -z ) ;
			// Debug.Log( "XMLParseUtilityPartial02:ParseQuaternion() x=" + x + "," + y + ",z" + z ) ;
			return true ;
		}
		return false ;
	}		
    public static void CheckSlotGameConifg()
    {
        JSONObject slotConfigJSON = new JSONObject(GetData("requestConfig"));
        JSONObject localConfigJSON = new JSONObject(System.IO.File.ReadAllText (Application.streamingAssetsPath + "/defaultGameConfig.json"));
        if(slotConfigJSON.HasField("androidSdkConfig") && localConfigJSON.HasField("androidSdkConfig")){
            string slotConfig = slotConfigJSON.GetField("androidSdkConfig").Print(false);
            string localConfig = localConfigJSON.GetField("androidSdkConfig").Print(false);

            if(!localConfig.Equals(slotConfig)){
                UnityEngine.Debug.Log("The local \"defaultGameConfig.json\" file is out-of-sync with the SLOT configuration. Please make sure to update your file with the latest changes from SLOT before building!");
            }
        }
    }
예제 #41
0
        /**
         * Constructor.
         * Generates an instance of <code>MarketItem</code> from a <code>JSONObject</code>.
         *
         * @param jsonObject a <code>JSONObject</code> representation of the wanted
         *                   <code>MarketItem</code>.
         * @throws JSONException
         */
        public MarketItem(JSONObject jsonObject)
        {
            //MarketItem miDeserialized = Newtonsoft.Json.JsonConvert.DeserializeObject<MarketItem>(jsonObject.ToString());
            if (jsonObject.HasField(StoreJSONConsts.MARKETITEM_MANAGED))
            {
                int isManaged = (int)jsonObject[StoreJSONConsts.MARKETITEM_MANAGED].n;
                SoomlaUtils.LogDebug(TAG, isManaged.ToString());
                if (isManaged == 0)
                {
                    this.mManaged = Managed.MANAGED;
                }
                else
                {
                    this.mManaged = Managed.UNMANAGED;
                }

            }
            else
            {
                this.mManaged = Managed.UNMANAGED;
            }
            if (jsonObject.HasField(StoreJSONConsts.MARKETITEM_PRODUCT_ID))
            {
                this.mProductId = jsonObject[StoreJSONConsts.MARKETITEM_PRODUCT_ID].str;
            }
            else
            {
                SoomlaUtils.LogError(TAG, "Market Item No Product ID");
            }
            this.mPrice = (double)jsonObject[StoreJSONConsts.MARKETITEM_PRICE].n;

            this.mMarketPriceAndCurrency = jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICE].str;
            this.mMarketTitle = jsonObject[StoreJSONConsts.MARKETITEM_MARKETTITLE].str;
            this.mMarketDescription = jsonObject[StoreJSONConsts.MARKETITEM_MARKETDESC].str;
            this.mMarketCurrencyCode = jsonObject[StoreJSONConsts.MARKETITEM_MARKETCURRENCYCODE].str;
            this.mMarketPriceMicros = (long)jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICEMICROS].n;

        }
예제 #42
0
        /// <summary>
        /// Constructor.
        /// Generates an instance of <c>MarketItem</c> from a <c>JSONObject<c>.
        /// </summary>
        /// <param name="jsonObject">A <c>JSONObject</c> representation of the wanted 
        /// <c>MarketItem</c>.</param>
        public MarketItem(JSONObject jsonObject)
        {
            string keyToLook = "";
            #if UNITY_IOS && !UNITY_EDITOR
            keyToLook = StoreJSONConsts.MARKETITEM_IOS_ID;
            #elif UNITY_ANDROID && !UNITY_EDITOR
            keyToLook = StoreJSONConsts.MARKETITEM_ANDROID_ID;
            #endif
            if (!string.IsNullOrEmpty(keyToLook) && jsonObject.HasField(keyToLook)) {
                ProductId = jsonObject[keyToLook].str;
            } else {
                ProductId = jsonObject[StoreJSONConsts.MARKETITEM_PRODUCT_ID].str;
            }
            Price = jsonObject[StoreJSONConsts.MARKETITEM_PRICE].n;
            int cOrdinal = System.Convert.ToInt32(((JSONObject)jsonObject[StoreJSONConsts.MARKETITEM_CONSUMABLE]).n);
            if (cOrdinal == 0) {
                this.consumable = Consumable.NONCONSUMABLE;
            } else if (cOrdinal == 1){
                this.consumable = Consumable.CONSUMABLE;
            } else {
                this.consumable = Consumable.SUBSCRIPTION;
            }

            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICE]) {
                this.MarketPriceAndCurrency = jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICE].str;
            } else {
                this.MarketPriceAndCurrency = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETTITLE]) {
                this.MarketTitle = jsonObject[StoreJSONConsts.MARKETITEM_MARKETTITLE].str;
            } else {
                this.MarketTitle = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETDESC]) {
                this.MarketDescription = jsonObject[StoreJSONConsts.MARKETITEM_MARKETDESC].str;
            } else {
                this.MarketDescription = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETCURRENCYCODE]) {
                this.MarketCurrencyCode = jsonObject[StoreJSONConsts.MARKETITEM_MARKETCURRENCYCODE].str;
            } else {
                this.MarketCurrencyCode = "";
            }
            if (jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICEMICROS]) {
                this.MarketPriceMicros = System.Convert.ToInt64(jsonObject[StoreJSONConsts.MARKETITEM_MARKETPRICEMICROS].n);
            } else {
                this.MarketPriceMicros = 0;
            }
        }
예제 #43
0
    private bool CompareJSONCharacterAttributes(JSONObject _member, JSONObject _addition)
    {
        Debug.Log("MEMBER: " + _member.ToString());
        Debug.Log("ADD: " + _addition.ToString());
        if(!_member.HasField("characterName") || !_addition.HasField("characterName"))
        {
            Debug.Log("One of these items isn't a JSON character representation.");
            return false;
        }

        if(_member["characterName"].str == _addition["characterName"].str &&
            _member["characterRace"].str == _addition["characterRace"].str &&
            _member["characterClass"].str == _addition["characterClass"].str)
            return true;

        return false;
    }
예제 #44
0
 public static void SendRewardMessage(JSONObject result, MyMessageScript messageScript, string initialString)
 {
     string rewardString = "";
     if (result.HasField("money"))
     {
         Debug.Log("reward found!");
         float money = result.GetField("money").n;
         string moneyReward = String.Format(StringResources.GetLocalizedString("moneyReward"), money);
         rewardString += moneyReward;
     }
     if (result.HasField("gems"))
     {
         Debug.Log("reward found!");
         float gems = result.GetField("gems").n;
         string gemsReward = String.Format(StringResources.GetLocalizedString("gemsReward"), gems);
         rewardString += gemsReward;
     }
     if (result.HasField("bonus"))
     {
         Debug.Log("reward found!");
         string bonusName = StringResources.GetLocalizedString(result.GetField("bonus").str);
         string bonusReward = String.Format(StringResources.GetLocalizedString("bonusReward"), bonusName);
         rewardString += bonusReward;
     }
     if (result.HasField("tramSkin"))
     {
         Debug.Log("reward found!");
         rewardString += StringResources.GetLocalizedString("tramSkinReward");
     }
     if (result.HasField("conductorSkin"))
     {
         Debug.Log("reward found!");
         rewardString += StringResources.GetLocalizedString("conductorSkinReward");
     }
     if (result.HasField("tramLives"))
     {
         Debug.Log("reward found!");
         float tramLives = result.GetField("tramLives").n;
         rewardString += String.Format(StringResources.GetLocalizedString("tramLivesReward"), tramLives);
     }
     if (rewardString != "")
     {
         initialString += rewardString;
         messageScript.AddMessage(initialString);
     }
 }
예제 #45
0
 /// <summary>
 /// Constructor.
 /// Generates an instance of <c>MarketItem</c> from a <c>JSONObject<c>.
 /// </summary>
 /// <param name="jsonObject">A <c>JSONObject</c> representation of the wanted 
 /// <c>MarketItem</c>.</param>
 public MarketItem(JSONObject jsonObject)
 {
     string keyToLook = "";
     #if UNITY_IOS && !UNITY_EDITOR
     keyToLook = JSONConsts.MARKETITEM_IOS_ID;
     #elif UNITY_ANDROID && !UNITY_EDITOR
     keyToLook = JSONConsts.MARKETITEM_ANDROID_ID;
     #endif
     if (!string.IsNullOrEmpty(keyToLook) && jsonObject.HasField(keyToLook)) {
         ProductId = jsonObject[keyToLook].str;
     } else {
         ProductId = jsonObject[JSONConsts.MARKETITEM_PRODUCT_ID].str;
     }
     Price = jsonObject[JSONConsts.MARKETITEM_PRICE].n;
     int cOrdinal = System.Convert.ToInt32(((JSONObject)jsonObject[JSONConsts.MARKETITEM_CONSUMABLE]).n);
     if (cOrdinal == 0) {
         this.consumable = Consumable.NONCONSUMABLE;
     } else if (cOrdinal == 1){
         this.consumable = Consumable.CONSUMABLE;
     } else {
         this.consumable = Consumable.SUBSCRIPTION;
     }
 }
        public override void Invite(string inviteMessage, string dialogTitle, InviteSuccess success, InviteFailed fail, InviteCancelled cancel)
		{
			FB.AppRequest(inviteMessage, null, null, null, null, "", dialogTitle, 
			              (IAppRequestResult result) => {
				if (result.Error != null) {
					SoomlaUtils.LogError(TAG, "Invite[result.Error]: "+result.Error);
					fail(result.Error);
				}
				else {
					SoomlaUtils.LogDebug(TAG, "Invite[result.Text]: "+result.RawResult);

					JSONObject jsonResponse = new JSONObject(result.RawResult);
					if (jsonResponse.HasField("cancelled")) {
						bool cancelled = jsonResponse["cancelled"].b;
						if (cancelled) {
							cancel();
							return;
						}
					}

					if (jsonResponse.HasField("to")) {
						List<JSONObject> jsonRecipinets = jsonResponse["to"].list;
						List<string> invitedIds = new List<string>();
						foreach (JSONObject o in jsonRecipinets) {
							invitedIds.Add(o.str);
						}
						success(jsonResponse["request"].str, invitedIds);
					}
					else {
						fail("Unable to send invite");
					}
				}
			});
		}
예제 #47
0
	/// <summary>
	/// Merge object right into left recursively
	/// </summary>
	/// <param name="left">The left (base) object</param>
	/// <param name="right">The right (new) object</param>
	static void MergeRecur(JSONObject left, JSONObject right) {
		if(left.type == JSONObject.Type.NULL)
			left.Absorb(right);
		else if(left.type == Type.OBJECT && right.type == Type.OBJECT) {
			for(int i = 0; i < right.list.Count; i++) {
				string key = (string)right.keys[i];
				if(right[i].isContainer){
					if(left.HasField(key))
						MergeRecur(left[key], right[i]);
					else
						left.AddField(key, right[i]);
				} else {
					if(left.HasField(key))
						left.SetField(key, right[i]);
					else
						left.AddField(key, right[i]);
				}
			}
		} else if(left.type == Type.ARRAY && right.type == Type.ARRAY) {
			if(right.Count > left.Count){
				Debug.LogError("Cannot merge arrays when right object has more elements");
				return;
			}
			for(int i = 0; i < right.list.Count; i++) {
				if(left[i].type == right[i].type) {			//Only overwrite with the same type
					if(left[i].isContainer)
						MergeRecur(left[i], right[i]);
					else{
						left[i] = right[i];
					}
				}
			}
		}
	}
예제 #48
0
		public void onGoodUpgrade(string message, bool alsoPush) {
			SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGoodUpgrade:" + message);

			var eventJSON = new JSONObject(message);

			VirtualGood vg = (VirtualGood)StoreInfo.GetItemByItemId(eventJSON["itemId"].str);
			UpgradeVG vgu = null;
			if (eventJSON.HasField("upgradeItemId") && !string.IsNullOrEmpty(eventJSON["upgradeItemId"].str)) {
				vgu = (UpgradeVG)StoreInfo.GetItemByItemId(eventJSON["upgradeItemId"].str);
		  	}

			StoreInventory.RefreshOnGoodUpgrade(vg, vgu);

			StoreEvents.OnGoodUpgrade(vg, vgu);

			if (alsoPush) {
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
				sep.PushEventOnGoodUpgrade(vg, vgu);
#endif
			}
		}
예제 #49
0
	static void MergeRecur(JSONObject left, JSONObject right) {
		if(right.type == JSONObject.Type.OBJECT) {
			for(int i = 0; i < right.list.Count; i++) {
				if(right.keys[i] != null) {
					string key = (string)right.keys[i];
					JSONObject val = (JSONObject)right.list[i];
					if(val.type == JSONObject.Type.ARRAY || val.type == JSONObject.Type.OBJECT) {
						if(left.HasField(key))
							MergeRecur(left[key], val);
						else
							left.AddField(key, val);
					} else {
						if(left.HasField(key))
							left.SetField(key, val);
						else
							left.AddField(key, val);
					}
				}
			}
		}// else left.list.Add(right.list);
	}
예제 #50
0
        /// <summary>
        /// Handles the <c>onMarketPurchaseDeferred</c> event, which is fired when a Market purchase was deferred
        /// until it can be finished by the family delegate.
        /// Note that this is an iOS only event for when users have set up "Ask to Buy" and the purchaser is
        /// selected as a family member that needs "family organizer" permission to buy.
        /// <see href="https://support.apple.com/en-us/HT201089">Apple's explanation of "Ask to Buy"</see>
        /// </summary>
        /// <param name="message">Message that contains information about the market purchase that is being
        /// deferred.</param>
        public void onMarketPurchaseDeferred(string message) {
            SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onMarketPurchaseDeferred: " + message);

            var eventJSON = new JSONObject(message);

            PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(eventJSON["itemId"].str);
            string payload = "";
            if (eventJSON.HasField("payload")) {
                payload = eventJSON["payload"].str;
            }
            StoreEvents.OnMarketPurchaseDeferred(pvi, payload);
        }
예제 #51
0
		public void onItemPurchased(string message, bool alsoPush) {
			SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onItemPurchased:" + message);

			var eventJSON = new JSONObject(message);

			PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(eventJSON["itemId"].str);
			string payload = "";
			if (eventJSON.HasField("payload")) {
				payload = eventJSON["payload"].str;
			}

			StoreEvents.OnItemPurchased(pvi, payload);

			if (alsoPush) {
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
				sep.PushEventOnItemPurchased(pvi, payload);
#endif
			}
		}
예제 #52
0
		/// <summary>
		/// Handles the <c>onMarketPurchase</c> event, which is fired when a Market purchase has occurred.
		/// </summary>
		/// <param name="message">Message that contains information about the market purchase.</param>
		public void onMarketPurchase(string message) {
			Debug.Log ("SOOMLA/UNITY onMarketPurchase:" + message);

			var eventJSON = new JSONObject(message);

			PurchasableVirtualItem pvi = (PurchasableVirtualItem)StoreInfo.GetItemByItemId(eventJSON["itemId"].str);
			string payload = "";
			var extra = new Dictionary<string, string>();
			if (eventJSON.HasField("payload")) {
				payload = eventJSON["payload"].str;
			}
			if (eventJSON.HasField("extra")) {
				var extraJSON = eventJSON["extra"];
				if (extraJSON.keys != null) {
					foreach(string key in extraJSON.keys) {
						if (extraJSON[key] != null) {
							extra.Add(key, extraJSON[key].str);
						}
					}
				}
			}

			StoreEvents.OnMarketPurchase(pvi, payload, extra);
		}
예제 #53
0
    /** Private functions **/
    /**
     * Transforms given JSONObject to StoreInfo
     *
     * @param JSONObject
     * @throws JSONException
     */
    private static void fromJSONObject(JSONObject JSONObject) {

        mVirtualItems = new Dictionary<String, VirtualItem>();
        mPurchasableItems = new Dictionary<String, PurchasableVirtualItem>();
        mGoodsCategories = new Dictionary<String, VirtualCategory>();
        mGoodsUpgrades = new Dictionary<String, List<UpgradeVG>>();
        mCurrencyPacks = new List<VirtualCurrencyPack>();
        mGoods = new List<VirtualGood>();
        mCategories = new List<VirtualCategory>();
        mCurrencies = new List<VirtualCurrency>();
        //mNonConsumables = new List<NonConsumableItem>();
        if (JSONObject.HasField(StoreJSONConsts.STORE_CURRENCIES)) {
            JSONObject virtualCurrencies = JSONObject[StoreJSONConsts.STORE_CURRENCIES];
            for (int i=0; i<virtualCurrencies.Count; i++){
                JSONObject o = virtualCurrencies[i];
                VirtualCurrency c = new VirtualCurrency(o);
                mCurrencies.Add(c);

                mVirtualItems.Add(c.getItemId(), c);
            }
        }

        if (JSONObject.HasField(StoreJSONConsts.STORE_CURRENCYPACKS)) {
            JSONObject currencyPacks = JSONObject[StoreJSONConsts.STORE_CURRENCYPACKS];
            for (int i=0; i<currencyPacks.Count; i++){
                JSONObject o = currencyPacks[i];
                VirtualCurrencyPack pack = new VirtualCurrencyPack(o);
                mCurrencyPacks.Add(pack);

                mVirtualItems.Add(pack.getItemId(), pack);

                PurchaseType purchaseType = pack.GetPurchaseType();
                if (purchaseType is PurchaseWithMarket) {
                    mPurchasableItems.Add(((PurchaseWithMarket) purchaseType)
                            .getMarketItem().getProductId(), pack);
                }
            }
        }

        // The order in which VirtualGoods are created matters!
        // For example: VGU and VGP depend on other VGs
        if (JSONObject.HasField(StoreJSONConsts.STORE_GOODS)) {
            JSONObject virtualGoods = JSONObject[StoreJSONConsts.STORE_GOODS];
            if (virtualGoods.HasField(StoreJSONConsts.STORE_GOODS_SU)) {
                JSONObject suGoods = virtualGoods[StoreJSONConsts.STORE_GOODS_SU];
                for (int i=0; i<suGoods.Count; i++){
                    JSONObject o = suGoods[i];
                    SingleUseVG g = new SingleUseVG(o);
                    addVG(g);
                }
            }


            if (virtualGoods.HasField(StoreJSONConsts.STORE_GOODS_LT)) {
                JSONObject ltGoods = virtualGoods[StoreJSONConsts.STORE_GOODS_LT];
                for (int i=0; i<ltGoods.Count; i++){
                    JSONObject o = ltGoods[i];
                    LifetimeVG g = new LifetimeVG(o);
                    addVG(g);
                }
            }


            if (virtualGoods.HasField(StoreJSONConsts.STORE_GOODS_EQ)) {
                JSONObject eqGoods = virtualGoods[StoreJSONConsts.STORE_GOODS_EQ];
                for (int i=0; i<eqGoods.Count; i++){
                    JSONObject o = eqGoods[i];
                    EquippableVG g = new EquippableVG(o);
                    addVG(g);
                }
            }

            if (virtualGoods.HasField(StoreJSONConsts.STORE_GOODS_PA)) {
                JSONObject paGoods = virtualGoods[StoreJSONConsts.STORE_GOODS_PA];
                for (int i=0; i<paGoods.Count; i++){
                    JSONObject o = paGoods[i];
                    SingleUsePackVG g = new SingleUsePackVG(o);
                    addVG(g);
                }
            }


            if (virtualGoods.HasField(StoreJSONConsts.STORE_GOODS_UP)) {
                JSONObject upGoods = virtualGoods[StoreJSONConsts.STORE_GOODS_UP];
                for (int i=0; i<upGoods.Count; i++){
                    JSONObject o = upGoods[i];
                    UpgradeVG g = new UpgradeVG(o);
                    addVG(g);

                    List<UpgradeVG> upgrades = mGoodsUpgrades[g.getGoodItemId()];
                    if (upgrades == null) {
                        upgrades = new List<UpgradeVG>();
                        mGoodsUpgrades.Add(g.getGoodItemId(), upgrades);
                    }
                    upgrades.Add(g);
                }
            }

        }

        // Categories depend on virtual goods. That's why the have to be initialized after!
        if (JSONObject.HasField(StoreJSONConsts.STORE_CATEGORIES)) {
            JSONObject virtualCategories = JSONObject[StoreJSONConsts.STORE_CATEGORIES];
            for(int i=0; i<virtualCategories.Count; i++){
                JSONObject o = virtualCategories[i];
                VirtualCategory category = new VirtualCategory(o);
                mCategories.Add(category);
                foreach(String goodItemId in category.getGoodsItemIds()) {
                    mGoodsCategories.Add(goodItemId, category);
                }
            }
        }
        /*
        if (JSONObject.TryGetValue(StoreJSONConsts.STORE_NONCONSUMABLES, out value)) {
            JSONObject nonConsumables = JSONObject.Value<JSONObject>(StoreJSONConsts.STORE_NONCONSUMABLES);
            for (int i=0; i<nonConsumables.Count; i++){
                JSONObject o = nonConsumables.Value<JSONObject>(i);
                NonConsumableItem non = new NonConsumableItem(o);
                mNonConsumables.Add(non);

                mVirtualItems.Add(non.getItemId(), non);

                PurchaseType purchaseType = non.GetPurchaseType();
                if (purchaseType is PurchaseWithMarket) {
                    mPurchasableItems.Add(((PurchaseWithMarket) purchaseType)
                            .getMarketItem().getProductId(), non);
                }
            }
        }*/
    }
예제 #54
0
    public static Keyframe ToKeyframe(JSONObject obj)
    {
        var k = new Keyframe(obj.HasField("time") ? obj.GetField("time").n : 0,
            obj.HasField("value") ? obj.GetField("value").n : 0);
        if (obj.HasField("inTangent")) k.inTangent = obj.GetField("inTangent").n;
        if (obj.HasField("outTangent")) k.outTangent = obj.GetField("outTangent").n;
        if (obj.HasField("tangentMode")) k.tangentMode = (int) obj.GetField("tangentMode").n;

        return k;
    }
예제 #55
0
 public static AnimationCurve ToAnimationCurve(JSONObject obj)
 {
     var a = new AnimationCurve();
     if (obj.HasField("keys"))
     {
         JSONObject keys = obj.GetField("keys");
         for (int i = 0; i < keys.list.Count; i++)
         {
             a.AddKey(ToKeyframe(keys[i]));
         }
     }
     if (obj.HasField("preWrapMode"))
         a.preWrapMode = (WrapMode) ((int) obj.GetField("preWrapMode").n);
     if (obj.HasField("postWrapMode"))
         a.postWrapMode = (WrapMode) ((int) obj.GetField("postWrapMode").n);
     return a;
 }
예제 #56
0
	IEnumerator PerformLogin(string username, string password){
		loginStatus = LoginStatus.LoggingIn;
		WWWForm loginForm = new WWWForm();
		loginForm.AddField("username", username);
		loginForm.AddField("unity", 1);
		loginForm.AddField("password", password);
		loginForm.AddField("submitted", 1);
		WWW www = new WWW( LOGIN_URL, loginForm );
		yield return www;
		if(www.error != null){
			Debug.Log("ERROR ON LOGIN: "******"id_u"));
			if(j.HasField("id_u")){
				string uID = j.GetField("id_u").str;
				
				userID = int.Parse(uID);
				Debug.Log("User "+ userID + " has logged In");
				loginStatus = LoginStatus.LoggedIn;
			}
		}
		
		yield return 0;
	}
예제 #57
0
	IEnumerator CreateAccount(string username, string password, string email){

		WWWForm registerForm = new WWWForm();
		registerForm.AddField("username", username);
		registerForm.AddField("email", email);
		registerForm.AddField("password", password);
		registerForm.AddField("submitted", 1);
		WWW www = new WWW( REGISTER_URL, registerForm );
		yield return www;
		if(www.error != null){
			Debug.Log("ERROR ON REGISTRATION: "+ www.error);
		}
		else{
			string encodedString = www.data;
			Debug.Log(encodedString);
			JSONObject j = new JSONObject(encodedString);
			// Debug.Log(j.list);
			// Debug.Log(j.HasField("id_u"));
			if(j.HasField("id_u")){
				string uID = j.GetField("id_u").str;
				Debug.Log(uID);
				userID = int.Parse(uID);
				Debug.Log(userID + ": Registered and Logged In");
				loginStatus = LoginStatus.LoggedIn;
			}
		}

		yield return 0;
	}
예제 #58
0
		private static void fromJSONObject(JSONObject storeJSON)
		{
			VirtualItems = new Dictionary<string, VirtualItem> ();
			PurchasableItems = new Dictionary<string, PurchasableVirtualItem> ();
			GoodsCategories = new Dictionary<string, VirtualCategory> ();
			GoodsUpgrades = new Dictionary<string, List<UpgradeVG>> ();
			CurrencyPacks = new List<VirtualCurrencyPack> ();
			Goods = new List<VirtualGood> ();
			Categories = new List<VirtualCategory> ();
			Currencies = new List<VirtualCurrency> ();
			if (storeJSON.HasField (StoreJSONConsts.STORE_CURRENCIES)) {
				List<JSONObject> objs = storeJSON [StoreJSONConsts.STORE_CURRENCIES].list;
				foreach (JSONObject o in objs) {
					VirtualCurrency c = new VirtualCurrency (o);
					Currencies.Add (c);
				}
			}
			if (storeJSON.HasField (StoreJSONConsts.STORE_CURRENCYPACKS)) {
				List<JSONObject> objs = storeJSON [StoreJSONConsts.STORE_CURRENCYPACKS].list;
				foreach (JSONObject o in objs) {
					VirtualCurrencyPack c = new VirtualCurrencyPack (o);
					CurrencyPacks.Add (c);
				}
			}
			if (storeJSON.HasField (StoreJSONConsts.STORE_GOODS)) {
				JSONObject goods = storeJSON [StoreJSONConsts.STORE_GOODS];
				if (goods.HasField (StoreJSONConsts.STORE_GOODS_SU)) {
					List<JSONObject> suGoods = goods [StoreJSONConsts.STORE_GOODS_SU].list;
					foreach (JSONObject o in suGoods) {
						var c = new SingleUseVG (o);
						Goods.Add (c);
					}
				}
				if (goods.HasField (StoreJSONConsts.STORE_GOODS_LT)) {
					List<JSONObject> ltGoods = goods [StoreJSONConsts.STORE_GOODS_LT].list;
					foreach (JSONObject o in ltGoods) {
						LifetimeVG c = new LifetimeVG (o);
						Goods.Add (c);
					}
				}
				if (goods.HasField (StoreJSONConsts.STORE_GOODS_EQ)) {
					List<JSONObject> eqGoods = goods [StoreJSONConsts.STORE_GOODS_EQ].list;
					foreach (JSONObject o in eqGoods) {
						EquippableVG c = new EquippableVG (o);
						Goods.Add (c);
					}
				}
				if (goods.HasField (StoreJSONConsts.STORE_GOODS_PA)) {
					List<JSONObject> paGoods = goods [StoreJSONConsts.STORE_GOODS_PA].list;
					foreach (JSONObject o in paGoods) {
						SingleUsePackVG c = new SingleUsePackVG (o);
						Goods.Add (c);
					}
				}
				if (goods.HasField (StoreJSONConsts.STORE_GOODS_UP)) {
					List<JSONObject> upGoods = goods [StoreJSONConsts.STORE_GOODS_UP].list;
					foreach (JSONObject o in upGoods) {
						UpgradeVG c = new UpgradeVG (o);
						Goods.Add (c);
					}
				}
			}

			if (storeJSON.HasField(StoreJSONConsts.STORE_CATEGORIES)) {
				List<JSONObject> categories = storeJSON[StoreJSONConsts.STORE_CATEGORIES].list;
				foreach (JSONObject o in categories){
					VirtualCategory category = new VirtualCategory(o);
					Categories.Add(category);
				}
			}

			updateAggregatedLists ();
		}
        private static void ProcessOtherUsersGameStateResponse(JSONObject jsonData)
        {
            JSONObject json = new JSONObject();

            String provider = null;
            if(jsonData.HasField("provider")){
                provider = jsonData.GetField("provider").str;
                json.AddField("provider", provider);
            }

            JSONObject gameStates = null;
            if(jsonData.HasField("gameStates")){
                gameStates = jsonData.GetField("gameStates");
                json.AddField("data", gameStates);
            }

            SpilUnityImplementationBase.fireOtherUsersGameStateLoaded (json.Print (false));
        }
예제 #60
0
        /*---------------------------------------------------------------------------------------*/
        private void jsontest()
        {
            JSONObject j1 = new JSONObject("{\"ID\":1,\"description\":\"descr card 1\",\"name\":\"Nombre1\",\"position\":1,\"stageID\":3,\"teamID\":1}");
            JSONObject j2 = new JSONObject("{\"ID\":2,\"description\":\"descr card 2\",\"name\":\"Nombre card 2\",\"position\":1,\"stageID\":2,\"teamID\":1}");
            JSONObject j3 = new JSONObject("{\"ID\":3,\"description\":\"descr card 3\",\"name\":\"Nombre de la tarjeta 3\",\"position\":2,\"stageID\":3,\"teamID\":2}");
            JSONObject col2 = new JSONObject ("{\"ID\":2,\"cards\":[{\"ID\":2,\"description\":\"descr card 2\",\"name\":\"Seguir con el server\",\"position\":1,\"stageID\":2,\"teamID\":1},{\"ID\":10,\"description\":\"descr card 3\",\"name\":\"Analisis de tecnologias\",\"position\":2,\"stageID\":2,\"teamID\":1},{\"ID\":11,\"description\":\"comentarios, anotaciones y javadoc\",\"name\":\"Documentar código\",\"position\":3,\"stageID\":2,\"teamID\":1}],\"description\":\"descr col 2\",\"name\":\"En progreso\",\"position\":2}");
            JSONObject col3 = new JSONObject("{\"ID\":3,\"description\":\"descr col 3\",\"name\":\"Finalizado\",\"position\":3,\"cards\":[{\"ID\":1,\"description\":\"descr card 1\",\"name\":\"Requisitos iniciales\",\"position\":1,\"stageID\":3,\"teamID\":1},{\"ID\":3,\"description\":\"descr card 3\",\"name\":\"Revisar fechas oficiales\",\"position\":2,\"stageID\":3,\"teamID\":2}]}");

            if(gameObject.name.Equals("ImageTarget 1")){
                string resul = restquery(IP+":"+port+"/board/stage/2");
                JSONObject j2_2 = new JSONObject (resul);
                if(j2_2.HasField("cards")){
                    changeMultipleTexts(j2_2);
                }else changeSimpleText(j2_2);
            }
            else if(gameObject.name.Equals("ImageTarget 2")){
                string resul = restquery(IP+":"+port+"/board/stage/3");
                JSONObject j3_2 = new JSONObject (resul);
                if(j3_2.HasField("cards")){
                    changeMultipleTexts(j3_2);
                }else changeSimpleText(j3_2);
            }
            else{
                changeSimpleText(j1);
            }
        }