Search Unity

Delete Saved Game Data

Discussion in 'Scripting' started by mschoenhals, Jan 18, 2020.

  1. mschoenhals

    mschoenhals

    Joined:
    Dec 18, 2016
    Posts:
    6
    Hi,
    I've put together an inventory system that saves at checkpoints (based on a tutorial I found online). I'm trying to now create a method to delete the saved data when creating a new game.

    How would I go about deleting the old data?

    Here is my ItemSaveIO:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public static class ItemSaveIO
    4. {
    5.     private static readonly string baseSavePath;
    6.  
    7.     static ItemSaveIO()
    8.     {
    9.         baseSavePath = Application.persistentDataPath;
    10.     }
    11.  
    12.     public static void SaveItems(ItemContainerSaveData items, string path)
    13.     {
    14.         FileReadWrite.WriteToBinaryFile(baseSavePath + "/" + path + ".dat", items);
    15.     }
    16.  
    17.     public static ItemContainerSaveData LoadItems(string path)
    18.     {
    19.         string filePath = baseSavePath + "/" + path + ".dat";
    20.  
    21.         if (System.IO.File.Exists(filePath))
    22.         {
    23.             return FileReadWrite.ReadFromBinaryFile<ItemContainerSaveData>(filePath);
    24.         }
    25.         return null;
    26.     }
    27. }
     
  2. Olipool

    Olipool

    Joined:
    Feb 8, 2015
    Posts:
    322
    The quickest idea I got would be to save the items but remove all items first. I don't know what ItemContainerSaveData is but probably you can add and remove items there? If you remove all of them then zero items will overwrite the old save.
    If you want to delete the whole file, you can try using System.IO.File.Delete(baseSavePath+"/"+path+".dat")
    (https://docs.microsoft.com/en-us/dotnet/api/system.io.file.delete?view=netframework-4.8)
     
    AnaLuyza and rockemgame like this.