Arrays from the Unity API

Several instructions within the Unity API result in heap memory allocations, which we should be aware of. This essentially includes everything that returns an array of data. For example, the following methods allocate memory on the heap:

GetComponents<T>(); // (T[])
Mesh.vertices; // (Vector3[])
Camera.allCameras; // (Camera[])

Each and every time we call a Unity API method that returns an array will cause a whole new version of that data to be allocated. Such methods should be avoided whenever possible or at the very least called once and cached so that we don't cause memory allocations more often than necessary.

There are other Unity API calls where we provide an array of elements to a method, and it writes the necessary data into the array for us. One such example is providing a Particle[] array to ParticleSystem to get its Particle data. The benefit of these types of API calls is that we can avoid reallocating large arrays, whereas the downside is that the array needs to be large enough to fit all of the objects. If the number of objects we need to acquire keeps increasing, then we may find ourselves reallocating larger arrays. In the case of ParticleSystem, we need to be certain we create an array large enough to contain the maximum number of Particle objects it generates at any given time.

Unity Technologies have hinted in the past that they may eventually change some of the API calls that return arrays into the form that requires an array to be provided. The API of the latter form can be confusing for new programmers at first glance; however, unlike the first form, it allows responsible programmers to use memory much more efficiently.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.234.62