using Mirror;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class Sent_Messages : NetworkBehaviour
{
[Header("简单聊天设置")]
private TMP_InputField chatInput;
private Text chatDisplay;
public int maxMessages = 10;
/*
OnStartServer() - 只在服务器执行
OnStartClient() - 在每个客户端执行
OnStartLocalPlayer() - 只在本地玩家执行
OnStartAuthority() - 当获得权限时执行
*/
public override void OnStartLocalPlayer()
{
chatInput = GameObject.FindGameObjectWithTag("ChatInput").GetComponent<TMP_InputField>();
chatDisplay = GameObject.FindGameObjectWithTag("ChatDisplay").GetComponent<Text>();
if (chatInput != null && chatDisplay != null)
{
Debug.Log("正常,不为空");
}
else if (chatInput != null)
{
Debug.Log("不正常,chatInput = null");
}
else if (chatDisplay != null)
{
Debug.Log("不正常,chatDisplay = null");
}
}
// 存储聊天记录
private string chatHistory = "";
void Update()
{
}
public void SendMessage()
{
if (chatInput == null)
{
Debug.Log("chatInput为null");
}
if (!gameObject.activeInHierarchy)
{
Debug.LogError($"玩家对象 {gameObject.name} 被禁用,无法发送消息");
}
// 检查 NetworkIdentity 是否存在
// 第52行之前添加安全检查
if (netIdentity == null)
{
Debug.LogError("NetworkIdentity 为 null,对象可能未正确初始化为网络对象");
Debug.LogError($"游戏对象: {gameObject.name}, 活跃状态: {gameObject.activeInHierarchy}");
return;
}
if (!isLocalPlayer)
{
Debug.Log("我不是本地玩家,不能发送消息");
return;
}
string message = chatInput.text.Trim();
if (!string.IsNullOrEmpty(message))
{
// 发送到服务器
CmdSendMessage(message);
Debug.Log("信息发送到服务器了");
}
chatInput.text = "";
}
[Command]
void CmdSendMessage(string message)
{
// 获取玩家名字
string playerName = $"玩家{connectionToClient.connectionId}";
// 广播给所有客户端
RpcReceiveMessage(playerName, message);
Debug.Log(" 广播给所有客户端");
}
[ClientRpc]
void RpcReceiveMessage(string playerName, string message)
{
// 添加新消息
string newMessage = $"\n{playerName}: {message}";
chatHistory += newMessage;
// 限制消息数量
string[] lines = chatHistory.Split('\n');
if (lines.Length > maxMessages)
{
chatHistory = string.Join("\n", lines, lines.Length - maxMessages, maxMessages);
}
// 更新显示
chatDisplay.text = chatHistory;
}
}
脚本挂载在本地Player预制体上,有网络身份组件和其他必要组件,SendMessage()的触发为button点击,canvas上有网络身份组件。
问题1:我在OnStartLocalPlayer()中用if语句检测chatInput 和chatDisplay 都不为空,但是在SendMessage()中检测chatInput 却为空。
问题2:在点击button后,SendMessage()下我用来测试的if语句都报错(即gameObject.activeInHierarchy为flase)。应该是因为我的是预制体资源
问题3:netIdentity == null;但是我明明加了网络身份组件。