Addon Realtime Global Chat

If you're looking for custom addons to enhance your game, feel free to reach out! Drop us an email at rafbizachi5@gmail.com with the details of what you need, and we'll gladly provide you with a no-obligation quote.

If you come across any bugs or have suggestions for urgent improvements to this addon, please feel free to reach out via email with the details. I'd greatly appreciate it!

Step-by-Step Guide for Setting Up the Global Chat System in Your Game

Here is a simplified guide to help you configure the Firebase Realtime Database for the Global Chat System, and get everything up and running in your game.


1. Set Up Firebase Realtime Database

Before anything, you'll need a Firebase project for the Realtime Database:

  • Go to Firebase Console.

  • Create a new Firebase project or use an existing one.

  • In the Firebase project dashboard, click on Realtime Database.

  • Select Create Database and follow the prompts to set up your database.

    • Ensure the location is correct for your needs.

    • Start in Test Mode for initial testing.

    • In the rules tab, add the following rule:

{
  "rules": {
    "chat": {
      ".read": "auth != null",
      ".write": "false",
      ".indexOn": ["timestamp"],
      "$messageId": {
        ".write": "auth != null && !data.exists()",
        ".validate": "newData.hasChildren(['playerId', 'playerName', 'iconId', 'frameId', 'message', 'timestamp', 'isHighlighted'])",
        "playerId": {
          ".validate": "newData.isString() && newData.val() === auth.uid" 
        },
        "playerName": {
          ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length <= 50"
        },
        "iconId": {
          ".validate": "newData.isString() && newData.val().length > 0"
        },
        "frameId": {
          ".validate": "newData.isString() && newData.val().length > 0"
        },
        "message": {
          ".validate": "newData.isString() && newData.val().length > 0 && newData.val().length <= 500"
        },
        "timestamp": {
          ".validate": "newData.isNumber() && newData.val() <= now" 
        },
        "isHighlighted": {
          ".validate": "newData.isBoolean()"
        }
      }
    }
  }
}

Create a chat node:


2. Add Firebase Realtime Database SDK to Your Unity Project

If you haven't already:


3. Drag the Global Chat Manager Prefab into Your Scene

Now that Firebase is set up, you can integrate the chat system:

  • In Unity, locate the GlobalChatManager prefab inside the addon folder UIElements.

  • Drag the GlobalChatManager prefab into your main menu canvas.

    • This prefab contains all necessary UI elements for the chat system, including the MiniChat.


6. Set Up a Button to Open the Chat UI

Next, you'll want to allow players to open the chat UI:

  • Create a new UI Button in your scene.

  • In the button’s OnClick() event, call the function:

    GlobalChatManager.OpenUIChat()
    • This will open the chat window when the button is clicked.


7. Add Your Firebase Realtime Database URL

