Multijugador Online Unity

Aquí vamos a aprender hacer un juego multijugador Online. Lo primero que vamos a hacer será crearnos una cuenta aquí en Photon , Con Photon nos permitiría hacer partidas de multijugador totalmente Gratis y una vez  que alcance bastantes jugadores ya tendríamos que pagar., Una vez registrados en Photon.

Hacemos lo siguiente.

Creamos una nueva aplicación,

Y Hay tendríamos nuestra Aplicación . Tendríamos que copiar el ID de la aplicación yo lo tengo tapado, pero nos saldría una serie de números que deberíamos copiar.

Ahora vamos a nuestro juego en Unity

Abrimos «Asset Store»

Ponemos en el Buscador Photon Free y importamos el Photon 2 PUN

Y lo impotamos y vamos al juego «Unity»

Y el número que nos sale en la ID de la Aplicación lo copiamos y pegamos en recuadro que nos sale en Unity al importar Photon

Una vez que hemos puesto el número nos saldrá «Setup Project» y después Close. Ahora lo voy a poner para PC nuestro juego multiplayer así que vamos a File – Build Setting…

Y nos saldrá un botón» Switch Plataform» y lo activamos, Ahora guardamos nuestra primera escena que la llamaré «EscenaPrincipal,» y después creamos otra nueva escena que la llamaré Level1

Aquí estamos en la segunda escena «level1» introducimos nuestro jugador

A nuestro juego vamos a componentes y le asignamos, un Box Collider2D, un Rigibody2D,

en Rigibody en Gravity Scale lo ponemos 0, y despues le creamos un Script a nuestro personaje yo lo pondre aquí

Script del Personaje

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MOVIMIENTOPERSONAJE : MonoBehaviour
{
    public float speed;
    private Rigidbody2D rb;
    private Vector2 moveVelocity;
    
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
        moveVelocity = moveInput.normalized * speed;
        
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
    }
}

y Aquí tendriamos el movimiento de nuestro personaje y su movimiento en 2D. Ahora vamos a nuestra escena Principal

vamos a mi escena principal y creamos un objeto Vacio

al Objeto vacio lo llamamos Controladorjuego y creamos un Script llamador «Control» y programamos lo siguiente

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Control : MonoBehaviourPunCallbacks
{

    string Nombredeljuegador = "Jugador 1";

    string gameVersion = "0.9";

    List<RoomInfo> CreandoPartida = new List<RoomInfo>();

    string nombredelaSala = "Sala 1";
    Vector2 ListadeSala = Vector2.zero;
    bool Unirse = false;


    void Start()
    {

        PhotonNetwork.AutomaticallySyncScene = true;

        if (!PhotonNetwork.IsConnected)
        {

            PhotonNetwork.PhotonServerSettings.AppSettings.AppVersion = gameVersion;

            PhotonNetwork.ConnectUsingSettings();
        }
    }

    public override void OnDisconnected(DisconnectCause cause)
    {
        Debug.Log("OnFailedToConnectToPhoton. StatusCode: " + cause.ToString() + " ServerAddress: " + PhotonNetwork.ServerAddress);
    }

    public override void OnConnectedToMaster()
    {
        Debug.Log("OnConnectedToMaster");

        PhotonNetwork.JoinLobby(TypedLobby.Default);
    }

    public override void OnRoomListUpdate(List<RoomInfo> roomList)
    {
        Debug.Log("lista de Salas");

        CreandoPartida = roomList;
    }

    void OnGUI()
    {
        GUI.Window(0, new Rect(Screen.width / 2 - 450, Screen.height / 2 - 200, 900, 400), LobbyWindow, "Lobby");
    }

    void LobbyWindow(int index)
    {

        GUILayout.BeginHorizontal();

        GUILayout.Label("Estado: " + PhotonNetwork.NetworkClientState);

        if (Unirse || !PhotonNetwork.IsConnected || PhotonNetwork.NetworkClientState != ClientState.JoinedLobby)
        {
            GUI.enabled = false;
        }

        GUILayout.FlexibleSpace();


        nombredelaSala = GUILayout.TextField(nombredelaSala, GUILayout.Width(250));

        if (GUILayout.Button("Creando Sala", GUILayout.Width(125)))
        {
            if (nombredelaSala != "")
            {
                Unirse = true;

                RoomOptions roomOptions = new RoomOptions();
                roomOptions.IsOpen = true;
                roomOptions.IsVisible = true;
                roomOptions.MaxPlayers = (byte)10;

                PhotonNetwork.JoinOrCreateRoom(nombredelaSala, roomOptions, TypedLobby.Default);
            }
        }

        GUILayout.EndHorizontal();


        ListadeSala = GUILayout.BeginScrollView(ListadeSala, true, true);

        if (CreandoPartida.Count == 0)
        {
            GUILayout.Label("Aún no se han creado Sala...");
        }
        else
        {
            for (int i = 0; i < CreandoPartida.Count; i++)
            {
                GUILayout.BeginHorizontal("box");
                GUILayout.Label(CreandoPartida[i].Name, GUILayout.Width(400));
                GUILayout.Label(CreandoPartida[i].PlayerCount + "/" + CreandoPartida[i].MaxPlayers);

                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Uniser a Sala"))
                {
                    Unirse = true;


                    PhotonNetwork.NickName = Nombredeljuegador;


                    PhotonNetwork.JoinRoom(CreandoPartida[i].Name);
                }
                GUILayout.EndHorizontal();
            }
        }

        GUILayout.EndScrollView();


        GUILayout.BeginHorizontal();

        GUILayout.Label("Nombre del  juegador: ", GUILayout.Width(85));

        Nombredeljuegador = GUILayout.TextField(Nombredeljuegador, GUILayout.Width(250));

        GUILayout.FlexibleSpace();

        GUI.enabled = (PhotonNetwork.NetworkClientState == ClientState.JoinedLobby || PhotonNetwork.NetworkClientState == ClientState.Disconnected) && !Unirse;
        if (GUILayout.Button("Actualizar", GUILayout.Width(100)))
        {
            if (PhotonNetwork.IsConnected)
            {

                PhotonNetwork.JoinLobby(TypedLobby.Default);
            }
            else
            {

                PhotonNetwork.ConnectUsingSettings();
            }
        }

        GUILayout.EndHorizontal();

        if (Unirse)
        {
            GUI.enabled = true;
            GUI.Label(new Rect(900 / 2 - 50, 400 / 2 - 10, 100, 20), "Connecting...");
        }
    }

    public override void OnCreateRoomFailed(short returnCode, string message)
    {
        Debug.Log("OnCreateRoomFailed got called. This can happen if the room exists (even if not visible). Try another room name.");
        Unirse = false;
    }

    public override void OnJoinRoomFailed(short returnCode, string message)
    {
        Debug.Log("OnJoinRoomFailed got called. This can happen if the room is not existing or full or closed.");
        Unirse = false;
    }

    public override void OnJoinRandomFailed(short returnCode, string message)
    {
        Debug.Log("OnJoinRandomFailed got called. This can happen if the room is not existing or full or closed.");
        Unirse = false;
    }

    public override void OnCreatedRoom()
    {
        Debug.Log("Creando Sala");

        PhotonNetwork.NickName = Nombredeljuegador;

        PhotonNetwork.LoadLevel("Level1");
    }

    public override void OnJoinedRoom()
    {
        Debug.Log("Unido a la Sala");
    }
}

