Unity Network 使用小结

Unity提供了NetWork的方法来实现网络连接,而实际项目中缺很少备用到了。这里作为了解NetWork的使用,做了一个CS局域网游戏的功能

创建服务器和连接客户端的方法

using UnityEngine;
using System.Collections;

public class MyNetwork : MonoBehaviour
{
    public int connections = 10;
    public int listenPort = 8899;
    public bool useNat = false;
    public string ip = "127.0.0.1";
    public GameObject playerPrefab;
	void OnGUI()
    {
	    if (Network.peerType == NetworkPeerType.Disconnected)
	    {
	        if (GUILayout.Button("创建服务器"))
	        {
	            //进行创建服务器的操作
	            NetworkConnectionError error = Network.InitializeServer(connections, listenPort, useNat);
	            print(error);
	        }
	        if (GUILayout.Button("链接服务器"))
	        {
	            NetworkConnectionError error = Network.Connect(ip, listenPort);
                print(error);
	        }
	    }
        else if (Network.peerType == NetworkPeerType.Server)
        {
            GUILayout.Label("服务器创建完成");
        }
        else if(Network.peerType == NetworkPeerType.Client)
        {
            GUILayout.Label("客户端已经接入");
        }
	}

    //注意,这两个方法都是在服务器上调用的
    private void OnServerInitlized()
    {
        print("Server 完成初始化");
        //Network.player;//访问到当前的player,客户端
        int group = int.Parse(Network.player + "");//直接访问Network.player会得到当前客户端的索引是唯一的
        Network.Instantiate(playerPrefab,new Vector3(0,10,0),Quaternion.identity,group );
    }

    private void OnPlayerConnected(NetworkPlayer player)
    {
        print("一个客户端连接过来,Index,number:" +player);
    }

    private void OnConnectedToServer()
    {
        print("我成功连接到服务器了");
        int group = int.Parse(Network.player + "");//直接访问Network.player会得到当前客户端的索引是唯一的
        Network.Instantiate(playerPrefab, new Vector3(0, 10, 0), Quaternion.identity, group);
    }
    //network view 组件用来在局域网之内去同步一个游戏物体的组件属性
    //network view 会把创建出来的客户端作为主人,就是主客户端,其他的客户端都是会以主客户端为准
}


Network

class in UnityEngine

Description

The network class is at the heart of the network implementation and provides the core functions.

This class configures the network interface and all the network parameters. You use it to set up a server or connect to one and have a row of helper functions to help you with those tasks. For more information on what is exposed in the editor see the Network Manger component reference.

NetworkConnectionError error = Network.InitializeServer(connections, listenPort, useNat);

创建服务器,连接数,端口,是否使用Nat功能;

Network.InitializeServer(connections, listenPort, useNat)<span style="color: rgb(27, 34, 41); line-height: 1em; font-family: 'Open Sans', sans-serif; background-color: rgb(255, 255, 255);"> Description</span>

Initialize the server.

connections  the number of allowed incomingis connections (note that this is generally not the same as the number of players). listenPortis the port number we want to listen to. useNat sets the NAT punchthrough functionality. If you want this server to be able to accept connections using NAT punchthrough, using the facilitator, set this to true.

连接错误,通过Debug,可以判断连接是否成功

NetworkConnectionError error<span style="color: rgb(27, 34, 41); line-height: 1em; font-family: 'Open Sans', sans-serif; background-color: rgb(255, 255, 255);"> Description</span>

Possible status messages returned by Network.Connect and in OnFailedToConnect in case the error was not immediate.

OnServerInitlized,<span style="font-family: Arial, Helvetica, sans-serif;">OnConnectedToServer 是Unity提供的服务器创建成功,客户端连接到服务器的执行</span>

在Network创建物体的方法由GameObject.Instantiate=>Network.Instantitae。原因是不论是客户端和服务器都要同步相应的创建操作,原来的方法显然是不能满足的。

private void OnServerInitialized()
{
        //服务端
        //GameController.Instantiate(soldierPrefab, pos1.position, Quaternion.identity);
        NetworkPlayer player = Network.player;
        int group = int.Parse(player + "");
        GameObject go = Network.Instantiate(soldierPrefab, pos1.position, Quaternion.identity, group) as GameObject;
        go.GetComponent<Player>().SetOwnerPlayer(Network.player);// 这个代码值设置了当前创建者的战士的ownerPlayer属性,在其他客户端这个属性是为null的
        //RPC:远程过程调用
        go.networkView.RPC("SetOwnerPlayer",RPCMode.AllBuffered,Network.player);//完成一个远程调用,会执行所有连接的客户端上的setownerplayer方法
        Screen.showCursor = false;
}
go.GetComponent<Player>().SetOwnerPlayer(Network.player);// 这个代码值设置了当前创建者的战士的ownerPlayer属性,在其他客户端这个属性是为null的
是调用服务器本地的方法。
go.networkView.RPC("SetOwnerPlayer",RPCMode.AllBuffered,Network.player);//完成一个远程调用,会执行所有连接的客户端上的setownerplayer方法
调用客户端执行相同的方法。

关于RPC要解释下,“SetOwnerPlyer” 方法名,类似SeneMessage方法,RPCMode.AllBuffered通知所有对象和缓存。


[RPC]//使用这个注解表示这个方法是一个远程调用的方法
    public void SetOwnerPlayer(NetworkPlayer player)
    {
        this.ownpalyer = player;
        if (Network.player != player)
        {
            LoseControl();//如果当前角色不是这个战士的创建者,就要把战士的控制禁用掉
        }
    }
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值