Search Unity

Unity Not Executing Network Commands

Discussion in 'Multiplayer' started by TheUnbangable, Jan 1, 2022.

  1. TheUnbangable

    TheUnbangable

    Joined:
    Jul 21, 2014
    Posts:
    4
    I am making a very simple multiplayer 2D game with 2 players, I decided to make my own networking solution as I have experience in that area, nothing complicated. However, I cannot figure out why unity will not execute the commands I am sending it via UDP.

    I have a gameobject in my scene which I attached the networking code to, the expected behaviour is that I send a "connected" string to Unity (which works fine and Unity reads it properly) but whenever I try to execute ANY Unity function after that, it just does not work. I get no crashes, no error messages, nothing, it just kind of hangs and I am not able to send any more commands either.

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using System.Net;
    4. using System.Text;
    5. using System.Net.Sockets;
    6.  
    7. [RequireComponent(typeof(HostFunctions))]
    8. public class Host : MonoBehaviour
    9. {
    10.     [Header("Network Settings")]
    11.     public string host = "127.0.0.1";
    12.     public int port = 6542;
    13.  
    14.     [Header("Game Settings")]
    15.     public GameObject playerPrefab;
    16.  
    17.     HostFunctions functions;
    18.     UdpClient server;
    19.     IPEndPoint sender;
    20.     const int bufferSize = 1024 * 4;
    21.     byte[] buffer = new byte[bufferSize];
    22.  
    23.     void Start()
    24.     {
    25.         functions = GetComponent<HostFunctions>();
    26.         server = new UdpClient(new IPEndPoint(IPAddress.Parse(host), port));
    27.         sender = new IPEndPoint(IPAddress.Any, 0);
    28.         server.BeginReceive(ReceiveCallback, null);
    29.         Debug.Log("Started listening @ " + server.Client.LocalEndPoint);
    30.     }
    31.  
    32.     void ReceiveCallback(IAsyncResult result)
    33.     {
    34.         buffer = server.EndReceive(result, ref sender);
    35.         string bufString = Encoding.Default.GetString(buffer).Replace("\0", "");
    36.  
    37.         Debug.Log(bufString);
    38.  
    39.         if(bufString.Equals("connected"))
    40.         {
    41.              // This is where the issue occurs, if I remove this line of code, everything will work fine
    42.             // but will not instantiate the playerPrefab object. No other Unity function will work either.
    43.             Instantiate(playerPrefab, new Vector3(1, 0, 0), new Quaternion(0, 0, 0, 0));
    44.         }
    45.  
    46.         server.BeginReceive(ReceiveCallback, null);
    47.     }
    48.  
    49.     void OnApplicationQuit()
    50.     {
    51.         if(server != null)
    52.         {
    53.             server.Close();
    54.             server.Dispose();
    55.         }
    56.     }
    57. }