Home > Software design >  Empty array if strings in c# for unity game
Empty array if strings in c# for unity game

Time:02-26

I am trying to empty and array of strings every-time a user clicks on load profiles so that the array doesn't get over populated with the same profiles over and over again every time they click load.

This is my array:

string[] files;

This is how i get the profiles but i need to empty it whenever getProfiles is called so it doesn't over populate with duplicate profiles

private void GetProfiles()
{
    //Check if directory with saved profiles exists
    if (Directory.Exists(filePath))
    {
        //Clear files array


        //Get all of the file paths of each file in this directory
        files = Directory.GetFiles(filePath);
        //profileTileTemplate.SetActive(true);

        //Go through each file and read the data and create a profile for each json file
        for(int i = 1; i <= files.Length -1; i  )
        {
            string json = File.ReadAllText(files[i]);
            Profile savedProfile = JsonUtility.FromJson<Profile>(json);
            Instantiate(profileTileTemplate,LoadProfileTransform);
            profileTileTemplate.SetActive(true);
            profileTileTemplate.GetComponentInChildren<Text>().text = savedProfile.playerName;
            Debug.Log(savedProfile.playerName);
        }
    }
}

how do i clear this array?

I have tried setting it to null but it doesn't work.

CodePudding user response:

Question is not clear, but if you want to empty the array and stay with the same length then you can write this wherever you want to.

files = new string[files.Length];

CodePudding user response:

as said I don't think this is related to the array at all .. GetFiles everytime returns a new array there are no duplicates.

However, you Instantiate a bunch of objects into the scene and never destroy them!

You could do this first

foreach(Transform child in LoadProfileTransform)
{
    Destroy (child.gameObject);
}
  • Related