You now need to link the chat system to your Firebase Realtime Database:

  • Select the GlobalChatManager prefab in your scene.

  • In the Inspector, locate the field labeled Database URL.

  • Copy the Realtime Database URL from your Firebase Console:

    • In Firebase, go to Realtime Database > Data and find your database URL at the top (it will look something like https://your-project-id.firebaseio.com/).

  • Paste this URL into the Database URL field in the GlobalChatManager component.


8. Test the Chat System

At this point, the setup should be complete:

  • Run the game in Unity.

  • Click the button to open the chat UI, and you should be able to send messages to the Firebase Realtime Database.

  • The MiniChat should also display recent messages.


9. Ready to Go!

Once the Firebase Realtime Database is connected, the chat system should work out of the box, with the UI already set up and configured.

  • You can adjust the Firebase Realtime Database rules and implement security measures based on your game’s requirements.

That’s it! Your global chat system should now be fully integrated into your game, ready for players to use.

Global Chat Manager Documentation

Overview

The GlobalChatManager is a Unity component that handles a global chat system using Firebase Realtime Database for real-time messaging. It provides functionality for sending, receiving, and displaying chat messages, including the ability to highlight certain messages.

Public Variables

UI Elements

  • UIChat (GameObject): The main UI GameObject for the chat window. You can show or hide this object using custom logic.

  • chatEntryPrefab (ChatEntry): Prefab for chat messages sent by other players. Modify this to change the appearance of other players' messages.

  • playerChatEntryPrefab (ChatEntry): Prefab for chat messages sent by the player themselves. Modify this to change the appearance of the player's messages.

  • chatContainer (Transform): The container where chat messages are instantiated. You can set this to your desired layout for message display.

  • miniChatEntry (MiniChatEntry): A reference for showing a summarized version of the latest message in a mini chat UI.

  • errorMessage (TextMeshProUGUI): A UI text component to display error messages when chat operations fail.

  • messageInputField (TMP_InputField): The input field for typing messages. You can customize the input box according to your game UI.

  • characterCounter (TextMeshProUGUI): Displays the remaining character count as the player types a message. You can style or hide this as needed.

  • scrollRect (ScrollRect): The scrollable area that contains chat messages. Adjust this if you're using a different scrolling system for the chat.

  • sendButton (Button): Button that sends the message when clicked. You can customize its behavior and appearance.

Message Settings

  • maxMessages (int): The maximum number of chat messages fetched from Firebase at once. Developers can adjust this to control how much history is loaded.

  • maxDisplayedMessages (int): The maximum number of messages that can be displayed in the chat UI at once. Adjust this to control the number of messages shown to the player.

  • messageCharacterLimit (int): Limits the number of characters allowed in a single message. You can increase or decrease the limit based on your game's needs.

Anti-Spam Settings

  • messageCooldown (float): The time in seconds the player must wait between sending messages. Adjust this to control spam prevention in the chat.

  • maxMessagesPerMinute (int): Limits the number of messages a player can send per minute. Developers can adjust this to manage the spam and server load.

Highlight Message Settings

  • highlightCurrencyId (string): The in-game currency ID required to highlight a message. This can be customized according to your in-game economy.

  • highlightCurrencyCost (int): The cost to highlight a message. You can modify this to set how expensive it is to highlight a message.

  • highlightToggle (Toggle): A UI toggle that enables or disables message highlighting. Set this to your UI toggle for highlighting.

Firebase Settings

  • databaseURL (string): The URL of your Firebase Realtime Database. Ensure that you correctly set this with your Firebase project's database URL.

Key Methods

OpenUIChat()

Opens the chat UI and loads messages. On the first load, it fetches the chat history from Firebase. After that, it updates the chat with new messages without reloading the full history.

CloseUIChat()

Closes the chat UI. This hides the chat window but does not stop the message updates in the background.

LoadChatHistory()

Fetches the latest chat messages from Firebase. Adjust the maxMessages variable to control how many messages are loaded.

SendMessageToChat()

Sends a message to the Firebase database after performing several validations, such as checking for empty messages, character limit, and anti-spam measures. The function also handles highlighted messages.

UpdateChatUI()

Updates the chat UI with the latest messages. It ensures that no more than maxDisplayedMessages are shown at once and removes old messages if needed.

ScrollToBottom()

Automatically scrolls the chat to the most recent message when new messages are added. Useful for maintaining a user-friendly chat interface.

Firebase Integration

This chat system requires Firebase Realtime Database for real-time messaging. Ensure that Firebase is properly set up with authentication for users. You can customize the Firebase database rules to suit your game's security requirements.

Customization Options

  • Message Prefabs: Customize chatEntryPrefab and playerChatEntryPrefab to change the look of chat messages for both the player and other users.

  • UI Layout: Modify the chatContainer and ScrollRect components to adjust how messages are displayed and scrolled.

  • Anti-Spam: Adjust messageCooldown and maxMessagesPerMinute to fine-tune spam prevention and message rate limits.

  • Highlight Feature: Developers can control the highlight feature through highlightCurrencyId, highlightCurrencyCost, and the highlightToggle. You can also completely disable this feature if not needed.

Error Handling

  • ShowErrorMessage(): Displays error messages in the UI when something goes wrong, such as exceeding message limits or connection issues with Firebase.

Recommendations

  • UI Responsiveness: Ensure that the chat UI scales well across different screen sizes and resolutions by testing it on various devices.

  • Message History: Depending on your game's needs, you may want to periodically clean up older messages in the Firebase database to minimize storage usage.

  • Customization of Firebase Rules: It is recommended to configure Firebase Realtime Database rules carefully to prevent unauthorized access and ensure secure message handling.

If you're looking for custom addons to enhance your game, feel free to reach out! Drop us an email at rafbizachi5@gmail.com with the details of what you need, and we'll gladly provide you with a no-obligation quote.

Last updated