~ can only be called from the main thread.Constructors and field initializers will be executed from the loading thread when loading a scene.Don't use this function in the constructor or field initializers, inst..
해당이슈는 Unity에서 Main Thread가 아닌곳에서 UnityEngine의 기능을 호출할때 발생하는 이슈이다.
반응형
여러상황에서 발생이 가능한데. 외부 라이브러리 <> Unity 사이에서 발생하는 경우가 종종있다.
Unity 에서 Main Thread를 보장하는곳에서 호출하려면 간단하게 Mono Update에서 호출하거나 Corotine을 통해서 호출하는 방법이 있다.
참고코드
<MobileAdsEventExecutor.cs>
// Copyright (C) 2018 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace GoogleMobileAds.Common
{
public class MobileAdsEventExecutor : MonoBehaviour
{
public static MobileAdsEventExecutor instance = null;
private static List<Action> adEventsQueue = new List<Action>();
private volatile static bool adEventsQueueEmpty = true;
public static void Initialize()
{
if (IsActive())
{
return;
}
// Add an invisible game object to the scene
GameObject obj = new GameObject("MobileAdsMainThreadExecuter");
obj.hideFlags = HideFlags.HideAndDontSave;
DontDestroyOnLoad(obj);
instance = obj.AddComponent<MobileAdsEventExecutor>();
}
public static bool IsActive()
{
return instance != null;
}
public void Awake()
{
DontDestroyOnLoad(gameObject);
}
public static void ExecuteInUpdate(Action action)
{
lock (adEventsQueue)
{
adEventsQueue.Add(action);
adEventsQueueEmpty = false;
}
}
public static void InvokeInUpdate(UnityEvent eventParam)
{
ExecuteInUpdate(() =>
{
eventParam.Invoke();
});
}
public void Update()
{
if (adEventsQueueEmpty)
{
return;
}
List<Action> stagedAdEventsQueue = new List<Action>();
lock (adEventsQueue)
{
stagedAdEventsQueue.AddRange(adEventsQueue);
adEventsQueue.Clear();
adEventsQueueEmpty = true;
}
foreach (Action stagedEvent in stagedAdEventsQueue)
{
if (stagedEvent.Target != null)
{
stagedEvent.Invoke();
}
}
}
public void OnDisable()
{
instance = null;
}
}
}
https://assetstore.unity.com/packages/tools/utilities/thread-dispatcher-202421
★☆☆☆☆
반응형
댓글