Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more..
    Dismiss Notice
  3. Dismiss Notice

Delete saved game - updating onClick listeners dynamically

Discussion in 'Scripting' started by ptgodz, Aug 8, 2019.

  1. ptgodz

    ptgodz

    Joined:
    Aug 4, 2016
    Posts:
    106
    Hi, I've implemented Save / load / delete in my game using playerprefs.

    I've got a problem when it comes to the delete function on each saved object. When I fire my delete function, everything works correctly and as expected. However I'm not really sure what's the best way to update the onClick listeners. When I remove an element from my List<SavedGame>, this updates the list and the relevant index for each item. However my listener is still pointing towards a specific index that is no longer correct for some elements. I know I could remove all listeners and then add listeners again to every saved object but is there any other method for saving these files that would suit better? Thanks

    My code looks like this.

    Code (CSharp):
    1. //the saved games i grab from playerprefs that are parsed to list in my start function
    2. public List<SavedGame> savedList;
    3.  
    4. //Vertical layout element to house saveobject prefabs
    5. public GameObject savedGameContainer
    6.  
    7. //Savegame ui prefab
    8. public GameObject savePrefab;
    9.  
    10. private void SetupButtonListeners (){
    11.     for(int i = 0; i < savedList.count; i++){
    12.         int index = i;
    13.         GameObject prefab = Instantiate(savedPrefab, false);
    14.         prefab.GetComponent<Button>().onClick.AddListener(() => {
    15.             DeleteSavedGame(index);
    16.             Destroy(prefab);
    17.       })
    18.    }
    19. }
    20.  
    21. public void DeleteSavedGame(int index){
    22.      savedList.RemoveAt(index);
    23.      //parse list and save to playerprefs below
    24. }
     
  2. ismaelflorit

    ismaelflorit

    Joined:
    Apr 16, 2019
    Posts:
    38
    Have you considered serializing your saved files?

    At minute 32, this video talks about using BinaryFormatter of the System.Runtime.Serialization.Formatters.Binary namespace.
     
  3. ptgodz

    ptgodz

    Joined:
    Aug 4, 2016
    Posts:
    106
    Hi Ismael, So using this solution, I would save each file individually. I suppose this would probably be a better alternative. I'll look into this, thankyou
     
    ismaelflorit likes this.