-1

I have a program which is searching words in a big sized word list In a game engine uses C# . But my problem is that when the list of words too big UI look seems it was hang. In prevention of it, I use UI so the user will know how many words searching. But the problem is that the UI shows result when searching is already done. How will I let the UI start give info when the user click certain button? Thank you in advance.

    public int searchedTextAmount = 0; 

    void Start()
    {
        int seacrhedTextAmount = 0;
    }

    void Update()
    {
        ui.text = searchedTextAmount;  // when buttonclickevent started, I like this value change while searching process in progress supplied by Search_Method
    }

    void Search_Method()
    {
        foreach (string word in words)
        {
            searchedTextAmount++;
            //someoperations
        }
    }

    void butonclickevent()
    {
        Invoke("Search_Method");
    }
D. GÜL
  • 3
  • 5

1 Answers1

1

You can use a Coroutine in combination with a StopWatch in order to interrupt the search and let one frame render if the searching takes to long.

Something like

// Tweak this according to your needs in the Inspector
[SerializeField] private float targetFramerate = 60f;

private StopWatch sw = new StopWatch();

IEnumerator Search_Method()
{
    // No need for this to be a field
    var searchedTextAmount = 0;
    var total = words.Length;

    // How long one frame may take before we force to render
    // E.g. for 60fps this will 16.66666...
    var millisecondsPerFrame = 1000f / targetFramerate;

    sw.Restart();       

    foreach (string word in words)
    {
        searchedTextAmount++;
        //someoperations

        if(sw.elapsedMilliseconds >= millisecondsPerFrame)
        {
            // This will update the text once a frame (so only when needed) and will look like e.g.
            // "Searching 50/500 (10%)
            ui.text = $"Searching ...  {searchedTextAmount}/{total} ({searchedTextAmount/(float)total:P0})";

            // This tells Unity to "pause" this routine
            // render this frame
            // and continue from here in the next frame
            yield return null;

            sw.Restart();
        }
    }

    sw.Stop();
}

void butonclickevent()
{
    StartCoroutine (Search_Method());
}

So a lower value for targetFrameRate means that your frame-rate during a search process will drop (lag) more. On the other hand a higher targetFrameRate will cause the search take longer in absolute real-time.

derHugo
  • 83,094
  • 9
  • 75
  • 115