1
 public void ChangeDailyTasks() { gameManager.ActiveTasks.today = gameManager.DateTimeNow(); gameManager.ActiveTasks.Dailytasks = new List<Task>(); while (gameManager.ActiveTasks.Dailytasks.Count != 5) { var addingTask = gameManager.TaskList[UnityEngine.Random.Range(0, gameManager.TaskList.Count)]; foreach (Task i in gameManager.ActiveTasks.Dailytasks) if (i.name != addingTask.name) gameManager.ActiveTasks.Dailytasks.Add(addingTask); } } 

If I call This function my computer is freezing What i doing is not correctly I just wanna Add 5 new Elements Inside List gameManager.ActiveTasks.Dailytasks. Thank you !

0

1 Answer 1

3

Issue(s)

  • in general rather use <= 5 ... With your current != 5 if for what reason ever your list has 6 or more elements → endless loop!

  • as I see it you are trying to iterate over and add elements to the same collection!

    • First of all this would cause an exception anyway since it is not allowed to modify a collection at the same time while you are iterating it.

    • Secondly it is empty! → The code within foreach is never executed → nothing is ever being added to your list → endless loop!

    I think what you wanted to do would have been something like

     var alreadyAdded = false; foreach (Task i in gameManager.ActiveTasks.Dailytasks) { if (i == addingTask) { alreadyAdded = true; continue; } } if(!alreadyAdded) { gameManager.ActiveTasks.Dailytasks.Add(addingTask); } 

    which can be done way easier using

     if(!gameManager.ActiveTasks.Dailytasks.Contains(addingTask)) { gameManager.ActiveTasks.Dailytasks.Add(addingTask); } 
  • Even if it would work that way (or after the before mentioned code) what if there are not enough Tasks available to get 5 unique ones? → Again endless loop.


Solution

It looks like what you are trying to achieve is having a list with 5 random but unique elements picked from the available ones in gameManager.TaskList.

So instead of a while loop you probably rather want to do

  • randomize the list of available tasks
  • pick 5 of them sequentially

You can do this in a single line using

  • Linq OrderBy with Random.value as order critera
  • followed by Linq Take to pick the first 5 items from the already randomized enumeration → as they are already randomized you can now go sequential

=> You get 5 random unique Tasks (or if not enough are available you get only as many as exist - can be 0).

Something like

using System.Linq; ... public void ChangeDailyTasks() { gameManager.ActiveTasks.today = gameManager.DateTimeNow(); gameManager.ActiveTasks.Dailytasks = gameManager.TaskList.OrderBy(t => Random.value).Take(5).ToList(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.