Version: 2017.1
Network Instantiate (Legacy)
Master Server (Legacy)

Network Level Loading (Legacy)

(Para nuevos proyectos puedes usar el Nuevo Networking System introducido en 5.1. Esta información es para antiguos proyectos usando el sistema antiguo de networking.)

A continuación se muestra un ejemplo sencillo de una forma de cargar un nivel en un juego multijugador. Se asegura de que no se procesen mensajes de red mientras se está cargando el nivel. También se asegura de que no se envíen mensajes, hasta que todo esté listo. Por último, cuando el nivel se carga, envía un mensaje a todos los scripts para que sepan que el nivel está cargado y pueden reaccionar a eso. La función SetLevelPrefix ayuda a mantener las actualizaciones de redes no deseadas fuera de un nuevo nivel cargado. Las actualizaciones no deseadas pueden ser actualizaciones del nivel anterior, por ejemplo. El ejemplo también utiliza grupos para separar los datos del juego y la comunicación de nivel de carga en grupos. El grupo 0 se utiliza para el tráfico de datos del juego y el grupo 1 para el nivel de carga. El grupo 0 se bloquea mientras se carga el nivel pero el grupo 1 se mantiene abierto, también puede transmitir la comunicación de chat para que pueda permanecer abierta durante la carga de nivel.

using UnityEngine;
using UnityEngine.Network;
using System.Collections;

[RequireComponent(NetworkView)]
public class ExampleScript : MonoBehaviour {
    string[] supportedNetworkLevels  = new[]{ "mylevel" };
    string disconnectedLevel = "loader";
    int lastLevelPrefix = 0;
    NetworkView networkView;    

    void Awake ()
    {
        // Network level loading is done in a separate channel.
        DontDestroyOnLoad(this);
        networkView = new NetworkView ();
        networkView.group = 1;
        Application.LoadLevel(disconnectedLevel);
    }
    
    void OnGUI ()
    {
        if (Network.peerType != NetworkPeerType.Disconnected)
        {
            GUILayout.BeginArea(Rect(0, Screen.height - 30, Screen.width, 30));
            GUILayout.BeginHorizontal();
            
            foreach (var level in supportedNetworkLevels)
            {
                if (GUILayout.Button(level))
                {
                    Network.RemoveRPCsInGroup(0);
                    Network.RemoveRPCsInGroup(1);
                    networkView.RPC( "LoadLevel", RPCMode.AllBuffered, level, lastLevelPrefix + 1);
                }
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.EndArea();
        }
    }
    
    [RPC]
    IEnumerator LoadLevel (string level, int 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, thus all those objects will get deleted anyway
        Network.SetSendingEnabled(0, false);    
        
        // We need to stop receiving because first the level must be loaded first.
        // 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 return;

        // Allow receiving data again
        Network.isMessageQueueRunning = true;
        // Now the level has been loaded and we can start sending out data to clients
        Network.SetSendingEnabled(0, true);

        var gameObjects = FindObjectsOfType(GameObject) as GameObject[];
        foreach (var go in gameObjects)
            go.SendMessage("OnNetworkLoadedLevel", SendMessageOptions.DontRequireReceiver); 
    }
    
    void OnDisconnectedFromServer ()
    {
        Application.LoadLevel(disconnectedLevel);
    }
}

script de ejemplo C#

var supportedNetworkLevels : String[] = [ "mylevel" ];
var disconnectedLevel : String = "loader";
private var lastLevelPrefix = 0;

function Awake ()
{
    // Network level loading is done in a separate channel.
    DontDestroyOnLoad(this);
    networkView.group = 1;
    Application.LoadLevel(disconnectedLevel);
}

function OnGUI ()
{
    if (Network.peerType != NetworkPeerType.Disconnected)
    {
        GUILayout.BeginArea(Rect(0, Screen.height - 30, Screen.width, 30));
        GUILayout.BeginHorizontal();
        
        for (var level in supportedNetworkLevels)
        {
            if (GUILayout.Button(level))
            {
                Network.RemoveRPCsInGroup(0);
                Network.RemoveRPCsInGroup(1);
                networkView.RPC( "LoadLevel", RPCMode.AllBuffered, level, lastLevelPrefix + 1);
            }
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
    }
}

@RPC
function LoadLevel (level : String, levelPrefix : int)
{
    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, thus all those objects will get deleted anyway
        Network.SetSendingEnabled(0, false);    

        // We need to stop receiving because first the level must be loaded first.
        // 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;

        // Allow receiving data again
        Network.isMessageQueueRunning = true;
        // Now the level has been loaded and we can start sending out data to clients
        Network.SetSendingEnabled(0, true);

        for (var go in FindObjectsOfType(GameObject))
            go.SendMessage("OnNetworkLoadedLevel", SendMessageOptions.DontRequireReceiver); 
}

function OnDisconnectedFromServer ()
{
    Application.LoadLevel(disconnectedLevel);
}

@script RequireComponent(NetworkView)

script de ejemplo JS

Network Instantiate (Legacy)
Master Server (Legacy)