Как загрузить выбранные данные из массива данных JSON, а затем, нажав кнопку «Далее», загрузить другие данные? - PullRequest
0 голосов
/ 16 октября 2019

Я сохраняю сведения о положении, повороте и т. Д. Различных объектов GameObject в формате JSON в постоянном пути данных приложения. Я делюсь кодом для метода, используемого для сохранения данных, и класс приведен ниже.

//Adding Data
public void AddMoveDetails()
{

    Debug.Log("saving");
    getAlldata.Clear();

    //--Getting the value from InputFields to save for moveno: and notes
    int datanum = int.Parse(moveNumField.GetComponent<InputField>().text);
    string notedata = noteField.GetComponent<InputField>().text;

    for (int i = 0; i < getAlldata.Count; i++)
    {
        getAlldata.RemoveAt(i);
    }

    //--Loading player1 data into list
    for (int i = 0; i < getAllPlayers.Count; i++)
    {
        getAlldata.Add(new PlayerHandler(1, getAllPlayers[i].transform.position, getAllPlayers[i].transform.rotation,
                                         getAllPlayers[i].transform.localScale, Vector3.zero, Vector3.zero,datanum));


    }

    //--Loading player2 data into list
    for (int i = 0; i < getAllPlayers2.Count; i++)
    {
        getAlldata.Add(new PlayerHandler(2, getAllPlayers2[i].transform.position, getAllPlayers2[i].transform.rotation,
                                         getAllPlayers2[i].transform.localScale, Vector3.zero, Vector3.zero,datanum));

       ;
    }

    //--Loading No:of football data into list
    for (int i = 0; i < getAllFootball.Count; i++)
    {
        getAlldata.Add(new PlayerHandler(4, getAllFootball[i].transform.position, getAllFootball[i].transform.rotation,
                                         getAllFootball[i].transform.localScale, Vector3.zero, Vector3.zero,datanum));

    }



    // --Loading No: of Lines data into list
    for (int i = 0; i < LinePositions0.Count;i++)
    {

        getAlldata.Add(new PlayerHandler(3,Vector3.zero, Quaternion.identity, Vector3.zero,LinePositions0[i],LinePositions1[i],datanum));

    }



    //for (int i = 0; i < getAlldata.Count; i++)
    //{
    //    //  showAlldata = getAlldata.Where((arg) => arg.id == 1).ToList();
    //    Debug.Log("Get All data = " + getAlldata[i]);
    //}



    playerNotes.Add(new PlayerMovement(datanum,notedata));
    ListContainer container = new ListContainer(getAlldata,playerNotes);

    //--Adding data in container into List<string> jsonstring
    jsonstring.Add(JsonUtility.ToJson(container));


    saveButtonShow.SetActive(false);

    moveNumField.text = "";
    noteField.text = "";

}

public void Save()
{


    //--Get Text typed in the input box
    savedName = saveName.text;

    //--Combing list of string into a single string
    string jsons = string.Join(",", jsonstring);

    //Writing into a JSON file in the persistent path
    using (FileStream fs = new FileStream(Application.persistentDataPath + "/" + savedName+".json" , FileMode.Create))
    {
        BinaryWriter filewriter = new BinaryWriter(fs);

        filewriter.Write(jsons);
        fs.Close();

    }

    saveButtonShow.SetActive(false);

}

Класс, указанный ниже

[System.Serializable]
public class PlayerHandler 
{
public int id; 
public Vector2 allposition;
public Quaternion allrotation;
public Vector2 allscale;

public Vector3 linepos0;
public Vector3 linepos1;
public int movetype;

public PlayerHandler(int ids,Vector2 allpos,Quaternion allrot,Vector2 allscal,Vector3 Line0,Vector3 Line1,int Moves)

{
    this.id = ids;
    this.allposition = allpos;
    this.allrotation = allrot;
    this.allscale = allscal;
    this.linepos0 = Line0;
    this.linepos1 = Line1;
    this.movetype = Moves;
}

}

