network view

ConnectionUI 脚本挂在摄像机上

using UnityEngine;
using System.Collections;

public class ConnectionUI : MonoBehaviour {
public string remoteIP = "127.0.0.1";
public int remotePort = 25000;
public int listenPort = 25000;
public bool useNAT = false;
public string yourIP = "";
public int yourPort=0;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
void OnConnectedToServer()
{
//通知场景中的物体网络已经准备好了
foreach(GameObject go in FindObjectsOfType<GameObject>())
{
go.SendMessage("OnNetworkLoadedLevel",SendMessageOptions.DontRequireReceiver);
}

}
void OnGUI()
{
//检查你是否连接到服务器。
if(Network.peerType==NetworkPeerType.Disconnected)
{
if(GUI.Button(new Rect(10,50,100,30),"Connect"))
{
Network.useNat=useNAT;
//连接到服务器
Network.Connect(remoteIP,remotePort);
}
if(GUI.Button(new Rect(10,100,100,30),"Start Server"))
{
Network.useNat=useNAT;
//创建服务器
Network.InitializeServer(32,listenPort);
//通知我们场景中的物体network已经准备好了。
foreach(GameObject go in FindObjectsOfType<GameObject>())
{
go.SendMessage("OnNetworkLoadedLevel",SendMessageOptions.DontRequireReceiver);
}
}
//添加IP地址和端口号
remoteIP=GUI.TextField(new Rect(120,10,100,20),remoteIP);
remotePort=int.Parse( GUI.TextField(new Rect(230,10,40,20),remotePort.ToString()));
}
else
{
//得到你的IP地址和端口
yourIP=Network.player.ipAddress;
yourPort=int.Parse(Network.player.port.ToString());
GUI.Label(new Rect(140,20,250,40),"IP Address:"+yourIP+":"+yourPort);
if(GUI.Button(new Rect(10,10,100,50),"Disconnect"))
{
//从服务器上断开连接
Network.Disconnect(200);
}
}

}

}

 

Instantiated 脚本的SpaceCraft绑定要监视的物体

using UnityEngine;
using System.Collections;

public class Instantiated : MonoBehaviour {
public Transform SpaceCraft;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}
void OnNetworkLoadedLevel()
{
//当网络加载后实例化SpaceCraft。
Network.Instantiate(SpaceCraft,transform.position,transform.rotation,0);
}

void OnPlayerDisconnected(NetworkPlayer player)
{
Network.RemoveRPCs(player,0);
Network.DestroyPlayerObjects(player);
}

}

 

你可能感兴趣的:(NetWork)