Самое время приступить к написанию сервера для этой игры, сегодня мы напишем тип соединения MasterServer/Client. Мы
создадим три типа сервера.
1) Создайте новую сцену и назовите его ServerChoose: File->New Scene, File->Save Scene.
Это сцена предназначена для выбора типа сервера.
2) Создайте новую сцену – UDPServer. Эта
сцена будет использовать UDP Broadcast соединение.
3) Создайте новую сцену – MasterServer. Эта
сцена будет использовать MasterServer соединение.
4) Еще раз создайте новую сцену - EmptyScene. Эта сцена будет загружаться, когда пользователь
отсоединиться и попробует соединиться еще раз.
5) Добавьте эти
сцены в build
settings: File -> Build Settings -> Add Open
Scene.
Откроется список, в этот список загружаются сцены и автоматически
назначается индекс сцены. У сцены ServerChoose индекс должен быть равен 0, MasterServer – 1, UDPServer – 2, StarTrooper
– 3, EmptyScene – 4.
6) Откройте сцену ServerChoose.
7) Создайте новый джаваскрипт под названием Menu. Эту
сцену и скрипт мы будем использовать для выбора типа сервера и соединения.
8) Перетащите этот скрипт в камере (Main Camera)
и введите туда следующий код:
- function
OnGUI() {
- GUI.Label(new
Rect((Screen.width/2)-80,(Screen.height/2)-130,200,50),"SELECT
- CONNECTION
TYPE");
- GUI.Label(new
Rect((Screen.width-220),(Screen.height-30),220,30),"STAR-TROOPER
- MULTIPLAYER
DEMO");
- if(GUI.Button(new
Rect((Screen.width/2)-100,(Screen.height/
- 2)-100,200,50),"Master
Server Connection"))
- {
- Application.LoadLevel("MasterServer");
- }
- if(GUI.Button(new
Rect((Screen.width/2)-100,(Screen.height/2)-40,200,50),"Direct
- Connection"))
- {
- Application.LoadLevel("StarTrooper");
- }
- if(GUI.Button(new
Rect((Screen.width/2)-100,(Screen.height/2)+20,200,50),"UDP
- Connection"))
- {
- Application.LoadLevel("UDPServer");
- }
- }
|
9) Откройте MasterServer
10) Создайте новый джаваскрипт – NetworkLevelLoad,
новый
игровой
объект
- ConnectionGUI. Перетиащите NetworkLevelLoad в ConnectionGUI и введите туда:
- // Keep track of the last level prefix (increment
each time a new level loads)
- private var lastLevelPrefix = 0;
- function Awake () {
- // Network level loading is done in a seperate
channel.
- DontDestroyOnLoad(this);
- networkView.group = 1;
- Application.LoadLevel("EmptyScene");
- }
- function OnGUI () {
- // When network is running (server or client) then display
the level "StarTrooper"
- if (Network.peerType !=
NetworkPeerType.Disconnected)
- {
- if (GUI.Button(new
Rect(350,10,100,30),"StarTrooper"))
- {
- // Make sure no old RPC calls are buffered and then
send load level command
- Network.RemoveRPCsInGroup(0);
- Network.RemoveRPCsInGroup(1);
- // Load level with incremented level prefix (for
view IDs)
- networkView.RPC( "LoadLevel",
RPCMode.AllBuffered, "StarTrooper",
- lastLevelPrefix + 1);
- }
- }
- }
- @RPC
- function LoadLevel (level : String, levelPrefix :
int) {
- Debug.Log("Loading level " + level +
" with prefix " + levelPrefix);
- lastLevelPrefix = levelPrefix;
- // There is no reason to send any more data over the
network on the default
- channel,
- // because we are about to load the level, because
all those objects will get deleted
- anyway
- Network.SetSendingEnabled(0, false);
- // We need to stop receiving because first the level
must be loaded.
- // Once the level is loaded, RPC's and other state
update attached to objects in the
- level are allowed to fire
- Network.isMessageQueueRunning = false;
- // All network views loaded from a level will get a
prefix into their NetworkViewID.
- // This will prevent old updates from clients
leaking into a newly created scene.
- Network.SetLevelPrefix(levelPrefix);
- Application.LoadLevel(level);
- yield;
- yield;
- // Allow receiving data again
- Network.isMessageQueueRunning = true;
- // Now the level has been loaded and we can start
sending out data
- Network.SetSendingEnabled(0, true);
- // Notify our objects that the level and the network
is ready
- var go : Transform[] = FindObjectsOfType(Transform);
- var go_len = go.length;
- for (var i=0;i<go_len;i++)
- {
- go[i].SendMessage("OnNetworkLoadedLevel",
- SendMessageOptions.DontRequireReceiver);
- }
- }
- function OnDisconnectedFromServer () {
- Application.LoadLevel("EmptyScene");
- }
- @script RequireComponent(NetworkView)
| Есть еще один скрипт он слишком большой и редактор запрещает его публикацию, так как символов в нем очень много, поэтому привести его здесь я не смогу, и прошу просто скачать его с сервера сайта: скачать
|