c# - 客户端不会从服务器获得生成的游戏对象,反之亦然
问题描述
所以,我正在为整个 Unet 系统而苦苦挣扎。现在,我想做的就是从一端到另一端产生对象。但即使这样也行不通。它在每个服务器和客户端上生成对象。但不同步。我搜索了很多地方并观看了很多视频 - 没有任何帮助。这是代码和检查员详细信息
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class NetworkController : NetworkBehaviour
{
public GameObject[] Spawns;
GameObject Canvas;
GameObject spawn;
[SyncVar]
public NetworkInstanceId ParentId;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
[Command]
public void CmdspawnPrefab()
{
Transform trns = GameObject.Find("Canvas").transform;
trns.position = trns.position + new Vector3(100, 200, 0);
GameObject go = Instantiate(Spawns[0], trns);
NetworkServer.Spawn(go);
}
}
我错过了什么?
解决方案
看来,我的整个工作流程都不正确。解决方案首先是在按钮上附加一个监听器,而不是在检查器上使用 onclick 函数 -
Button b = BoardController.Buttons[0].GetComponent<Button>();
b.onClick.AddListener(delegate () { Cmd_ButtonPressed(1); });
第二种是创建游戏对象,其中包含一个控制您的棋盘的脚本“GameManager”,以及一个包含 Rpc 函数的“RpcManager”。然后在 playerobject 脚本中,使用命令。
这是我使用过的类,用于更新图像而不是生成对象,想法基本相同 - 了解 Unet 的基本原理并传递命令。
public class PlayerObject : NetworkBehaviour {
public BoardManager BoardController;
public ClientRPCmanager ClientRPCManager;
// Use this for initialization
void Start () {
ClientRPCManager = GameObject.FindGameObjectWithTag("ClientRPCmanager").GetComponent<ClientRPCmanager>();
BoardController = ClientRPCManager.BoardController;
Button b = BoardController.Buttons[0].GetComponent<Button>();
b.onClick.AddListener(delegate () { Cmd_ButtonPressed(1); });
}
// Update is called once per frame
void Update () {
}
public void SetButton(int i)
{
BoardController.SetButton(i);
}
[Command]
public void Cmd_ButtonPressed(int i)
{
ClientRPCManager.Rpc_ButtonPressed(i);
}
董事会经理
public class BoardManager : NetworkBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public GameObject[] Buttons;
public Sprite[] Sprites;
public void SetButton(int index)
{
GameObject img = GameObject.Find("X");
img.GetComponent<Image>().sprite = Sprites[0];
}
RpcManager
public class ClientRPCmanager : NetworkBehaviour {
public BoardManager BoardController;
public NetworkManager Manager;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
[ClientRpc]
public void Rpc_ButtonPressed(int index)
{
BoardController.SetButton(index);
}
希望这对人们了解 Unet 有所帮助。我通过仔细查看这个项目了解到这一点https://www.youtube.com/watch?v=8Kd2RAfgzW0
推荐阅读
- flutter - Flutter BottomNavigationBar 在顶部发光?
- java - AWS SWF - Workflow passing activity results with signals driving the workflow
- java - Each microservice has to implement authentication and authorization or it's better one centerized to deal with it?
- sql - 使用索引连接临时表
- azure-api-management - 无法使用 Azure API 管理液体模板解析肥皂响应
- angular - 添加新的角度组件 npm 安装和导入的步骤是什么?
- python - 餐厅菜单和收据的最佳解决方案
- wpf - 对话框出现在其他窗口后面
- json - Postgres 通过复制脚本导出不喜欢导入时带引号的 json
- powerpoint - 在 Powerpoint 视图中替换字体不会替换字体