大家好,我正在尝试为多人游戏进行聊天,并且我已经将消息预制件在所有客户端和主机上实例化,因此工作正常。唯一的问题是文本没有变化,它仍然是默认值。这是我的代码:
ChatManager.cs:
using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class ChatManager : NetworkBehaviour
{
[SerializeField] private GameObject chat;
[SerializeField] private GameObject chatItemPrefab;
[HideInInspector] public List<ChatItem> messages;
public float messageExpireTime = 5;
public static ChatManager instance;
void Awake()
{
instance = this;
}
public void ChatSendMessage(string sender, string message)
{
CmdChatSendMessage(sender, message);
}
[Command]
void CmdChatSendMessage(string sender, string message)
{
GameObject chatItem = Instantiate(chatItemPrefab);
chatItem.transform.SetParent(chat.transform);
ChatItem messageSettings = chatItem.GetComponent<ChatItem>();
messageSettings.Setup(sender, message);
messageSettings.chatNetId = chat.GetComponent<NetworkIdentity>().netId;
NetworkServer.Spawn(chatItem);
StartCoroutine(WaitForExpire(chatItem));
}
public IEnumerator WaitForExpire(GameObject chatItem)
{
yield return new WaitForSeconds(messageExpireTime);
CmdDestroyChatMessage(chatItem);
}
[Command]
void CmdDestroyChatMessage(GameObject chatItem)
{
NetworkServer.Destroy(chatItem);
}
}
ChatItem.cs:
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Networking;
public class ChatItem : NetworkBehaviour
{
[SerializeField] private Text senderText;
[SerializeField] private Text messageText;
[SyncVar] public NetworkInstanceId chatNetId;
[SyncVar] public string sender;
[SyncVar] public string message;
void Start()
{
GameObject chatParent = ClientScene.FindLocalObject(chatNetId);
transform.SetParent(chatParent.transform);
}
public void Setup(string sender, string message)
{
senderText.text = string.Format("[{0}]:", sender);
messageText.text = message;
this.sender = sender;
this.message = message;
}
}
如果&#34; ChatSendMessage&#34;使用参数调用&#34; Server&#34;和#34;你好!&#34;主持人:
主持人看到:
但是客户看到了:
这是默认文字..
我正在处理的问题是什么。有任何想法吗?感谢
答案 0 :(得分:0)
已修复 - 我也在start方法中设置了文本,因此,如果您是发送者,则会被设置方法覆盖,但如果您是远程客户端,则设置永远不会运行,您可以设置syncvar中的文本,该文本已经通过发送人的客户端上的设置方法设置。 e.g。
void Start()
{
GameObject chatParent = ClientScene.FindLocalObject(chatNetId);
transform.SetParent(chatParent.transform);
senderText.text = string.Format("[{0}]:", sender);
messageText.text = message;
}