I have GameManager class that has Log method:
using UnityEngine;
using UnityEngine.UI;
public class GameManager: MonoBehaviour {
public static GameManager Instance;
[SerializeField] private ScrollRect m_GUIConsoleContainer;
[SerializeField] private UnityEngine.UI.Text m_GUIConsole;
...
void Awake() {
Instance = this;
}
...
public void Log(string message) {
m_GUIConsole.text = m_GUIConsole.text + message + "\n";
}
}
GameManager class has static instance, so I can invoke Log method in anywhere like this:
GameManager.Instance.Log("Helloworld");
However it works only first time. After invoke Log again, Unity gives me this error message:
get_isActiveAndEnabled 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. UnityEngine.UI.Text:set_text(String)
I assigned reference of m_GUIConsoleContainer and m_GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error.
How should I avoid this error message? Using Unity 2018.2.1f1.
p.s. Error coming from here, another class called NetworkManager:
void OnReceivedBytes(IAsyncResult result) {
try {
if(m_Socket == null) {
return;
}
int resultLength = m_Socket.EndReceive(result);
if(resultLength == 0) {
Shutdown();
return;
}
Log("Received: " + m_RecvBuffer[0]); <<- Error coming from here
...
}
...
}
And this is where it call OnReceivedBytes:
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
public class NetworkManager: MonoBehaviour {
private Socket m_Socket;
void Start() {
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_Socket.Connect("localhost", 1337);
if(m_Socket.Connected) {
Log("Connected.");
m_Socket.BeginReceive(
m_RecvBuffer,
0,
m_RecvBuffer.Length,
SocketFlags.None,
new System.AsyncCallback(OnReceivedBytes),
null
);
}
else {
Log("Failed to Connect.");
}
}
...
}
GameManager.Instance.Log
from? The error might be at the call site, rather than insideGameManager
itself. \$\endgroup\$ – DMGregory♦ Mar 3 '19 at 13:34