기억저장고

UnityEngine.UnityException: IsPersistent can only be called from the main thread.오류해결방법 본문

Unity

UnityEngine.UnityException: IsPersistent can only be called from the main thread.오류해결방법

기억해조 2022. 9. 6. 18:57

WebSocket 통신으로 받은 데이터 처리 시, 메인쓰레드에서만 돌릴 수 있다는 오류가 생길 수 있다.
(UnityEngine.UnityException: IsPersistent can only be called from the main thread.) 

 

[발생한 오류]

Change Color Error : UnityEngine.UnityException: IsPersistent 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, instead move initialization code to the Awake or Start function.
  at (wrapper managed-to-native) UnityEngine.Renderer.IsPersistent(UnityEngine.Renderer)
  at UnityEngine.Renderer.get_material () [0x00001] in <898af1af8ccf490a906c218e1e74b230>:0 
  at ObjectBase.ChangeColor (System.String partName, System.String hexColor, System.String propertiesName) [0x0000a] in D:\MMPSTREAMING\Project\mmpStreamingURP\Assets\01_Script\Base\ObjectBase.cs:157

 


*해결방법
1. UnityMainThread.cs 스크립트 작성(복붙해서 스크립트 제작)

using System;
using System.Collections.Generic;
using UnityEngine;

internal class UnityMainThread : MonoBehaviour
{
    internal static UnityMainThread wkr;
    Queue<Action> jobs = new Queue<Action>();

    void Awake()
    {
        wkr = this;
    }

    void Update()
    {
        while (jobs.Count > 0)
            jobs.Dequeue().Invoke();
    }

    internal void AddJob(Action newJob)
    {
        jobs.Enqueue(newJob);
    }
}

 

2. 오류가 나는 함수에 적용

    public void MyFunction(string partName)
    {
            //아래와 같이 코드 작성
            UnityMainThread.wkr.AddJob(() =>
            {
				//원래 돌려야하는 코드 작성 
				Debug.Log("원래 돌려야하는 코드");
            });
    }

 

출처

https://stackoverflow.com/questions/53916533/setactive-can-only-be-called-from-the-main-thread

 

SetActive() can only be called from the main thread

I am stuck with this problem for 3 days, I did a lot of research, but couldn't find any answer, Here is a brief explanation of what is happening, trying to work with Firebase Database and Authentic...

stackoverflow.com

 

Comments