• 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
Question by CricketNew10 · Jul 04, 2017 at 08:17 AM · unity 5networkingmultiplayerfloatsendmessage

How to send/receive float values from other online players

I am relatively new in developing online games, so I don't know too much details on the proper methods of setting things up except for the basics. The only issue I've found myself having is being able to send values to other players. I understand how you can make a player lose health when they get hit by a bullet. I want to know how I could share values of players power of attack and then compare that attack with another's. If someone could refer/type just a simple script js/c# of how a float value can be shared with another player online it be extremely helpful, because I've been looking for months and i've yet to find exactly what i'm looking for.

Comment

People who like this

0 Show 0
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

3 Replies

· Add your reply
  • Sort: 
avatar image

Answer by Vollmondum · Jul 04, 2017 at 11:05 AM

You are looking for a purchasing of a server computer with Windows Server installed and constantly running to receive/send data from/to players. Best servers tutorial And since you're saying you're new to online, let it go till have extra $5.000 and extra 1-2 years for learning MySQL to be run on that server.MySQL learning

Another thing is fake online. Create a list of 1000-10000 names and let people think they are online.

Have fun :)

Comment
efge

People who like this

-1 Show 0 · Share
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

Answer by ctalystnetwork · Jul 05, 2017 at 10:19 PM

Multiplayer poses a lot of questions and issues to address.

  • The Load: How many players are you expecting?

  • The Frequency: How often will you be updating the position?

  • The latency: Where in the world will you servers be?

  • Performance: How fast can the server get and send the information

After figuring out what you need here you have to set up a server and set it all up. Now the question that this brings up is is it worth it? Your development costs and learning curve will delay the release of your game and set you back some money. Altho there are other services out there that offer to take care of a lot of the dev for you. Take a look at Amazon, or Unitys Multiplayer

With any set up you will have an operating cost.

Now for my shameless self promotion: take a look at ctalyst to help offset these costs! We're even giving a $100 free for new developers!

Comment

People who like this

0 Show 0 · Share
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

Answer by efeguclu · Jul 06, 2017 at 12:36 AM

CricketNew10

