• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by 1Jena1 · Apr 16, 2017 at 08:46 AM · c#textexceptionsocketsetc

Load can only be called from the main thread

Load 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.Resources:Load(String) ServerScript:DisplayText(String) (at Assets/ServerScript.cs:129) ServerScript:InitSocket() (at Assets/ServerScript.cs:43)

source is

 public GameObject obj;
 private Text txt;

 // Use this for initialization
 void Start ()
 {
     DisplayText("sdsf");
 }
 
 // Update is called once per frame
 void Update () {
     
 }

 public void ServerOpenButton()
 {
     Thread t = new Thread(InitSocket);
     t.IsBackground = true;
     t.Start();
 }

 TcpListener server = null;
 TcpClient clientSocket = null;
 static int counter = 0;

 public Dictionary<TcpClient, string> clientList = new Dictionary<TcpClient, string>();

 private void InitSocket()
 {
     DisplayText(">> server start");

     server = new TcpListener(IPAddress.Any, 9999);
     clientSocket = default(TcpClient);
     server.Start();

     while (true)
     {
         try
         {
             counter++;
             clientSocket = server.AcceptTcpClient();
             DisplayText(">> client connect.");

             NetworkStream stream = clientSocket.GetStream();
             byte[] buffer = new byte[1024];
             int bytes = stream.Read(buffer, 0, buffer.Length);
             string user_name = Encoding.Unicode.GetString(buffer, 0, bytes);
             user_name = user_name.Substring(0, user_name.IndexOf("$"));

             clientList.Add(clientSocket, user_name);

             // send message all user
             SendMessageAll(user_name + " Joined ", "", false);

             handleClient h_client = new handleClient();
             h_client.OnReceived += new handleClient.MessageDisplayHandler(OnReceived);
             h_client.OnDisconnected += new handleClient.DisconnectedHandler(h_client_OnDisconnected);
             h_client.startClient(clientSocket, clientList);
         }
         catch (SocketException se)
         {
             Trace.WriteLine(string.Format("InitSocket - SocketException : {0}", se.Message));
             break;
         }
         catch (Exception ex)
         {
             Trace.WriteLine(string.Format("InitSocket - Exception : {0}", ex.Message));
             break;
         }
     }

     clientSocket.Close();
     server.Stop();
 }

 void h_client_OnDisconnected(TcpClient clientSocket)
 {
     if (clientList.ContainsKey(clientSocket))
         clientList.Remove(clientSocket);
 }

 private void OnReceived(string message, string user_name)
 {
     string displayMessage = "From client : " + user_name + " : " + message;
     DisplayText(displayMessage);
     SendMessageAll(message, user_name, true);
 }

 public void SendMessageAll(string message, string user_name, bool flag)
 {
     foreach (var pair in clientList)
     {
         Trace.WriteLine(string.Format("tcpclient : {0} user_name : {1}", pair.Key, pair.Value));

         TcpClient client = pair.Key as TcpClient;
         NetworkStream stream = client.GetStream();
         byte[] buffer = null;

         if (flag)
         {
             buffer = Encoding.Unicode.GetBytes(user_name + " says : " + message);
         }
         else
         {
             buffer = Encoding.Unicode.GetBytes(message);
         }

         stream.Write(buffer, 0, buffer.Length);
         stream.Flush();
     }
 }

 public void DisplayText(string text)
 {
     GameObject tmp;
     tmp = (GameObject) Instantiate(Resources.Load("Text"), obj.transform); //this line is 129
     txt = tmp.GetComponent<Text>();
     txt.text = text;
     UnityEngine.Debug.Log(text);
 }

Start -> sdsf print

but button click, and error

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image PizzaPie · Apr 16, 2017 at 10:25 AM 0
Share

Unity api is not thread safe so when you try to use a Unity function (inside DisplayText) ,outside the main thread you end up with the error. Even if you remove the instatiate line the GetComponent will throw an error too as the debug.log will do.

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How to change color of animated Text component 2 Answers

(Unity) My Text UI not updating 1 Answer

Click ui text to dissapear in 3D unity 2017 first person game script for ui multiple texts?,Clicking Text away in Unity 2017 3D first person game 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges