Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

OnDestroy not executed Mirror multiplayer

DamastDamast Member
edited May 23 in Programming

~ FIXED: just chaged OnDestroy to OnDisable and it works

Hey, I have a problem:

I'm using the mirror multiplayer package and I've tryed to make a simple chat system.

When I stop the host or client and the Player gameobject gets destroyed, the OnDestroy method does not run . 

Therefore this line of code is also not executed: "OnMessage - = HandleNewMessage", which means that the message is output multiple times when reconnected to a server. 

Thank you in advance!

using Mirror;
using System;
using TMPro;
using UnityEngine;

namespace Menu.Chat
  public class ChatBehaviour : NetworkBehaviour
    //gameobject text to set the text on the screen
    [SerializeField] private TMP_Text chatText = null;
    //gameobject inputField to read the text and reset the textfield
    [SerializeField] private TMP_InputField inputField = null;

    private static event Action<string> OnMessage;

    public void Awake()
      //get UI components
      chatText = GameObject.FindGameObjectWithTag("chatText").GetComponent<TMP_Text>();
      inputField = GameObject.FindGameObjectWithTag("inputField").GetComponent<TMP_InputField>();
    public override void OnStartAuthority()
      OnMessage += HandleNewMessage;

    private void OnDestroy()
      if (!hasAuthority) { return; }
      Debug.Log("has authority",gameObject);
      OnMessage -= HandleNewMessage;

    private void HandleNewMessage(string message)
      Debug.Log("append text to chathistory");
      // append message to chathistorie
      chatText.text += message;

    public void Send(string message)
      //if enter is pressed
      if (!Input.GetKeyDown(KeyCode.Return)) { return; }
      //and message is not null or whitespace
      if (string.IsNullOrWhiteSpace(message)) { return; }
      //tell server to send message
      Debug.Log("Send message: " + message + " to server");
      //clear input field
      inputField.text = string.Empty;

    private void CmdSendMessage(string message)
      //Sever formats message
      RpcHandleMessage($"<color=#881350>[{connectionToClient.connectionId}]:</color> {message}");

    private void RpcHandleMessage(string message)
      //add new line and message on client
      Debug.Log("Reccived message: " + message + " from client");

Best Answer

  • DamastDamast Member
    Accepted Answer

    just chaged OnDestroy to OnDisable andit works

Sign In or Register to comment.