You are In your Lucky Day I'm going to write a script I'm going to use Net.Sockets and NetStreams... First, Create A Script called Server.cs And attach it to an empty gameObject.. Copy Paste this codes into that:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using System.Net.Sockets;
 using System;
 using System.Net;
 using System.IO;
 
 public class Server : MonoBehaviour {
     #region variables
     public int port = 6321;
     public static Server Instance { set; get; }
     private List<ServerClient> clients;
     public List<IPAddress> Hosts;
     private List<ServerClient> disconnectList;
 
     private TcpListener server;
     private bool isServerStarted;
 
     #endregion
 
     private void Start() {
         Instance = this;
     }
     public void Init() {
         DontDestroyOnLoad(gameObject);
         clients = new List<ServerClient>();
         disconnectList = new List<ServerClient>();
 
         try
         {
             server = new TcpListener(IPAddress.Any, port);
 
             server.Start();
             StartListening();
             isServerStarted = true;
         }
         catch (Exception e)
         {
             Debug.Log("Server Açılamadı : " + e.Message);
         }
     }
 
     private void Update() {
         if (!isServerStarted)
             return;
 
         foreach (ServerClient c in clients)
         {
             if (!IsConnected(c.tcp))
             {
                 c.tcp.Close();
                 disconnectList.Add(c);
                 continue;
             }
             else {
                 NetworkStream s = c.tcp.GetStream();
                 if (s.DataAvailable) {
                     StreamReader okuyucu = new StreamReader(s, true);
                     string data = okuyucu.ReadLine();
 
                     if (data != null)
                         OnIncomingData(c, data);
 
                 }
             }
         }
     }
 
     private void StartListening()
     {
         server.BeginAcceptTcpClient(AcceptTcpClient,server);
     }
 
     private void AcceptTcpClient(IAsyncResult ar)
     {
         TcpListener listener = (TcpListener)ar.AsyncState;
 
         string herkes = "";
         foreach (ServerClient i in clients) {
             herkes += i.clientName + "|";
         }
 
         ServerClient sc = new ServerClient(listener.EndAcceptTcpClient(ar));
         clients.Add(sc);
         StartListening();
 
         Broadcast("SCON|" + herkes,clients[clients.Count-1]);
         Debug.Log("Added to clients : " + sc.clientName);
     }
 
 
     private bool IsConnected(TcpClient tcp)
     {
         try {
             if (tcp != null && tcp.Client != null && tcp.Client.Connected)
             {
                 if (tcp.Client.Poll(0, SelectMode.SelectRead))
                     return !(tcp.Client.Receive(new byte[1], SocketFlags.Peek) == 0);
 
                 return true;
             }
             else {
                 return false;
             }
         }
         catch
         {
             return false;
         }
     }
     #region DataSendGet
     private void Broadcast(string data, List<ServerClient> serverClients)
     {
         foreach (ServerClient sc in serverClients)
         {
             try {
                 StreamWriter yazici = new StreamWriter(sc.tcp.GetStream());
                 yazici.WriteLine(data);
                 yazici.Flush();
                 Debug.Log(sc.clientName);
             } catch(Exception e){
                 Debug.Log(e.Message);
             }
         }
     }
     private void Broadcast(string data, ServerClient serverClient)
     {
         List<ServerClient> sc = new List<ServerClient>() { serverClient };
         Broadcast(data, sc);
     }
     private void OnIncomingData(ServerClient c, string data)
     {
         Debug.Log("Server:" + data);
         string[] datalar = data.Split('|');
 
         switch (datalar[0])
         {
             case "CCON":
                 c.clientName = datalar[1];
                 c.isHost = (datalar[2] == "0") ? false : true;
                 if (!clients.Contains(c))
                     clients.Add(c);
 
                 Broadcast("SCNN|" + c.clientName, clients);
                 break;
             case "CMSG":
                 Broadcast("SMSG|" + c.clientName + "|" + datalar[1], clients);
                 break;
         }
     }
     #endregion
 }
 public class ServerClient
 {
     public string clientName;
     public TcpClient tcp;
     public bool isHost;
 
     public ServerClient(TcpClient tcp)
     {
         this.tcp = tcp;
     }
 }

After that Create a script called Client.cs And Attach it to an Empty gameObject.. Copy Paste this codes into client.cs:

 using System.Collections.Generic;
 using UnityEngine;
 using System.IO;
 using System.Net.Sockets;
 using System;
 using UnityEngine.UI;
 
 public class Client : MonoBehaviour {
     #region variables
     public string ClientAD;
     public bool isHost;
     private bool isConnected;
     private TcpClient tcpclient;
     private StreamReader okuyucu;
     private StreamWriter gonderici;
     public NetworkStream netstream;
     public List<Cliente> users = new List<Cliente>();
     #endregion
     private void Start() {
         DontDestroyOnLoad(gameObject);
     }
     public bool ConnectToServer(string host, int port)
     {
         if (isConnected)
             return false;
 
         try
         {
             tcpclient = new TcpClient(host,port);
             netstream = tcpclient.GetStream();
             gonderici = new StreamWriter(netstream);
             okuyucu = new StreamReader(netstream);
 
             isConnected = true;
         }
         catch (Exception e)
         {
             Debug.Log("Baglantı Hatası : " + e.Message);
         }
             
 
         return isConnected;
     }
     private void Update() {
         if (isConnected)
         {
             if (netstream.DataAvailable)
             {
                 string data = okuyucu.ReadLine();
                 if (data != null)
                 {
                     OnIncomingData(data);
                 }
             }
         }
     }
     public void Gonder(string data) {
         if (!isConnected)
             return;
 
         gonderici.WriteLine(data);
         gonderici.Flush();
     }
     private void OnIncomingData(string data) {
         Debug.Log("Client:" + data);
         // EXAMPLE : SMSG|AhmetMehmetVeli|15.0f
         string[] datalar = data.Split('|');
 
         switch (datalar[0])
         {
             case "SCON":
                 for (int i = 1; i < datalar.Length - 1; i++)
                 {
                     UserConnected(datalar[i], false);
                 }
                 Gonder("CCON|"+ClientAD + "|" + ((isHost)?1:0).ToString());
                 break;
             case "SCNN":
                 UserConnected(datalar[1], false);
                 break;
             case "SMSG":
                 string message = datalar[2];
                 float msgFloat = float.Parse(message);
                 ChatManager.Instance.GetChatMessage(msgFloat);
                 break;
         }
     }
     private void UserConnected(string name, bool host) {
         Cliente newclient = new Cliente();
         newclient.clientname = name;
         newclient.isHost = host;
 
         users.Add(newclient);
 
     }
     private void OnApplicationQuit() {
         CloseSocket();
     }
     private void OnDisable() {
         CloseSocket();
     }
     private void CloseSocket() {
         if (!isConnected)
             return;
 
         gonderici.Close();
         okuyucu.Close();
         tcpclient.Close();
         isConnected = false;
 
     }
 }
 public class Cliente
 {
     public string clientname;
     public bool isHost;
 
 }

