Photon为每个玩家创建一个新房间

本文关键字:一个 新房间 房间 玩家 创建 Photon | 更新日期: 2023-09-27 18:18:18

我已经编写了我的Photon脚本,以便玩家加入一个随机房间,如果没有找到房间,玩家将自动创建一个新房间。然而,当我在两台不同的电脑上构建和运行游戏时,两台电脑上都找不到房间,所以它们都创建了自己的房间。有人能告诉我为什么吗?

当只需要1名玩家时,游戏就会像它应该的那样开始,但当需要2名玩家时,因为我上面提到的问题,它就不会开始了。

using UnityEngine;
using System.Collections;
public class NetworkManager : Photon.PunBehaviour
{
public string playerprefabname = "player";
Vector3 spawner = new Vector3(9.9f, -3.8f, -0.1f);

// Use this for initialization
void Start()
{
    //Log stuff to console
    PhotonNetwork.logLevel = PhotonLogLevel.Full;
    //Connect
    PhotonNetwork.ConnectUsingSettings("v0.1");
    //Sync scenes
    PhotonNetwork.automaticallySyncScene = true;
}
//Display connection state on game
void OnGUI()
{
    GUILayout.Label(PhotonNetwork.connectionStateDetailed.ToString());
}

public override void OnConnectedToMaster()
{
    PhotonNetwork.JoinLobby();
}
public override void OnJoinedLobby()
{
    PhotonNetwork.JoinRandomRoom();
}
//Create a room if fail to join one
void OnPhotonRandomJoinFailed()
{
    Debug.Log("Can't join random room!");
    RoomOptions roomOptions = new RoomOptions() { isVisible = false, maxPlayers = 2 };
    PhotonNetwork.CreateRoom(null, roomOptions, TypedLobby.Default);
}
// when joined to a room check if 3 players are there, then send to level
public override void OnJoinedRoom()
{
    if (PhotonNetwork.playerList.Length == 2)
    {
        Debug.Log("2 Players In Room Starting Level");
        GameObject myPlayer = PhotonNetwork.Instantiate(playerprefabname, spawner, spawnpoint.rotation, 0);
        //GameObject MyCam = PhotonNetwork.Instantiate ("Camera", CamPos, Quaternion.identity, 0);
        GameObject camera = GameObject.FindWithTag("MainCamera");
        if (camera != null)
        {
            CameraController followScript = camera.GetComponent("CameraController") as CameraController;
            if (followScript != null)
            {
                followScript.target = myPlayer;
            }
        }
    }
}
public override void OnPhotonPlayerConnected(PhotonPlayer newPlayer)
{
    if (PhotonNetwork.playerList.Length == 2)
    {
        Debug.Log("2 Players In Room Starting Level");
        GameObject myPlayer = PhotonNetwork.Instantiate(playerprefabname, spawner, spawnpoint.rotation, 0);
        //GameObject MyCam = PhotonNetwork.Instantiate ("Camera", CamPos, Quaternion.identity, 0);
        GameObject camera = GameObject.FindWithTag("MainCamera");
        if (camera != null)
        {
            CameraController followScript = camera.GetComponent("CameraController") as CameraController;
            if (followScript != null)
            {
                followScript.target = myPlayer;
            }
        }
    }
}

}

Photon为每个玩家创建一个新房间

原因是创建房间时isVisible选项设置为false。因为房间没有显示在房间列表中,不能通过随机连接选择

这些电脑是通过局域网还是无线方式相互连接的?当两台计算机之间没有连接时,它会创建一个房间。

相关文章: