For Loop Unity



Jump To:

Visit my website: If you want to learn, how to use C# to create Games with Unity3D, this is the right video-series for you! Use a JavaScript for loop to create multiple primitive objects. Unity Store Vector3 Data Using Json Parsing Which Is Not Possible Using PlayerPrefs; Collision Detection without Rigid body in Unity; How to Reflect a Game Object on Collision: Great Help For Beginners; The Mystery of WaitUntil & WaitWhile in Unity 5.3 Revealed!! ForEach Loop Optimization in Unity. In this video we take a look at how loops work in c# with unity! For more information and in-depth knowledge of C# and Unity, check out The Unity C# Surviva. For loops are a way to perform repetitive tasks. In this video, you'll learn how to setup a loop and run it in code.Interested in game development?

Objective:

The main Objective of this blog post is to explain how to Avoid Usage of ForEach Loop in Unity

This blog post is part of our ongoing Latest Optimization Initiative for Unity Games.

Unity

If you would like to learn how to optimize your games, you can check out this blog post:

Are you noticing some glitches in the gameplay?

Does glitches/ Lag appear while iterating over loops?

Do you have to iterate through list of many GameObjects?

If you have any of the concerns like these, then you have come to the right place!

'Usually Glitches/ LAG during game can occur due to high Garbage Collection in a single frame. So before going ahead let us first understand, What Is Garbage Collection (GC)?' Arcgis torrent download.

Loop

What is Garbage Collection?

  • Garbage collection is an important part of memory management system of any computing device. Its main aim is to attempt to reclaim or free memory occupied by objects that are no longer in use by a program.
  • It is an effective automated system which tries to make sure that unwanted objects do not keep the space occupied, and allow effective and optimized usage of memory. Though it is an automated system, programmers do have some kind of control over it.
  • Usually GC is executed whenever processing power is available and on assurance that the object is no longer going to be used.

SO WHAT DOES THIS HAVE TO DO WITH FOREACH LOOP IN UNITY?

  • To understand this let us take an example
Unity for loop list

Step 1Set up scene in Unity as follow

Take an canvas and take text as shown above.

Take an empty gameobject and rename it to GameObjectList.

Create few other empty gameobjects (about 10-30 would be fine) as its children.

Step 2Create a Script and name it as per your wish

I have named it as ForEachLoopTest.cs

I use C# as my coding preference, you can use javascript if you wish

Note

I have commented for loop code and kept only the forEach Loop active

Step 3Assign References and Test the Code

To Assign References and Test the Code follow the given steps:

  • Attach script to GameObjectList and assign the all empty gameobjects to emptyGameObjects list
  • Now execute the game.
  • Open Profiler Window.
  • Now Press Space button.

Do you notice something in the profiler?

Unity For Each

Check this selected line in the profiler. It shows 40B GC Allocation on every update when the space button is pressed.

Now Stop the game and go back to the script. Comment out the foreach loop part and uncomment for loop part.

As you can see from the code the iteration of the loop will be the same in both the case

Now save and execute the game again and perform the above steps again.

Turn on the profiler and press space button.

Do you notice any change?

NO GC? Magic? Did GC have any other effect on the demo?

HOW DID IT AFFECT MY GAME?

  • You might be shouting.. “HEY WHAT A WASTE OF TIME, I don’t see any change except a number change in the profiler!!”
  • Well in this case you are right, but now imagine there is a case where you have to run through different loops with over 1000’s of iterations, each loop giving out few bytes of GC!
  • This will surely create a glitch in a mobile device with slow processor as memory allocation does take a lot of processing power, especially garbage collection.
  • Now if you don’t take care and continue looping each frame, you will surely end up with not so nice game and destroy your user experience.
  • So avoiding for-each loop would be a wise choice whenever possible.

OKAY MAYBE YOU ARE RIGHT, BUT WHAT IS THE REASON BEHIND THIS GC?

  • So you must be wondering, it’s just a loop! What Garbage (Object) is there to collect from here?

Let us see the syntax first:

Now on compile , complier will preprocess the code into:

WOW! So well, in short here for-each will create an enumerator object on each iteration, the use of those objects die out when iteration gets completed.

Loop

Garbage collector will pounce on first chance it will get to destroy this useless object. Hence resulting in GC and in turn causing the lag/Glitch during game update, irritating the player.

Note

Amount of GC will differ depending on type of collection you are iterating through. In our case it’s a list and shows about 40 Bytes, but this may have been different if I would have used Dictionary or any other such collection.

OH I GET IT NOW!

I hope this is the feeling in your mind on reading this blog post! If you still don’t get it, you can always ask me questions in the comment section. I will surely get back to you for the same. So now conclusion is simple, avoid for-each loop as much as possible in your games. Each small optimization helps in the long run.

'So that’s it for this post! Keep checking our BLOG section. We will keep updating new tips and tricks of optimization. And help you simplify the hard phase of optimization.'

This blog post is part of our ongoing Latest Optimization Initiative for Unity Games.

If you would like to learn how to optimize your games, you can check out this blog post:

Got an Idea of Game Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Unity 3D Game Development Company in India.

Talented Game Developer as well as a player with a mania for video games and the game industry. Always Ready to take up challenging Projects. Proud to be making with the TheAppGuruz Team

PREVIOUS POST
The Roller-Coaster World (and a Story) of Game Designing
NEXT POST
Want To Run Your Games 10x Faster? Here’s How
-->

This topic contains two examples that illustrate the Parallel.For method. The first uses the Parallel.For(Int64, Int64, Action<Int64>) method overload, and the second uses the Parallel.For(Int32, Int32, Action<Int32>) overload, the two simplest overloads of the Parallel.For method. You can use these two overloads of the Parallel.For method when you do not need to cancel the loop, break out of the loop iterations, or maintain any thread-local state.

Note

This documentation uses lambda expressions to define delegates in TPL. If you are not familiar with lambda expressions in C# or Visual Basic, see Lambda Expressions in PLINQ and TPL.

The first example calculates the size of files in a single directory. The second computes the product of two matrices.

Directory size example

This example is a simple command-line utility that calculates the total size of files in a directory. It expects a single directory path as an argument, and reports the number and total size of the files in that directory. After verifying that the directory exists, it uses the Parallel.For method to enumerate the files in the directory and determine their file sizes. Each file size is then added to the totalSize variable. Note that the addition is performed by calling the Interlocked.Add so that the addition is performed as an atomic operation. Otherwise, multiple tasks could try to update the totalSize variable simultaneously.

Matrix and stopwatch example

This example uses the Parallel.For method to compute the product of two matrices. It also shows how to use the System.Diagnostics.Stopwatch class to compare the performance of a parallel loop with a non-parallel loop. Note that, because it can generate a large volume of output, the example allows output to be redirected to a file.

When parallelizing any code, including loops, one important goal is to utilize the processors as much as possible without over parallelizing to the point where the overhead for parallel processing negates any performance benefits. In this particular example, only the outer loop is parallelized because there is not very much work performed in the inner loop. The combination of a small amount of work and undesirable cache effects can result in performance degradation in nested parallel loops. Therefore, parallelizing the outer loop only is the best way to maximize the benefits of concurrency on most systems.

The Delegate

The third parameter of this overload of For is a delegate of type Action<int> in C# or Action(Of Integer) in Visual Basic. An Action delegate, whether it has zero, one or sixteen type parameters, always returns void. In Visual Basic, the behavior of an Action is defined with a Sub. The example uses a lambda expression to create the delegate, but you can create the delegate in other ways as well. For more information, see Lambda Expressions in PLINQ and TPL.

The Iteration Value

The delegate takes a single input parameter whose value is the current iteration. This iteration value is supplied by the runtime and its starting value is the index of the first element on the segment (partition) of the source that is being processed on the current thread.

If you require more control over the concurrency level, use one of the overloads that takes a System.Threading.Tasks.ParallelOptions input parameter, such as: Parallel.For(Int32, Int32, ParallelOptions, Action<Int32,ParallelLoopState>).

Return Value and Exception Handling

For returns a System.Threading.Tasks.ParallelLoopResult object when all threads have completed. This return value is useful when you are stopping or breaking loop iteration manually, because the ParallelLoopResult stores information such as the last iteration that ran to completion. If one or more exceptions occur on one of the threads, a System.AggregateException will be thrown.

In the code in this example, the return value of For is not used.

Analysis and Performance

You can use the Performance Wizard to view CPU usage on your computer. As an experiment, increase the number of columns and rows in the matrices. The larger the matrices, the greater the performance difference between the parallel and sequential versions of the computation. When the matrix is small, the sequential version will run faster because of the overhead in setting up the parallel loop.

Synchronous calls to shared resources, like the Console or the File System, will significantly degrade the performance of a parallel loop. When measuring performance, try to avoid calls such as Console.WriteLine within the loop.

Compile the Code

Unity Foreach Loop

Copy and paste this code into a Visual Studio project.

Unity For Each In List

See also