Now create scene for connecting and u are going to use this public voids.. If you are going to be host and create your server you are going to use HostButton() if you are going to connect to existing host you are going to use ConnectToServer()

     public GameObject serverPrefab, clientPrefab;
 
     public void ConnectToServer() {
         try
         {
             Client c = Instantiate(clientPrefab).GetComponent<Client>();
             c.ClientAD = GameObject.Find("nameField").GetComponent<InputField>().text;
             c.isHost = false;
             if (c.ClientAD == "")
                 c.ClientAD = "Stranger";

             //Under this line you see 127.0.0.1 that is ip you are going to connect and 6321 is the port 
             make sure port is same with host's port...

             c.ConnectToServer("127.0.0.1", 6321);
         }
         catch (Exception e)
         {
             Debug.Log(e.Message);
         }
     }
     public void HostButton() {
         try {
             Server s = Instantiate(serverPrefab).GetComponent<Server>();
             s.Init();
             Client c = Instantiate(clientPrefab).GetComponent<Client>();
             c.ClientAD = GameObject.Find("nameField").GetComponent<InputField>().text;
             c.isHost = true;
             if (c.ClientAD == "")
                 c.ClientAD = "Admin";

                 // this line below you are seeing an ip that is localhost and means your ip you can create 
              host wherever you want and 6321 is port

             c.ConnectToServer("127.0.0.1", 6321);
             Debug.Log("Created Server at port: 6321");
         }
         catch (Exception e) {
             Debug.Log(e.Message);
         }
     }

And finally you are going to take and send values with these lines :

     public static ChatManager Instance { set; get; }
 
     void Start () {
         Instance = this;
         
     }
     public void SendMessage() {
 /* this is you InputField that you are going to write your message if you don't created(You don't have) you can use custom string like : string s = "bla bla bla"*/
         InputField ifield = GameObject.Find("messageField").GetComponent<InputField>();
         if (ifield.text == "")
             return;
 
         string msg = "CMSG|" + ifield.text;
         Client client = FindObjectOfType<Client>();
         client.Gonder(msg);
         ifield.text = "";
     }
     public void GetChatMessage(float value)
     {
         // value = the value that you got from another onlines
 
          
     }



Comment
Bunny83

People who like this

1 Show 3 · Share
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 efeguclu · Jul 05, 2017 at 08:40 PM 0
Share

why don't you look to this answer :P

avatar image Vollmondum efeguclu · Jul 06, 2017 at 10:08 AM 0
Share

Probably because the stuff you posted is meant for 2-3 players, not 50-100k :)

avatar image efeguclu Vollmondum · Jul 06, 2017 at 01:59 PM 0
Share

no it's probaby not because there is a server component if you open in server machine and everyone connects to it. so you could be 100k players if you want

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

175 People are following this question.

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

Related Questions

Unity networking tutorial? 6 Answers

How can a client connect more players to a network game? 1 Answer

WWW Database (SQL?) Speed. 1 Answer

Client side Player prefab spawned by overriding GameManager return false for isLocalPlayer 0 Answers

Online Mulitplayer options in Free Unity 1 Answer


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