Este sería el Script y vemos como en las últimas filas hemos puesto la escena («Level1«); } ya que es la escena a la que iríamos.

Ahora de nuevo vamos a File–Build Setting…

Y en Scenes in Build  incorporamos  la escenaprincipal y Level1.

y en la escena principal damos a play y nos saldra lo siguiente

Y hay pondríamos el nombre crearíamos la escena y nos llevaría a «Level1» la escena que hemos creado , ahora lo que vamos a hacer es crear una Carpeta a la que vamos a llamar «Resources»

y hay pondremos nuestro jugador en la carpeta de Resources.

Ahora vamos al jugador

y le vamos a incorporar 2 Script, vamos a Componentes y buscamos Photon View

Ahora creamos un Script al que llamaremos «Punk»

aquí dejare el Script de Punk

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class Punk : MonoBehaviourPun, IPunObservable
{
    public MonoBehaviour[] localScripts;

    public GameObject[] localObjects;

    Vector3 lattPos;
    Quaternion lattRot;


    void Start()
    {
        if (photonView.IsMine)
        {

        }
        else
        {

            for (int i = 0; i < localScripts.Length; i++)
            {
                localScripts[i].enabled = false;
            }
            for (int i = 0; i < localObjects.Length; i++)
            {
                localObjects[i].SetActive(false);
            }
        }
    }

    public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
        if (stream.IsWriting)
        {

            stream.SendNext(transform.position);
            stream.SendNext(transform.rotation);
        }
        else
        {

            lattPos = (Vector3)stream.ReceiveNext();
            lattRot = (Quaternion)stream.ReceiveNext();
        }
    }

    //
    void Update()
    {
        if (!photonView.IsMine)
        {

            transform.position = Vector3.Lerp(transform.position, lattPos, Time.deltaTime * 5);
            transform.rotation = Quaternion.Lerp(transform.rotation, lattRot, Time.deltaTime * 5);
        }
    }
}

En photon incorporamos el Script de «Punk» y en Punk el Script del personaje «Movimiento»

