客户端不会从服务器获取衍生的gameObject,反之亦然

时间:2018-08-27 09:03:40

标签: c# visual-studio unity3d unity3d-unet

因此,我正在为整个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);
    }
}

enter image description here

我想念什么?

1 个答案:

答案 0 :(得分:0)

看来,我的整个工作流程都不正确。解决方案是首先将侦听器附加到按钮,而不是使用检查器上的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

来了解的