Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

C# - Using Peer-To-Peer server to send messages(strings) to clients.

Discussion in 'Scripting' started by Fuby, Oct 15, 2014.

  1. Fuby

    Fuby

    Joined:
    Mar 26, 2014
    Posts:
    35
    I´m programming a game with the Unity engine using C#. I want users to function as servers or clients and also I want the server to be able to send messages(strings) to the clients. I´ve tried using functions, but of course it didn´t realy work since if have 2 seperate identities. Right now I´m trying to use RCP but it doesn´t seem to work like in the tutorial....I get an compiler error in the Update function. I´ve attached the Network View component (everything else works).



    using UnityEngine;
    using System.Collections;

    and run
    public class NetworkManager : MonoBehaviour
    {
    private int maxConnections = 12;
    private int serverPort = 9955;
    public string message = "NoMessageSelected";
    public bool sendMessage = false;

    public void OnGUI()
    {
    //Creates 2 Buttons on GUI, if disconnected
    if (Network.peerType == NetworkPeerType.Disconnected)
    {
    if (GUI.Button (new Rect (100, 100, 100, 30), "Server"))
    {
    Network.InitializeServer (maxConnections, serverPort);
    }
    if (GUI.Button (new Rect (200, 100, 100, 30), "Client"))
    {
    Network.Connect ("localHost", serverPort);
    }
    }
    ////Shows Client or Server GUI
    //Client
    if (Network.peerType == NetworkPeerType.Client)
    {
    GUI.Label (new Rect (100, 100, 400, 30), "Connected to Server");
    //Disconnect
    if (GUI.Button (new Rect (200, 200, 100, 30), "Disconnect"))
    {
    Network.Disconnect();
    MasterServer.UnregisterHost();
    }
    }
    //Server
    if (Network.peerType == NetworkPeerType.Server)
    {
    GUI.Label (new Rect (100, 100, 400, 30), "Clients connected: " +
    Network.connections.Length);
    message = GUI.TextField(new Rect(150, 150, 200, 20), message, 25);//How to
    receive "message"?
    //Sends message via RPC
    if (GUI.Button (new Rect (200, 200, 100, 30), "Send Message"))
    {
    networkView.RPC ("PrintText", RPCMode.All, "Hello world");
    }
    }
    }


    public void Update()
    {
    Debug.Log (message);
    }

    @RPC
    function PrintText (text : String)
    {
    Debug.Log(text);
    }

    }