Creating a Simple Online Chat System in Unity with Fishnet and Playflow Cloud: A Step-by-Step Tutorial

Welcome to the exciting world of game development! In this step-by-step tutorial, we’ll guide you through the process of creating a friendly and interactive online chat system in Unity. What makes this tutorial special is the use of FishNet for networking magic and the PlayFlow Cloud, a fantastic service for seamlessly managing your game’s data in the cloud.

🚀 What You’ll Achieve:

  • Establish a network connection using FishNet, providing a solid foundation for real-time communication.
  • Dive into the PlayFlow Cloud, unlocking the power to store and retrieve chat messages effortlessly.
  • Craft a sleek and user-friendly chat interface using Unity’s intuitive UI tools.

🛠️ Key Steps in the Tutorial:

  1. Setting Up Your FishNet Connection
  2. Making the chat functionality
  3. Exploring PlayFlow Cloud Integration

👩‍💻 Who is This For?

  • Beginners in Unity looking to enhance their skills with real-world projects.
  • Enthusiasts eager to explore the synergy of FishNet and PlayFlow Cloud for seamless networking and cloud functionality.
  • Anyone wanting to add a social and engaging element to their Unity game.

🌟 Why This Tutorial? Unlock the potential of your Unity game by adding a chat system that connects players in a fun and interactive way. Whether you’re creating a multiplayer game or simply want to enhance user engagement, this tutorial is your gateway to building a thriving online community within your project.

👉 Let’s embark on this coding journey together! Get ready to witness the magic of FishNet and the convenience of PlayFlow Cloud as we craft a fantastic online chat experience in Unity. Happy coding! 🎮✨

First of all, Create a new project in unity . Install Fishnet and playflow from unity asset store.


Fishnet : https://assetstore.unity.com/packages/tools/network/fish-net-networking-evolved-207815

Playflow cloud : https://assetstore.unity.com/packages/tools/network/playflow-cloud-206903

Step 1: Follow this tutorial first..
https://youtu.be/g-tGM_n2kR4 (The basic chat system using fishnet)

Step 2: Add a new send message button..

Step 3: Create a panel and put all those chat related things inside it. (Chatbox, messageInput and send button) and make another panel as the start screen and make the username field its child. Add a new button in the new panel for opening the main chat panel.

Step 4: Unpack the network manager prefab and the network Hud canvas. Deactivate the server and client button.

Your hierarchy will look like this,

Step 5: Now modify the “NetworkHudCanvases.cs” script attached in your NetworkHUDCanvases gameobject. Just comment out the OnGUI method.. We don’t need it for now. (Line 86 to 128)

Step 6: Create a new Script “saveText” for saving the username.. and attach it in the “ChatController” GameObject.

saveText.cs

using UnityEngine;
using TMPro;

public class SaveText : MonoBehaviour
{
    public TMP_InputField inputField;

    // This function will be called when a button or an event triggers the save action.
    public void SaveTextToPlayerPrefs()
    {
        // Ensure there is some text entered before saving.
        if (!string.IsNullOrEmpty(inputField.text))
        {
            // Save the text to PlayerPrefs with a key, for example, "SavedText".
            PlayerPrefs.SetString("SavedText", inputField.text);
            PlayerPrefs.Save();

            Debug.Log("Text saved to PlayerPrefs: " + inputField.text);
        }
        else
        {
            Debug.LogWarning("Text input is empty. Nothing saved.");
        }
    }

    // This function will be called during initialization to load the saved text.
    void Start()
    {
        // Retrieve the saved text from PlayerPrefs using the same key.
        if (PlayerPrefs.HasKey("SavedText"))
        {
            string savedText = PlayerPrefs.GetString("SavedText");
            inputField.text = savedText;

            Debug.Log("Text loaded from PlayerPrefs: " + savedText);
        }
    }
}

Your ChatController will look like this:

Modified chatBroadcast Script:

using System;
using UnityEngine;
using FishNet;
using FishNet.Broadcast;
using FishNet.Connection;
using TMPro;
using UnityEngine.Rendering.Universal.Internal;
using UnityEngine.UI;

public class ChatBroadCast : MonoBehaviour
{
    public Transform chatHolder;
    public GameObject msgElement;
    public TMP_InputField userName, message;
    public Button sendButton;

    private void OnEnable()
    {
        InstanceFinder.ClientManager.RegisterBroadcast<Message>(OnMessageReceived);
        InstanceFinder.ServerManager.RegisterBroadcast<Message>(OnClientMessageReceived);
    }

    private void OnDisable()
    {
        if (InstanceFinder.ClientManager!=null)
        {
            InstanceFinder.ClientManager.UnregisterBroadcast<Message>(OnMessageReceived);
        }
        else if (InstanceFinder.ServerManager!=null)
        {
            InstanceFinder.ServerManager.UnregisterBroadcast<Message>(OnClientMessageReceived);
        }
    }

    private void Awake()
    {
        sendButton.onClick.AddListener(SendMessage);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return))
        {
            SendMessage();
        }
    }

    private void SendMessage()
    {
        Message msg = new Message()
        {
            username = userName.text,
            message = message.text
        };
        
        if(InstanceFinder.IsServer)
        {
            InstanceFinder.ServerManager.Broadcast(msg);
        }
        else if(InstanceFinder.IsClient)
        {
            InstanceFinder.ClientManager.Broadcast(msg);
        }
    }

    private void OnMessageReceived(Message message)
    {
        GameObject messageObject = Instantiate(msgElement, chatHolder);
        messageObject.GetComponent<TextMeshProUGUI>().text = message.username + ": " + message.message;
    }

    private void OnClientMessageReceived(NetworkConnection networkConnection, Message message)
    {
        InstanceFinder.ServerManager.Broadcast(message);
    }
    
    public struct Message : IBroadcast
    {
        public string username;
        public string message;
    }
}

Step 7 : Add onClick Events in your start button

Step 8: Add Tugboat component to you Network Manager Gameobject.

Step 9:
– Now its time to Upload our server build to playflow cloud. First select the NetworkHudCanvases and select “Host” in auto start type.

– Open Play flow cloud window. Click on Get token and copy the token from the opened tab in browser and paste it.
– Select server scene. Then press Upload server.
– Then in launch server select location and instance type and then start server.

– Click on Get status button unlit you get an IP address (not 0.0.0.0). When u get an IP address copy it and paste it in your Tugboat component’s client address field.

Step 10: Now in your networkHudCanvases gameobject select Client in auto start .

You are all done.. Make Build and you are test by opening multiple instances of the game build…..

If you need the source code or any help then feel free comment here..

Endless Existence
Endless Existence
Articles: 74

Leave a Reply

Your email address will not be published. Required fields are marked *