Unity3d Unet multiplayer - only server host can place buildings network aware

亡梦爱人 提交于 2020-01-06 15:52:57

问题


I am writting an multiplayer game but I am stuck with building system - I mean I've created a code to place blocks it works perfectly fine on host-side (when you run this script on host the block spawn for every client) but it isn't working on client side ( blocks spawn only for local client but not for server and other clients ). I've seen many simillar problems but no answer was found this day. Maybe you guys could give me a hand. Here's my code:

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Builder : NetworkBehaviour {

    public GameObject preview;
    public Transform currentPreview;
    bool isPreviewing = false;
    GameObject buildingPreview;
    private NetworkIdentity networkId;

    // Use this for initialization
    void Start ()
    {
        networkId = GetComponent<NetworkIdentity>();
    }

    // Update is called once per frame

    void ViewPreview()
    {
        buildingPreview = Instantiate(preview, transform.position, transform.rotation) as GameObject;
        currentPreview = buildingPreview.transform;
        isPreviewing = true;
    }
    void Update ()
    {
        CmdBuild(); 
    }

    void CmdBuild()
    {
        if (networkId.isLocalPlayer)
        {

        }
        else
        { return; }
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (!isPreviewing)
                ViewPreview();
            else
            {
                Destroy(buildingPreview);
                isPreviewing = false;
            }
        }
        if (isPreviewing)
        {
            Preview();
        }
    }


    [Command]
    void CmdSpawnBuilding()
    {
        GameObject buildingPlaced = Instantiate(preview, currentPreview.position, currentPreview.rotation) as GameObject;
        NetworkServer.Spawn(buildingPlaced);
    }

    void Preview()
    {
        currentPreview.position = transform.position + transform.forward * 3f;
        currentPreview.rotation = transform.rotation;
        if (Input.GetButtonDown("Fire1"))
        {
            CmdSpawnBuilding();
            isPreviewing = false;
        }
    }
}

P.S: I have network identity script assigned to prefab I am creating network aware and I have that prefab in my Network Manager as Registred Spawnable Prefabs.

来源:https://stackoverflow.com/questions/40413680/unity3d-unet-multiplayer-only-server-host-can-place-buildings-network-aware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!