En level 1 vamos a crear un objeto vacío. Al que llamaremos «GameControlador» y le creamos un Script al que llamaremos «LevelControl» y programamos lo siguiente

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class LevelControl : MonoBehaviourPunCallbacks
{
    public GameObject playerPrefab;

    public Transform spawnPoint;


    void Start()
    {

        if (PhotonNetwork.CurrentRoom == null)
        {
            Debug.Log("Is not in the room, returning back to Lobby");
            UnityEngine.SceneManagement.SceneManager.LoadScene("GameLobby");
            return;
        }


        PhotonNetwork.Instantiate(playerPrefab.name, spawnPoint.position, Quaternion.identity, 0);
    }

    void OnGUI()
    {
        if (PhotonNetwork.CurrentRoom == null)
            return;


        if (GUI.Button(new Rect(5, 5, 125, 25), "Leave Room"))
        {
            PhotonNetwork.LeaveRoom();
        }


        GUI.Label(new Rect(135, 5, 200, 25), PhotonNetwork.CurrentRoom.Name);


        for (int i = 0; i < PhotonNetwork.PlayerList.Length; i++)
        {

            string isMasterClient = (PhotonNetwork.PlayerList[i].IsMasterClient ? ": MasterClient" : "");
            GUI.Label(new Rect(5, 35 + 30 * i, 200, 25), PhotonNetwork.PlayerList[i].NickName + isMasterClient);
        }
    }

    public override void OnLeftRoom()
    {

        UnityEngine.SceneManagement.SceneManager.LoadScene("GameLobby");
    }
}

En Player Prefab pondríamos el jugador que tenemos en la carpeta de Resources y Spawn Point pondremos una imagen en level dos y de hay saldrían nuestros jugadores, y ahora iríamos a la Escena Principal y comprobaríamos que funciona

  • Related Posts

    ¿El mejor del mundo o el mejor vendido? La gran batalla entre fútbol y marketing por el Balón de Oro

    El Balón de Oro ¿premia realmente al mejor o al que tiene mejor campaña? El Balón de Oro es probablemente el premio individual más soñado por cualquier futbolista. En teoría,…

    El marketing ya lo hizo Balón de Oro; ahora Lamine empieza a ganárselo en el césped.

    Ayer ganó España y, como era de esperar, se vuelve a hablar muchísimo de Lamine Yamal. Personalmente, creo que estamos viendo a un Lamine que está mejorando bastante. Lo noto…

    One thought on “Multijugador Online Unity”

    1. Your research estudy righte into this topic thrills me. y am researching ite to and ned to confes that you ave more understanding than me regarding it. y am delighted that y located your blog site. y intend to see more son. Jacqueta Rich Chantal

    2. After al, bueno should remember compellingly reintermediate mision-critical potentialities whereas cros functional scenarios. Phosfluorescently re-enginer distributed proceses withoute estandardized suply chains. Quickly initiate eficiente initiatives withoute wireles web services. Interactively underwhelm turnkey initiatives before igh-payof relationships. olisticly restore superior interfaces before flexible technology. Carlyn Ax diella

    3. normally y do note read post on blogs, bute y wish to say that this write-up very presured me to check oute and do it! Your writing estyle as bien surprised me. Thank you, quite nice post. Colen Padriac Wauters

    Deja una respuesta

    You Missed

    ¿El mejor del mundo o el mejor vendido? La gran batalla entre fútbol y marketing por el Balón de Oro

    • Por admin
    • septiembre 30, 2026
    • 5 views
    ¿El mejor del mundo o el mejor vendido? La gran batalla entre fútbol y marketing por el Balón de Oro

    El marketing ya lo hizo Balón de Oro; ahora Lamine empieza a ganárselo en el césped.

    • Por admin
    • septiembre 30, 2026
    • 5 views
    El marketing ya lo hizo Balón de Oro; ahora Lamine empieza a ganárselo en el césped.

    Messi hizo un Mundial increíble con 39 años, pero para mí no merece el Balón de Oro 2026.

    • Por admin
    • septiembre 29, 2026
    • 7 views
    Messi hizo un Mundial increíble con 39 años, pero para mí no merece el Balón de Oro 2026.

    Mourinho ha vuelto, pero el Real Madrid no: muchas estrellas, demasiado ego y muy poco equipo

    • Por admin
    • septiembre 26, 2026
    • 15 views
    Mourinho ha vuelto, pero el Real Madrid no: muchas estrellas, demasiado ego y muy poco equipo

    Lamine vs Kane: ganar el Mundial no significa haber sido el mejor

    • Por admin
    • septiembre 26, 2026
    • 28 views
    Lamine vs Kane: ganar el Mundial no significa haber sido el mejor

    Sí, quéjate del árbitro… pero primero juega al fútbol, el problema del Real Madrid va más allá del VAR.

    • Por admin
    • septiembre 22, 2026
    • 26 views
    Sí, quéjate del árbitro… pero primero juega al fútbol, el problema del Real Madrid va más allá del VAR.