Как получить данные из списка Json по очереди, используя две кнопки «Следующая» и «Предыдущая»? - PullRequest
0 голосов
/ 02 ноября 2019

Я десериализовал данные из следующего JSON. Я создал JSON, сохранив их. Хотелось бы, чтобы я сохранил в лучшем формате, чтобы я мог легко его извлечь.

[{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,"y":9.267399787902832},
"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},"movetype":1}],"NoteValues":[{"movenumber":1,
"notemsg":"Added one"}]},{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,
"y":9.267399787902832},"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},"movetype":2},{"id":1,
"allposition":{"x":-0.02840942144393921,"y":6.721944808959961},"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},"movetype":2}],"NoteValues":[{"movenumber":2,"notemsg":"Added two"}]},
{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,"y":9.267399787902832},
"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},"movetype":3},{"id":1,"allposition":{"x":-0.02840942144393921,
"y":6.721944808959961},"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},"movetype":3},{"id":1,
"allposition":{"x":-0.10085266828536987,"y":4.49822473526001},"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},"movetype":3}],"NoteValues":[{"movenumber":3,"notemsg":"Added three"}]},
{"SaveValues":[{"id":1,"allposition":{"x":-0.015270888805389405,"y":9.267399787902832},
"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},"movetype":4},{"id":1,"allposition":{"x":-0.02840942144393921,
"y":6.721944808959961},"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},"movetype":4},{"id":1,
"allposition":{"x":-0.10085266828536987,"y":4.49822473526001},"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},"movetype":4},{"id":1,"allposition":{"x":0.17862117290496827,"y":1.5408382415771485},
"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},"movetype":4}],"NoteValues":[{"movenumber":4,
"notemsg":"Added four"}]}]

Так что яя пытаюсь достичь, сначала я нажимаю кнопку загрузки, чтобы загрузить сохраненные данные, которые получают первые данные NoteValues-notemsg в текст и отображают их. Затем, когда я нажимаю кнопку «Далее», он получает значения из SaveValues ​​и загружает данные gameObjectего положение, вращение и т. д. Снова при нажатии кнопки «Далее» нажимается следующее значение NoteValues-notemsg. Снова нажимается кнопка «Далее». Полученные данные сохраняются и помещает игровой объект в эту позицию. Это повторяется.

int counter = 0;
RootObjects GetItems;
int tempvalue;
bool showmsg = true;
ListContainer container;

public void LoadAllPositions(Button b)
{
    SaveValuesDeserialize.Clear();
    NoteValuesDeserialzeList.Clear();

    ClearUserLoaded(getAllPlayers);
    ClearUserLoaded(getAllPlayers2);
    ClearUserLoaded(getAllLines);
    loadpanel.SetActive(false);

    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))
    {
        string jsonLoadstring;
        using (FileStream fs = new FileStream(Application.persistentDataPath + "/" + filename, FileMode.Open))
        {
            fs.Dispose();
            jsonLoadstring = File.ReadAllText(Path.Combine(Application.persistentDataPath, filename));
            Debug.Log("DataJsonRead - - -" + jsonLoadstring);

            string saveString = "{ \"Roots\" : " + jsonLoadstring + "}";
            GetItems = JsonUtility.FromJson<RootObjects>(saveString);
            JSONNode JNode = SimpleJSON.JSON.Parse(jsonLoadstring);

            //—The deserealized JSON data is int the GetItems.Roots.
            //—How to use this list to get values using next button and previous button.
            for (int k = 0; k < GetItems.Roots.Length; k++)
            {
                for (int i = 0; i < GetItems.Roots[k].SaveValues.Length; i++)
                {
                    int id = GetItems.Roots[k].SaveValues[i].id;
                    Vector3 posobj = GetItems.Roots[k].SaveValues[i].allposition;
                    Quaternion rotobj = GetItems.Roots[k].SaveValues[i].allrotation;
                    Vector3 scaleobj = GetItems.Roots[k].SaveValues[i].allscale;
                    Vector3 tempPos0 = GetItems.Roots[k].SaveValues[i].linepos0;
                    Vector3 tempPos1 = GetItems.Roots[k].SaveValues[i].linepos1;
                    int movnos = GetItems.Roots[k].SaveValues[i].movetype;

                    //--Not sure any help with this List
                    SaveValuesDeserialize.Add(new PlayerHandler(id, posobj, rotobj, scaleobj, tempPos0, tempPos1, movnos));
                }

                for (int i = 0; i < GetItems.Roots[k].NoteValues.Length; i++)
                {
                    int movenumber = GetItems.Roots[k].NoteValues[i].movenumber;
                    string messageval = GetItems.Roots[k].NoteValues[i].notemsg;

                    //--Not sure any help with this List
                    NoteValuesDeserialzeList.Add(new PlayerMovement(movenumber, messageval));
                }
            }

             //--inorder to display the message initially
            NextHitButton();

            saveString = "";
            jsonLoadstring = "";
        }

        buttonHolder.SetActive(false);
        Loadedbtn.SetActive(true);
    }
    else
    {
        Debug.Log("No file");
    }
}

public void NextHitButton()
{
    if(showmsg == true)
    {
        MsgGo.SetActive(true);
        string readtxt=NoteValuesDeserialzeList[counter].notemsg;
        MsgTxt.text = readtxt;
        TTSTest.TTsInstance.StartTalking(readtxt);
        nxtBtn.SetActive(true);

        showmsg = false;
    }
    else
    {
        MsgGo.SetActive(false);

        for (int k = 0; k < counter+1; k++)
        {

            Debug.Log("Loop counter " + counter);
            for (int i = 0; i < GetItems.Roots[k].SaveValues.Length; i++)
            {
                int id = GetItems.Roots[k].SaveValues[i].id;
                Vector3 posobj=GetItems.Roots[k].SaveValues[i].allposition;
                Quaternion rotobj=GetItems.Roots[k].SaveValues[i].allrotation;
                Vector3 scaleobj=GetItems.Roots[k].SaveValues[i].allscale;
                GameObject go = null;

                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 = GetItems.Roots[k].SaveValues[i].linepos0;
                    Vector3 tempPos1 = GetItems.Roots[k].SaveValues[i].linepos1;
                    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);
                    Vector3 pos =  (tempPos0 + tempPos1) * 0.5f ;
                     GameObject gg=  Instantiate(CapsuleCol,pos,Quaternion.identity);
                    gg.transform.SetParent(InstantiatedParent);
                    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.GetComponent<PlayerMove>().enabled = false;
                }


                go.transform.position = posobj;
                go.transform.rotation = rotobj;
                go.transform.localScale = scaleobj;
                allreadyLoaded.Add(go);
            }
        }
         //—If the counter value is greater then hide the next button.
        if (counter >= GetItems.Roots.Length - 1)
        {
            nxtBtn.SetActive(false);
            showmsg = true;
            return;
        }
        showmsg = true;
        prevBtn.SetActive(true);

        counter++;
    }
}

public void PreviousButton()
{
    Debug.Log("previous msgval " + showmsg);
    if (showmsg == true)
    {
        NextHitButton();
    }
    else
    {
        Clearload();
        counter--;
        MsgGo.SetActive(false);

   }
}

Приведенный выше код состоит из трех разделов. Загрузка данных, операция «Следующая кнопка» и операция «Предыдущая кнопка». Что мне нужно сделать, чтобы легко решить ее. Если бы я получил его в виде одного списка, то было бы легко догадаться. Мне удалось заставить работать следующую кнопку. но когда я применяю логику предыдущей кнопки, следующая кнопка перестает работать.

Следующая работа

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