Search Unity

GameObject.Find is not working

Discussion in 'Scripting' started by Thehopebird, Nov 13, 2017.

  1. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
    Hello.

    Im tryiing to create a multiplayer chat consisting of a server and a client. Im still kind of new to programming so this is the video im following:


    at 3:29 he uses the function GameObject.Find to find a textbox game object and write inside of it.
    It works for him perfectly, but apparently not for me.
    I have attached a picture of my code.
    is there a similar way to do this? I hope someone is able to help and maybe provide an example.

    Thank you very much for helping! :) Screenshot_2.png
     
  2. Blarzek

    Blarzek

    Joined:
    Sep 4, 2017
    Posts:
    4
    Is that GameObject named "HostInput"?
    I need to see your GameObject hierarchy on Unity.

    A similar way to do this is to create a public field on your class and associate it to your GameObject from Inspector on Unity Editor.

    Code (CSharp):
    1. public class MyClass : MonoBehaviour {
    2.     public GameObject hostInput;
    3.  
    4.     ...
    5. }
    Here you can associate your GameObject to this field on your script:

     
    Last edited: Nov 13, 2017
  3. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
  4. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
    My unity does not recognize public GameObject either.. it just stays grey and is not recognized. Thank you for answering
     
  5. Kaart

    Kaart

    Joined:
    Jul 31, 2017
    Posts:
    62
    Make sure you call GameObject.Find from a function in your script, most likely the Start() or Awake() function since GameObject.Find is quite performance heavy (https://docs.unity3d.com/ScriptReference/GameObject.Find.html). Also make sure the GameObjects "HostInput" and "PortInput" are present in your scene hierarchy and have a InputField attached. See the example below how to use GameObject.Find() from the Start() function.

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class FindDemo : MonoBehaviour {  
    5.     string host, h;
    6.     int port, p;
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.         h = GameObject.Find("HostInput").GetComponent<InputField>().text;
    11.  
    12.         if (h != "")
    13.         {
    14.             host = h;  
    15.         }
    16.         int.TryParse(GameObject.Find("PortInput").GetComponent<InputField>().text, out p);
    17.         if (p != 0)
    18.         {
    19.             port = p;
    20.         }
    21.     }
    22. }
     
  6. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
    Thank you for your answer Kaart.
    HostInput and PortInput are in my scene hierarchy and they do have input fields. I tried moving the lines of code to publiv void start() and this does not work either. Its completely greyed our and for some reason it just wont be recognized. Screenshot_4.png
     
  7. Kaart

    Kaart

    Joined:
    Jul 31, 2017
    Posts:
    62
    Did you include UnityEngine?

    Code (CSharp):
    1. using UnityEngine;
     
  8. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
  9. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,292
    Make sure the GameObject is active.

     
  10. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
    Ït's active :(
     
  11. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,292
    Post the full script(in text, not a screenshot) and the error you get when you run it.
     
  12. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
    Heres my code for the client:

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. using System.Net.Sockets;
    7. using System.IO;
    8. using System;
    9. using System.Net;
    10.  
    11.  
    12. public class Client : MonoBehaviour
    13. {
    14.  
    15.     private bool socketReady;
    16.     private TcpClient socket;
    17.     private NetworkStream stream;
    18.     private StreamWriter writer;
    19.     private StreamReader reader;
    20.    
    21.  
    22.    
    23.        public void ConnectToServer()
    24.     {
    25.         //if already connected, ignore this function
    26.         if (socketReady)
    27.         {
    28.             return;
    29.         }
    30.  
    31.         //Deafult host / port values
    32.         string host = "127.0.0.1";
    33.         int port = 6321;
    34.                 //Overwrite default host / port values, if theres is anything in the text boxes
    35.        string h;
    36.         int p;
    37.  
    38.  
    39.         h = GameObject.Find("HostInput").GetComponent<InputField>().text;
    40.         if (h != "")
    41.             host = h;
    42.         int.TryParse(GameObject.Find("PortInput").GetComponent<InputField>().text, out p);
    43.         if (p != 0)
    44.             port = p;
    45.  
    46.         //Create the socket
    47.         try
    48.         {
    49.             socket = new TcpClient(host, port);
    50.             stream = socket.GetStream();
    51.             writer = new StreamWriter(stream);
    52.             reader = new StreamReader(stream);
    53.             socketReady = true;
    54.  
    55.  
    56.         }
    57.         catch(Exception e)
    58.         {
    59.             Debug.Log("Socket error " + e.Message);
    60.  
    61.         }
    62.  
    63.     }
    64.  
    65.     private void Update()
    66.     {
    67.         if (socketReady)
    68.         {
    69.             if (stream.DataAvailable)
    70.             {
    71.                 string data = reader.ReadLine();
    72.                 if (data != null)
    73.                     OnIncomingData(data);
    74.             }
    75.         }
    76.  
    77.     }
    78.     private void OnIncomingData(string data)
    79.     {
    80.         Debug.Log("Server: " + data);
    81.     }
    82. }
    83.  
    Heres's my code for the Server:
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using System.Net.Sockets;
    6. using System;
    7. using System.Net;
    8. using System.IO;
    9.  
    10. public class Server : MonoBehaviour
    11. {
    12.     private List<ServerClient> clients;
    13.     private List<ServerClient> disconnectList;
    14.  
    15.     public int port = 6231;
    16.     private TcpListener server;
    17.     private bool serverStarted;
    18.  
    19.     private void Start()
    20.     {
    21.         clients = new List<ServerClient>();
    22.         disconnectList = new List<ServerClient>();
    23.  
    24.         try
    25.         {
    26.             server = new TcpListener(IPAddress.Any, port);
    27.             server.Start();
    28.  
    29.             StartListenning();
    30.             serverStarted = true;
    31.             Debug.Log("Server has been started on port " + port.ToString());
    32.         }
    33.         catch (Exception e)
    34.         {
    35.             Debug.Log("Socket error:" + e.Message);
    36.         }
    37.  
    38.     }
    39.  
    40.     private void Update()
    41.     {
    42.         if (!serverStarted)
    43.             return;
    44.  
    45.         foreach (ServerClient c in clients)
    46.         {
    47.             //is the client still connected?
    48.             if (!IsConnected(c.tcp))
    49.             {
    50.                 c.tcp.Close();
    51.                 disconnectList.Add(c);
    52.                 continue;
    53.             }
    54.  
    55.             //Check for message from the client
    56.             else
    57.             {
    58.                 NetworkStream s = c.tcp.GetStream();
    59.                 if (s.DataAvailable)
    60.                 {
    61.                     StreamReader reader = new StreamReader(s, true);
    62.                     string data = reader.ReadLine();
    63.  
    64.                     if (data != null)
    65.                         OnIncomingData(c, data);
    66.                 }
    67.             }
    68.         }
    69.     }
    70.  
    71.     private void StartListenning()
    72.     {
    73.         server.BeginAcceptTcpClient(AcceptTcpClient, server);
    74.     }
    75.  
    76.     private bool IsConnected(TcpClient c)
    77.     {
    78.         try
    79.         {
    80.             if (c != null && c.Client != null && c.Client.Connected)
    81.             {
    82.                 if (c.Client.Poll(0, SelectMode.SelectRead))
    83.                 {
    84.                     return !(c.Client.Receive(new byte[1], SocketFlags.Peek) == 0);
    85.                 }
    86.                 return true;
    87.             }
    88.             else return false;
    89.         }
    90.         catch
    91.         {
    92.             return false;
    93.         }
    94.     }
    95.  
    96.     private void AcceptTcpClient(IAsyncResult ar)
    97.     {
    98.         TcpListener listener = (TcpListener)ar.AsyncState;
    99.  
    100.         clients.Add(new ServerClient(listener.EndAcceptTcpClient(ar)));
    101.         StartListenning();
    102.  
    103.         // Send a message to everyone, say someone has connected
    104.         Broadcast(clients[clients.Count - 1].ClientName + "has connected", clients);
    105.     }
    106.  
    107.     private void OnIncomingData(ServerClient c, string data)
    108.     {
    109.  
    110.         Debug.Log(c.ClientName + "has sent the following message: " + data);
    111.     }
    112.     private void Broadcast(string data, List<ServerClient> cl)
    113.     {
    114.         foreach (ServerClient c in cl)
    115.         {
    116.             try
    117.             {
    118.                 StreamWriter writer = new StreamWriter(c.tcp.GetStream());
    119.                 writer.WriteLine(data);
    120.                 writer.Flush();
    121.                                 }
    122.             catch(Exception e)
    123.             {
    124.                 Debug.Log("Write error : " + e.Message + " to client" + c.ClientName);
    125.             }
    126.         }
    127.     }
    128.  
    129. }
    130.  
    131. public class ServerClient
    132. {
    133.     public TcpClient tcp;
    134.     public string ClientName;
    135.  
    136.     public ServerClient(TcpClient clientSocket)
    137.     {
    138.         ClientName = "Guest";
    139.         tcp = clientSocket;
    140.     }
    141.  
    142. }
    My GameObjects are all active etc. So i have no idea why this is not working. I've been following a tutorial where it worked perfectly for the guy who made it.
    This is the error i get when i run it:
    Socket error: was not able to connect since the destination computer actively denied this.

    (the error is translated from danish, so it might not be 100% correct)
     
  13. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,292
    The error looks unrelated to GameObject.Find.
    You have networking problems.

    Socket error: was not able to connect since the destination computer actively denied this.
     
  14. Thehopebird

    Thehopebird

    Joined:
    Nov 8, 2017
    Posts:
    8
    Do you have any suggestions on where in my code this error happens?
    Thank you
     
  15. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    8,292