有没有人在新的 Unity UNET 网络上使用多个玩家预制件(例如,具有不同预制件的不同角色类)?

最佳答案

终于让它工作了!
非常感谢@ClausKleber 的回答
http://forum.unity3d.com/threads/how-to-set-individual-playerprefab-form-client-in-the-networkmanger.348337/#post-2256378

下面编辑了工作版本,与网络管理器 HUD 一起创建和加入。

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class NetManagerCustom : NetworkManager
{
    // in the Network Manager component, you must put your player prefabs
    // in the Spawn Info -> Registered Spawnable Prefabs section
    public short playerPrefabIndex;


    public override void OnStartServer()
    {
        NetworkServer.RegisterHandler(MsgTypes.PlayerPrefab, OnResponsePrefab);
        base.OnStartServer();
    }

    public override void OnClientConnect(NetworkConnection conn)
    {
        client.RegisterHandler(MsgTypes.PlayerPrefab, OnRequestPrefab);
        base.OnClientConnect(conn);
    }

    private void OnRequestPrefab(NetworkMessage netMsg)
    {
        MsgTypes.PlayerPrefabMsg msg = new MsgTypes.PlayerPrefabMsg();
        msg.controllerID = netMsg.ReadMessage<MsgTypes.PlayerPrefabMsg>().controllerID;
        msg.prefabIndex = playerPrefabIndex;
        client.Send(MsgTypes.PlayerPrefab, msg);
    }

    private void OnResponsePrefab(NetworkMessage netMsg)
    {
        MsgTypes.PlayerPrefabMsg msg = netMsg.ReadMessage<MsgTypes.PlayerPrefabMsg>();
        playerPrefab = spawnPrefabs[msg.prefabIndex];
        base.OnServerAddPlayer(netMsg.conn, msg.controllerID);
        Debug.Log(playerPrefab.name + " spawned!");
    }

    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        MsgTypes.PlayerPrefabMsg msg = new MsgTypes.PlayerPrefabMsg();
        msg.controllerID = playerControllerId;
        NetworkServer.SendToClient(conn.connectionId, MsgTypes.PlayerPrefab, msg);
    }

    // I have put a toggle UI on gameObjects called PC1 and PC2 to select two different character types.
    // on toggle, this function is called, which updates the playerPrefabIndex
    // The index will be the number from the registered spawnable prefabs that
    // you want for your player
    public void UpdatePC ()
    {
        if (GameObject.Find("PC1").GetComponent<Toggle>().isOn)
        {
            playerPrefabIndex = 3;
        }
        else if (GameObject.Find("PC2").GetComponent<Toggle>().isOn)
        {
            playerPrefabIndex= 4;
        }
    }
}

关于unity3d - 如何为 Unity 的新 UNET 使用多玩家预制件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32241511/

10-12 04:14