"AddComponent with MonoBehaviour is not allowed" error in UnityAds

Hi guys, I’ve got an error that I think is inside the Unity Ads API after updating to the stable build Unity 5.4.0f3.

How do I fix this? Thanks.

I modified AsyncExec.cs to make it work:

#if UNITY_ANDROID || UNITY_IOS

namespace UnityEngine.Advertisements {
  using UnityEngine;
  using System.Collections;

  class CoroutineHost : MonoBehaviour { }

  internal class AsyncExec {
    private static GameObject asyncExecGameObject;
    private static MonoBehaviour coroutineHost;
    private static AsyncExec asyncImpl;
    private static bool init = false;

    private static MonoBehaviour getImpl() {
      if(!init) {
        asyncImpl = new AsyncExec();
        asyncExecGameObject = new GameObject("Unity Ads Coroutine Host") { hideFlags = HideFlags.HideAndDontSave };
        coroutineHost = asyncExecGameObject.AddComponent<CoroutineHost>();
        Object.DontDestroyOnLoad(asyncExecGameObject);
        init = true;
      }

      return coroutineHost;
    }

    private static AsyncExec getAsyncImpl() {
      if(!init) {
        getImpl();
      }

      return asyncImpl;
    }

    public static void runWithCallback<K,T>(System.Func<K,System.Action<T>,IEnumerator> asyncMethod, K arg0, System.Action<T> callback) {
      getImpl().StartCoroutine(asyncMethod(arg0, callback));
    }
  }
}

#endif
3 Likes

Thanks a lot. But this should’ve been fixed by the Unity guys themselves, right? I mean, this is their standart feature and it has errors.

Thank you very much. I was helped.

A great solution. Thank you very much.