1. Home
  2. Docs
  3. UniREST Solution 3.5
  4. Getting Started
  5. What’s new
  6. 3.3

3.3

Version 3.3

UnityWebRequest bug in Unity 2021 and improvements

The UnityWebRequest class is the system that Unity uses for communicating with web servers. Basically, it’s an implementation of the .NET HttpClient class optimized for Unity and it’s used by UniREST for every HTTP transmission.

In Unity 2021, the UnityWebRequest class rises an annoying error in the Console in some circumstances (not always). This is the error:

A Native Collection has not been disposed, resulting in a memory leak. Allocated from:
Unity.Collections.NativeArray`1:.ctor(Byte[], Allocator) …. /NativeArray.cs:69)

Looking at the Unity online manual, they say that for post communications you have to use the Post() method, which requires two parameters; the URL to contact and the data to send:

UnityWebRequest.Post( url, postData )

postData is a mandatory parameter. It can be a string, a list of strings, a WWWForm class instance, etc. However, if you need to send something different or your server-side application has some specific need, you can send raw data as a byte array and, for this scope, you have to use the UploadHandlerRaw() method. This is what UniREST does: it takes your encrypted data, converts it into a byte array and sends it to your Server.

Here is where the error occurs! In UniREST, the post data was declared both in the Post() and the UploadHandlerRaw() methods: in the first method because it’s mandatory, in the second method because the raw format is required. According to the Unity manual, the Post() method automatically creates a UploadHandlerRaw of the postData parameter. Probably, in the previous Unity releases, this worked because the use of the UploadHandlerRaw() method replaced the raw memory filled by the Post() method. Instead, in Unity 2021, something goes wrong.

The solution is pretty easy (even if googling around no one suggested this): to avoid the use of the Post() method and work directly with an instance of the UnityWebRequest class providing only the relevant needed parameters. In UniREST 3.3, this part has been optimized resolving this Unity 2021 issue and ensuring a correct disposing of the involved resources.

In conclusion, in my very personal opinion, I found the combination of the Post() / UploadHandlerRaw() method not so clear. If the postData parameter doesn’t fit my needs and I have to or want to use the UploadHandlerRaw() method, it should be clearer that I have to use an instance and not directly the UnityWebRequest class (as all the manual examples suggest). Or, the Post() method should have a new override for the postData as a byte array.