How to get data for previous button while I am getting details with the next button?

I loading a data initially from a list .The using next button I iterate and get step by step details.Now I want to get previous details using the previous button.

[{"SaveValues":[{"id":1,"allposition":{"x":-3.962002754211426,"y":5.379615783691406},
"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},
{"id":2,"allposition":{"x":-3.95703125,"y":-5.000710487365723},"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":"move1"}]},{"SaveValues":[{"id":1,"allposition":{"x":-3.962002754211426,"y":5.379615783691406},
"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":2.9946722984313967,"y":2.2187490463256838},"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":2,"allposition":{"x":-3.95703125,"y":-5.000710487365723},"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":2,"allposition":{"x":2.3515613079071047,"y":-3.417968988418579},"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":"Move2"}]}]
int n = 0,k=0,counter=1;
int tempvalue;
bool showmsg=false;
int prevcount = 0;
    bool previous = false;

    List<SaveNextValues> savenext = new List<SaveNextValues>();
    List<SaveNextValues> savenextagain = new List<SaveNextValues>();
public struct SaveNextValues
    {
      
        public int counterplus;
        public int tempplus;
        public bool msgvalueplus;
       

        public SaveNextValues(int Counters,int Temps,bool Msgvalue)
        {
          
            this.counterplus = Counters;
            this.tempplus = Temps;
            this.msgvalueplus = Msgvalue;
          
        }


    }
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);


                ShowMessage(0,0);

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

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


        }
        else
        {

            Debug.Log("No file");
        }
      
    }
 public void ShowMessage(int rootvalue,int arrayvalue)
    {
 
        var deseiralized = GetItems.Roots[rootvalue].NoteValues[arrayvalue].notemsg;

        MsgGo.SetActive(true);
        nxtBtn.SetActive(true);
        MsgTxt.text = deseiralized;
        n = GetItems.Roots.Length;
     
        showmsg = false;
     
    }
public void NextHitButton()
    {
      
        if (tempvalue != counter && showmsg==true)
        {
         
            Debug.Log("Value of tempvalue= " + tempvalue);
            ShowMessage(tempvalue, 0);
            //--Added for previous button
         
            return;
        }
        if(showmsg==false)
        {
            MsgGo.SetActive(false);
            for (int k = 0; k < counter; k++)
            {
                    Clearload();
                   // Debug.Log("Latest counter value .." + counter);
                    tempvalue = 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);
                }
                

            }
                counter++;

        
            if (counter > GetItems.Roots.Length)
            {
                    nxtBtn.SetActive(false);
                    Debug.Log("Break .." + counter);
                    //--Counter is set back to 1 to load values again
                    //counter = 1;

            }
                showmsg = true;
            prevBtn.SetActive(true);

//--Trying to save the current values into a list and later take values inside previous button.Wrong code here .
            savenext.Add(new SaveNextValues(counter, tempvalue, showmsg));
            savenextagain = savenext.Where((agr)=>agr.counterplus==counter).Distinct().ToList();
         
        }

    }

    public void PreviousButton()
    {
        Clearload();
        counter = savenextagain[0].counterplus-1 ;
        tempvalue = savenextagain[0].tempplus-1;
        showmsg = !savenext[0].msgvalueplus;
        NextHitButton();
    
    }

You incrementing your counter after next item is displayed and that’s a problem. Initially set your counter to -1. Enable Next button. When next is clicked, increment the counter and check it against array bounds, then call your logic from NextHitButton. And on prev, decrement the counter, check bounds, and call same function again.

my counter needs to start from 1.As I am already calling the 0 th element to showmessage(0,0) inside LoadAllPositions() function.When I hit load button already the first message will be shown from there I need to hit the next button.

It will start from 1, look. Set it to -1 initially to indicate you’re nowhere. Load all data and call showNext. In showNext increment the counter and call the update logic with 0. When user hits next, again increment the counter and call update logic, it will be 1 atm.

Iy look at my logic when I hit next ,it should only increment when showmsg is false.

I see. This is exactly why you have hard time making back button. Move that logic outside of page switching. Only switch pages back and forth if needed. Single responsibility principle is applicable to functional decomposition too, not only to object types.

But I have to show in between.

Inbetween of what? Youre calling showmessage(0,0) after reading whole file, so you can safely move that line out of that function and call it after calling that function if needed. In the end, you should have something like this

   public class Loader : MonoBehaviour
   {
      private List<object> DataFromFile;
      private int CurrentIndex = -1;
     
      private void Start()
      {
         LoadAllData();
         ShowNextMessage();
      }

      private void LoadAllData()
      {
         // here goes your loading function
         DataFromFile = new List<object>() { "HELLO", "WORLD" };
      }

      public void ShowNextMessage()
      {
         CurrentIndex += 1;
        
         if (CurrentIndex >= DataFromFile.Count)
         {
            CurrentIndex = 0;
         }

         ShowMessage();
      }

      public void ShowPrevMessage()
      {
         CurrentIndex -= 1;
        
         if (CurrentIndex < 0)
         {
            CurrentIndex = DataFromFile.Count - 1;
         }

         ShowMessage();
      }

      private void ShowMessage()
      {
         if (DataFromFile.Count > 0)
         {
            // here goes your code setting up that dialog
            Debug.Log(DataFromFile[CurrentIndex]);
         }
      }
   }

Afaik this is the easiest way to make prev/next buttons for pretty much anything and if you try another way it will bring you only more of headache.

It is happening like this,When I click load button.I initially have to show the message at that time the next button is shown on the screen.Now I hit the next button to show the positions.Again I hit the next button to show the message.Again if I click the next button show the positions.Like that it goes.

insidiousellipticalbluewhale Like this.