[Admob + PlayerPrefs] => TrySetInt can only be called from the main thread

Hello!

I have a button in my game which on click shows an rewarded video ad.
After user watch the ad, a callback function is executed. Inside it I try to set a value with PlayerPrefs.SetInt.
The problem appear at that line, in android monitor I receive TrySetInt can only be called from the main thread
alt text

Almost all methods of the Unity API are not thread safe and can only be called from the main thread. (Almost) all callbacks you get from Unity directly are executed from the main thread. However your “ad” framework most likely calls it’s callbacks on a seperate thread. Inside such a method you can’t use the Unity API. This includes PlayerPref.SetInt which is causing the error in your case, but also SceneManager.LoadScene.

If you work with threads you have multiple options how to handle this problem. The easiest way is to set a boolean value to true in the callback and check that boolean in Update. When it’s true do whatever you wanted to do in the callback and set the bool back to false.

Another way is to use a scheduler that can queue a task on the main thread from any other thread. For example Whydoidoit’s Loom class

This is just for any one who visits here in future. I also ran in the same issue and here is the approach I used to solve my issue. This will work just with simple Coroutines. Check the answer and my comment below. Thanks.

http://answers.unity.com/answers/1747811/view.html