[System.Serializable]
public class PlayerMovement
{
public int movenumber;
public string notemsg;
public PlayerMovement(int Movenum,string Note)
{
    this.movenumber = Movenum;
    this.notemsg = Note;

}

}

После использования вышеописанного метода сохранения я получаю данные JSON, приведенные ниже.

{


"SaveValues":[
      {
         "id":1,
         "allposition":{
            "x":-1.5170230865478516,
            "y":6.489965915679932
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":1,
         "allposition":{
            "x":4.076644420623779,
            "y":5.852467060089111
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":2,
         "allposition":{
            "x":-3.0194902420043947,
            "y":-2.64868426322937
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":2,
         "allposition":{
            "x":3.249917984008789,
            "y":-4.824670791625977
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":4,
         "allposition":{
            "x":0.1149669885635376,
            "y":0.6910357475280762
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      }
   ],
   "NoteValues":[
      {
         "movenumber":1,
         "notemsg":"Pass to Left first"
      }
   ]
},
{
   "SaveValues":[
      {
         "id":1,
         "allposition":{
            "x":-1.5170230865478516,
            "y":6.489965915679932
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":1,
         "allposition":{
            "x":4.076644420623779,
            "y":5.852467060089111
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":1,
         "allposition":{
            "x":-0.277055561542511,
            "y":8.918830871582032
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":1,
         "allposition":{
            "x":-4.2421875,
            "y":3.5467114448547365
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":1,
         "allposition":{
            "x":2.872697353363037,
            "y":2.4352784156799318
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":2,
         "allposition":{
            "x":-3.0194902420043947,
            "y":-2.64868426322937
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":2,
         "allposition":{
            "x":3.249917984008789,
            "y":-4.824670791625977
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":2,
         "allposition":{
            "x":-0.6722860336303711,
            "y":-5.846545219421387
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":2,
         "allposition":{
            "x":-0.2020561695098877,
            "y":-9.395970344543457
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      },
      {
         "id":4,
         "allposition":{
            "x":0.1149669885635376,
            "y":0.6910357475280762
         },
         "allrotation":{
            "x":0.0,
            "y":0.0,
            "z":0.0,
            "w":1.0
         },
         "allscale":{
            "x":1.0,
            "y":1.0
         },
         "linepos0":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         },
         "linepos1":{
            "x":0.0,
            "y":0.0,
            "z":0.0
         }
      }
   ],
   "NoteValues":[
      {
         "movenumber":1,
         "notemsg":"Pass to Left first"
      },
      {
         "movenumber":2,
         "notemsg":"Pass to right the move forward"
      }
   ]
}

Ниже приведен код для загрузки всех данных изJSON и создание экземпляра Gameobject для положения, поворота и т. д., аналогичных сохраненным в файле JSON.

public void LoadAllPositions(Button b)
{

    ClearUserLoaded(getAllPlayers);
    ClearUserLoaded(getAllPlayers2);
    ClearUserLoaded(getAllLines);


    Debug.Log("index button value = " + b.transform.parent.transform.GetSiblingIndex());
    int index = b.transform.parent.transform.GetSiblingIndex();
    var filename = listLoaditems[index].transform.GetChild(1).GetComponent<Text>().text;
    Debug.Log("filename is pos : " + filename);

    //--Loading File by name
    if (File.Exists(Application.persistentDataPath + "/" + filename))
    {



        //Debug.Log("FileName is === " + filename);

        GameObject go = null;
        string jsonLoadstring;
        using (FileStream fs = new FileStream(Application.persistentDataPath + "/" + filename, FileMode.Open))
        {

            BinaryReader filereader = new BinaryReader(fs);
            jsonLoadstring = filereader.ReadString();
            fs.Close();
            Debug.Log("JsonLoaded String==" + jsonLoadstring);

            JSONNode JNode = SimpleJSON.JSON.Parse(jsonLoadstring);
            Debug.Log("Jnode --- " +JNode["SaveValues"].Count);



            Debug.Log("Save value count = "+JNode["SaveValues"][0].Count);

          //--Retrieving All data,loading and Instantiating GameObjects into the saved position
           for (int i = 0;i<JNode["SaveValues"][0]["id"].Count;i++)
            {
                 Debug.Log("Jnode values " + JNode["SaveValues"][i].ToString());

                int id = JNode["SaveValues"][i]["id"];
                Vector3 posobj =new Vector3 (JNode["SaveValues"][i]["allposition"]["x"],JNode["SaveValues"][i]["allposition"]["y"],JNode["SaveValues"][i]["allposition"]["z"]);
                Quaternion rotobj = new Quaternion(JNode["SaveValues"][i]["allrotation"]["x"], JNode["SaveValues"][i]["allrotation"]
                                                   ["y"], JNode["SaveValues"][i]["allrotation"]["z"], JNode["SaveValues"][i]["allrotation"]["w"]);
                Vector3 scaleobj = new Vector3(JNode["SaveValues"][i]["allscale"]["x"], JNode["SaveValues"][i]["allscale"]["y"],
                                              JNode["SaveValues"][i]["allscale"]["z"]);


                if(id==1)
                {

                    go=  Instantiate(players1,SpriteLoadParent);
                    go.GetComponent<PlayerMove>().enabled = false;
                }
                else if(id==2)
                {
                    go = Instantiate(players2,SpriteLoadParent);
                    go.GetComponent<PlayerMove>().enabled = false;
                }
                else if(id==3)
                {
                    Vector3 tempPos0 = new Vector3(JNode["SaveValues"][i]["linepos0"]["x"], JNode["SaveValues"][i]["linepos0"]["y"], JNode["SaveValues"][i]["linepos0"]["z"]);
                    Vector3 tempPos1 = new Vector3(JNode["SaveValues"][i]["linepos1"]["x"], JNode["SaveValues"][i]["linepos1"]["y"], JNode["SaveValues"][i]["linepos1"]["z"]);
                    go = Instantiate(linePrefab,SpriteLoadParent);

                    NewLine = go.GetComponent<LineRenderer>();
                    NewLine.SetPosition(0, tempPos0);
                    NewLine.SetPosition(1, tempPos1);

                    GameObject gameObject = Instantiate(Arrowhead,SpriteLoadParent);
                    gameObject.transform.position = NewLine.GetPosition(1);

                    gameObject.transform.rotation = Quaternion.LookRotation(NewLine.GetPosition(1) - NewLine.GetPosition(0), Vector3.back);
                   //Debug.Log("InstaPos = " +go.transform.position.x + ":"+go.transform.position.y+" : "+go.transform.position.z);
                    Vector3 pos =  (tempPos0 + tempPos1) * 0.5f ;
                     GameObject gg=  Instantiate(CapsuleCol,pos,Quaternion.identity);
                    gg.transform.SetParent(LineParent);
                    gg.transform.LookAt(tempPos1);

                    gg.GetComponent<CapsuleCollider>().height = Vector3.Distance(tempPos0, tempPos1);
                    gg.GetComponent<CapsuleCollider>().radius =0.2f;


                }
                else if(id==4)
                {
                    go = Instantiate(football, SpriteLoadParent);
                }

                go.transform.position = posobj;
                go.transform.rotation = rotobj;
                go.transform.localScale = scaleobj;
                allreadyLoaded.Add(go);

                //DeserialzeList.Add(new PlayerHandler(id, posobj, rotobj, scaleobj));




            }


            Debug.Log("Go Count = " + allreadyLoaded.Count);

        }

        loadpanel.SetActive(false);
        buttonHolder.SetActive(false);
        Loadedbtn.SetActive(true);


    }
    else
    {

        Debug.Log("No file");
    }

}

Здесь я загружаю все данные, вместо этого я хочу первоначально показать содержимое в первом массиве «NoteValues»,затем после нажатия кнопки OK Я хочу загрузить только первый массив «SaveValues», затем нажмите кнопку NEXT , чтобы отобразить второй массив «NoteValues», затем после нажатия кнопки OK показывать второй массив «SaveValues» и т. Д. Короче говоря, используйте кнопку для получения данных по разделам при нажатии на них.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...