I am randomizing an array of strings and writing it to an external file in the system. I am also reading the contents of text file before I write to it so that the no duplicates are found. If there is a duplicate, I am recalling the function to generate a random string. The problem lies here: (a) Once the stack is filled, I get an error message saying StackOverflowException: The requested operation caused a stack overflow. (b) Once the stack is filled, the shuffle function completes the function to generate random string very slow
Is there a better way to achieve what I am doing? Right now it is only 5 array of strings. It could be a thousand later. Should I use List instead of Array?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class GenerateRandomNumber : MonoBehaviour
{
private string[] animals = new string[5] {"Pig", "Dog", "Camel", "Giraffe", "Elephant"};
public string GetAnimal;
public string word;
string path;
void Start()
{
path = "Assets/StreamingAssets/ID.txt";
}
void Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
ShuffleAnimals();
}
}
public void ShuffleAnimals()
{
GetAnimal = animals[Random.Range(0, animals.Length)];
word = File.ReadAllText(path);
if(word.Contains(GetAnimal))
{
ShuffleAnimals();
}
else
File.AppendAllText(path, GetAnimal + System.Environment.NewLine);
}
}
Aucun commentaire:
Enregistrer un commentaire