Quantcast
Channel: Photon Unity Networking (PUN) — Photon Engine
Viewing all 8947 articles
Browse latest View live

Extra prefabs gets spawned

$
0
0
I use the following code to spawn Players. But when its called both master and client there are extra prefabs getting spawned.

Can someone help me?

Exactly 3 Target(clone) and Player(clone) are instantiated in the scene.
[PunRPC]
	public void RPC_SpawnTargets()
	{
		int i = 1;		
               TargetFormation=GameObject.Find("Target Formation").GetComponent<Transform>();
		foreach (Transform child in TargetFormation ) 
		{
			GameObject target = PhotonNetwork.Instantiate(Path.Combine("Prefabs","Target"),child.transform.position,Quaternion.identity,0) as GameObject;
			target.name = "Target ("+i+")";			
			target.transform.parent = child;
			print("Target Function called "+i+" times");			
			i++;
		}
		i = 0;		
	}

	[PunRPC]
	public void RPC_SpawnPlayers()
	{
		int i = 1;		
		PlayerFormation=GameObject.Find("Player Formation").GetComponent<Transform>();
		foreach (Transform child in PlayerFormation ) 
		{
			GameObject player =PhotonNetwork.Instantiate(Path.Combine("Prefabs","Player"),child.transform.position,Quaternion.identity,0) as GameObject;
			player.name = "Player ("+i+")";			
			player.transform.parent = child;		
			i++;
		}
		i=0;
	}

PvP Collision Based Multiplayer

$
0
0
Hi folks,

I'm fairly new to network programming, and especially PUN having only downloaded it a couple of days ago. I was hoping to get a little advice as to how I might go about achieving my game mechanic, as from searching around a bit I get the impression this one of those "tricky ones."

The game is a 2D PvP last man standing, where for the sake of simplicity each player is a bouncy circle. The only user input for now is to click around your player to apply a small push. The aim is to collide with other players to bump them out the playable area.

You'll likely anticipate the problem I'm having already. Syncing movement through PUN is lovely and smooth and works for multiple players, but the problem comes in when colliding with others. Sometimes the player we collide with doesn't move at all, sometimes they do but very delayed. From other discussions I understand this to be down to the "ownership" of the RigidBody2Ds on each client.

I'm having a hard time sorting out in my head what my best course of action is, is it simply a case of doing some lag compensation on each object to ensure the RigidBodies are better in-sync? Or will I need to do something more clever like transferring ownership to MasterClient or disabling collisions on non-Masters?

Any help would be much appreciated, apologies if I haven't been clear enough!

How would I architecture my code

$
0
0
I'm switching from UNet to PUN and I have some questions on how to architecture my code. In UNet I had a pretty simple formula: player sends input to server, server does stuff, server updates relevant stuff on all clients. But in PUN there is no server, it's just a bunch of clients talking to each other. I have a few ideas though. For example, let's say I shoot an enemy:
1. Should I apply the damage to the enemy on the client that shot the enemy and then send the new health value to all players?
2. Should I send an RPC to all clients telling them to apply X amount of damage to the enemy (would likely cause some de-sync issues)
3. Should I send an RPC to the master of the room, apply the damage there and send it to all clients. I think this would be the best approach to the problem since it is the closer I can get to an authoritative server.

I'm trying to find the most optimized way with code easy to follow. In UNet I could always be sure stuff would run on the server using the [Server] tag or in a client using the [Client] tag. In PUN I'm never 100% sure (mistakes can happen) and there is a lot of room for variables to de-sync. So in PUN I need to constantly worry about where the code is running.

How to make master client who has lowest lag?

$
0
0
I would like to choose master client that player has the lowest lag. How can I achieve that?

Objects not spawning in formation

$
0
0
I use this code to spawn players and targets but somehow they are spawned out of place.Can someone help me?
<pre class="CodeBlock"><code>[PunRPC]
	public void RPC_SpawnTargets()
	{
		int i = 1;		
        TargetFormation=GameObject.Find("Target Formation").GetComponent<Transform>();
		foreach (Transform child in TargetFormation ) 
		{
			GameObject target = PhotonNetwork.Instantiate(Path.Combine("Prefabs","Target"),child.transform.position,Quaternion.identity,0) as GameObject;
			target.name = "Target ("+i+")";			
			target.transform.parent = child;					
			i++;
		}
		i = 0;		
	}

	[PunRPC]
	public void RPC_SpawnPlayers()
	{
		int i = 1;		
		PlayerFormation=GameObject.Find("Player Formation").GetComponent<Transform>();
		foreach (Transform child in PlayerFormation ) 
		{
			GameObject player =PhotonNetwork.Instantiate(Path.Combine("Prefabs","Player"),child.transform.position,Quaternion.identity,0) as GameObject;
			player.name = "Player ("+i+")";			
			player.transform.parent = child;			
			i++;
		}
		i=0;
	}

How many photonviews can a room have max? Please read my scenario!

$
0
0
Im developing a game where you can shoot high speed bullets. very fast. and a lot. But there are 2 scenarios:


I Photonnetwork.Instantiate each bullet (with transferred ownership) and it has very good position synchronisation even on high speed, I destroy each bullet from the network after 3 seconds. But the Photonview ID still keeps counting up. For example Ive shot 50 bullets, all 50 get removed from the game, it continues counting from 51, is that bad? is there a maximum amount it will reach? like 1000?? I have a lot of photonview components in my game so I really must know.


OR


I have a stash of 200 bullets already as scene objects (outside the player's sight). and everytime a bullet is going to get ''shot'', the bullet quickly goes to the player's gun in one frame and gets shot starting from the next frame, after 3 seconds that bullet gets (destoyed, not really destroyed but gets back into the invisible stash ;)) but this method of quickly going from point A to B to C (from Stash to Gun to the hit position) is very very laggy because it happens so fast (it happens so fast that it actually goes from point A to C, skipping B !), photonview cant keep up with it, but if I didnt use this stash method and instead instantiated (first method) it would be OK.

Method 1 would be perfect, but im afraid theres a photonview limit? is there a limit? or is it OK if the bullets get destroyed and basically removed the photonview ID from the game, or is it a problem that it still keeps counting up?


Please help and thanks!

Hiring programmer to implement PUN

$
0
0
I'm looking for a programmer well versed in Photon Networking to help get my project's photon networking implemented.

This is a paid contract gig. Either hands on programing or as a consultant.

I've had a go at it and realized I need someone more knowledgeable than I am to get it running on Photons multiplayer.

I'm mostly needing some complex instantiations synced and some UMA data synced.

Is room.SetCustomProperties costly?

$
0
0
A question, can I use PhotonNetwork.room.SetCustomProperties at rather high frequency, or should I add my own caching layer that sort of first bundles up the changes and then transmits them in intervals of say 10s? (Typical specific frequency are not known yet by us, as this is for a sandbox universe where people can invent their own creations.) When I say costly, I mean e.g. much faster bottlenecking/ much slower than the normal RPCalls where a max of 500/s/room is fine. Thanks!

Fallback when Photon machine broken?

$
0
0
The EU region was recently down during a critical time for us, and support told me that it was due to one machine's hardware failure. That machine hardware's has since been fixed, but my question is, for future reliability is there any plan we can subscribe to where we would get fail redundancy with a second machine for such cases? Single Points of Failures are always a bit unsettling. Or should we consider adding code on our end that tries to detect outages and then switch to the US region (for another $99/month, I guess). Thanks!

isnt 500 messages/s tooooo low for a battleroyale game?

$
0
0
is there anyway to run the game without doing 1 message per player and second while only sending it to quarter the players in the room? just to get close to the 500 messages range ( i doubt it will even get lower than 500) cuz that will make the game rrreallyy unplayable

Ram Crash

$
0
0
Exception: DynamicHeapAllocator out of memory - Could not get memory for large allocationCould not allocate memory: System out of memory!
Is this a ram crash? And if it is can anyone tell me how to prevent it from receiving it?

RPC ends up on synced player instead of the real remote player

$
0
0
So, I have a PhotonView on my player that gets Instantiated.

The problem is that when I try to send an RPC to the same object on a remote client, the view IDs won't match and it ends up on a synced player, not the one that is controlled locally.

Any ideas?


OnPhotonInstantiate(PhotonMessageInfo info) - info.photonView returning as null!?

$
0
0
I'm unable to find any help on this. All the topics I've found seem to dodge the answer.

So I have PhotonNetwork.Instantiate() in a script spawning a new game object in the scene.

In the new game object, I have another script. Inside that script contains OnPhotonInstantiate(PhotonMessageInfo info).

Logging info.photonView returns null, and trying to use it gives me a NullException error; though the documentation says it should return the same photonView that instantiated the object. Has anyone else got it to work? Am I doing something wrong?

Photon not rejoining Master Server after leaving room

$
0
0
Hi, I'm having an issue where Photon Network doesn't appear to rejoin the Master Server after leaving a room.

In our game, we switch between online and offline modes. This involves changing to a transition (loading) scene, which asynchronously loads the main scene, connects to photon if not connected and joins a room.

The scenario where it fails is when it is in the main scene in offline mode, we click a button to trigger reloading the scene in online mode which:

1. Sets our own offlineMode bool to false.
2. Calls PhotonNetwork.LeaveRoom().
3. Loads the transition scene.
4. In the Start method of a script in the transition scene, our ConnectToPhoton method is called.

The ConnectToPhoton method is as follows:

public void ConnectToPhoton() {
      if (offlineMode) {
                if (PhotonNetwork.connected) {
                    PhotonNetwork.Disconnect();
                }
                else {
                    OnDisconnectedFromPhoton();
                }
              return;
     }
    else {
         PhotonNetwork.offlineMode = false;
    }
     
     // If we are not connected to Photon, connect
     if (!PhotonNetwork.connected) {
            PhotonNetwork.ConnectUsingSettings(GAME_VERSION);
     }
     // Join the lobby if we haven't
     else if (!PhotonNetwork.insideLobby) {
            PhotonNetwork.JoinLobby();
      }
     // Join a random room
     else {
           PhotonNetwork.JoinRandomRoom();
      }
Joining the offline room shows the following logs:
- OnStatusChanged: Disconnect current State: Disconnecting
- OnConnectedToMaster() was called by PUN. This client is now connected.
- OnStatusChanged: Connect current State: ConnectingToGameserver
- Joined a room: offline room // This is our own log which logs the room name when a room is joined

When the room is left in order to switch to an online room, only the method for the OnLeftRoom callback provides logs:
public override void OnLeftRoom() {
            base.OnLeftRoom();
            Debug.Log("OnLeftRoom() was called by PUN.");
        }
I am expecting either of the following methods to receive callbacks after the room is left:

        public override void OnConnectedToMaster() {
            base.OnConnectedToMaster();
            Debug.Log("OnConnectedToMaster() was called by PUN. This client is now connected.");
            PhotonNetwork.JoinRandomRoom();
        }

        public override void OnJoinedLobby() {
            Debug.Log("OnJoinedLobby was called by PUN. This client is now connected.");
            PhotonNetwork.JoinRandomRoom();
        }
The client state of Photon at this point is 'ConnectedToGameserver', which according to the documentation means "Still in process to join/create room.(will-change)". Leaving it to process for a few minutes still does not trigger connecting to the master or joining the lobby.

I am not sure why Photon is not connecting to the Master Server after leaving the room, and appears to be still on the Game server. Any suggestions as to why it isn't, or what I might be doing wrong are appreciated.

In case it's useful, the Start method for our persistent (DoNotDestroyOnLoad) Network Manager script is:
void Start() {
            PhotonNetwork.autoJoinLobby = true;
            PhotonNetwork.automaticallySyncScene = false;
            PhotonNetwork.logLevel = logLevel; // Currently set to PhotonLogLevel.Full, and set to ALL in the inspector
            offlineMode = loadSceneOffline;
 }
I can provide more code blocks and logs if needed.

How do I create 1 host and 3 clients, instead of 4 clients/hosts

$
0
0
Hello,
I am currently creating a game using photon Networking, and I am having a problem with defining a host. Basically I spawn some cubes right now, that are spawned locally on every user's program, and each user's computer does their own calculations for the cube's movement, I want to only create these cubes on one of the client's computer, and then send any death state or movement information to the other clients, so everything is synced to the "host". But so far I have not been able to find a way to do that.

This is an image of the code I currently use to try defining a "host".


This is an image of the code I use to transfer the data to the objects PhotonVeiw in other clients.


Any feedback is appreciated :smile:

PhotonNetwork not connecting to master server after leaving room

$
0
0
Hi, I'm having an issue where Photon Network doesn't appear to rejoin the Master Server after leaving a room.

In our game, we switch between online and offline modes. This involves changing to a transition (loading) scene, which asynchronously loads the main scene, connects to photon if not connected and joins a room.

The scenario where it fails is when in the main scene in offline mode, we click a button to trigger reloading the scene in online mode which:

1. Sets our own offlineMode bool to false.
2. Calls PhotonNetwork.LeaveRoom().
3. Loads the transition scene.
4. In the Start method of a script in the transition scene, our ConnectToPhoton method is called.

The ConnectToPhoton method is as follows:

public void ConnectToPhoton() {
    if (offlineMode) {
          if (PhotonNetwork.connected) {
               PhotonNetwork.Disconnect();
          }
          else {
               OnDisconnectedFromPhoton();
          }
          return;
     }
    else {
         PhotonNetwork.offlineMode = false;
    }
     
     // If we are not connected to Photon, connect
     if (!PhotonNetwork.connected) {
            PhotonNetwork.ConnectUsingSettings(GAME_VERSION);
     }
     // Join the lobby if we haven't
     else if (!PhotonNetwork.insideLobby) {
            PhotonNetwork.JoinLobby();
      }
     // Join a random room
     else {
           PhotonNetwork.JoinRandomRoom();
    }
Joining the offline room shows the following logs:
- OnStatusChanged: Disconnect current State: Disconnecting
- OnConnectedToMaster() was called by PUN. This client is now connected.
- OnStatusChanged: Connect current State: ConnectingToGameserver
- Joined a room: offline room // This is our own log which logs the room name when a room is joined

When the room is left in order to switch to an online room, only the method for the OnLeftRoom callback provides logs:
public override void OnLeftRoom() {
            base.OnLeftRoom();
            Debug.Log("OnLeftRoom() was called by PUN.");
        }
I am expecting either of the following methods to receive callbacks after the room is left:
public override void OnConnectedToMaster() {
            base.OnConnectedToMaster();
            Debug.Log("OnConnectedToMaster() was called by PUN. This client is now connected.");
            PhotonNetwork.JoinRandomRoom();
        }

        public override void OnJoinedLobby() {
            Debug.Log("OnJoinedLobby was called by PUN. This client is now connected.");
            PhotonNetwork.JoinRandomRoom();
        }
The client state of Photon at this point is 'ConnectedToGameserver', which according to the documentation means "Still in process to join/create room.(will-change)". Leaving it to process for a few minutes still does not trigger connecting to the master or joining the lobby.

I am not sure why Photon is not connecting to the Master Server after leaving the room, and appears to be still on the Game server. Any suggestions as to why it isn't, or what I might be doing wrong are appreciated.

In case it's useful, the Start method for our persistent (DoNotDestroyOnLoad) Network Manager script is:
void Start() {
            PhotonNetwork.autoJoinLobby = true;
            PhotonNetwork.automaticallySyncScene = false;
            PhotonNetwork.logLevel = logLevel; // Currently set to PhotonLogLevel.Full, and set to ALL in the inspector
            offlineMode = loadSceneOffline;
 }
I can provide more code blocks and logs if needed.

Connecting with Dubai

$
0
0
Hi,
We've had a few issues getting PUN working from Dubai, the tests done in dubai cannot even create a room, let alone connect with us/join our rooms (in Australia).
We currently have the region set to AU but we have also tried the India server (conveniently in between).

Are there any known photon server issues within Dubai? What is the best region to be using?

Thank you,
Simone
UnleashedXR

Character Duplicate, Start Game when players are ready and nonrestrictive spawn.

$
0
0
This is my game logic:

- player joins game,
- finds and enters a room
- when room master clicks on start room, all player who has a player.customprop[IS_READ]

should load into a new scene(eg: MAP), with master. (more like you have to be ready to join a game even though you are in the room).

And if the game has already started and you ready up, the MAP will be loaded for you.




I have 2 main issues:

- when 1 spawn player, it duplicated it to the number of clients in the room (if i have 2 player, i will end up with 4 characters being spawn, and if i have 3 clients ready i will end up having 9 characters spawned).

- When game have started, and a new client join, photon actually spawns the characters in lobbby after PhotonNetwork.JoinRoom(roomName); not in MAP


psudo code
:RoomsCanvas.enabled
listAllCreatedRooms()
if (clickedOnAnyListedRoom)
PhotonNetwork.JoinRoom(roomName);
:LobbyCanvas.enables
if (masterClicksOnStartGame)
each (PlayerThatIsReady)
SceneManager.LoadSceneAsync("Map");
else
remain in LobbyCanvas.
if (ClickedOnReady && Map.isLoaded)
SceneManager.LoadSceneAsync("Map");

My question is how do i stop charaacter be spawned (x Number_Of_Clients_In_MAP) and how can i stop photon from spawning the players in :LobbyCanvas.enables once i join room


public class Lobby : LobbyInterface
{
[SerializeField] private GameObject loadingScreen;

private void OnJoinedRoom()
{
TeamBalancer.Push();
foreach (PhotonPlayer player in PhotonNetwork.playerList)
{
AddToList(player, true); // list player in room
}
}

private void OnPhotonPlayerConnected(PhotonPlayer photonPlayer)
{
AddToList(photonPlayer, false); // list player in room
}

private void OnPhotonPlayerDisconnected(PhotonPlayer photonPlayer)
{
//for replace we can loop through here
RemoveFromList(photonPlayer);

// Remove player ready count.
if ((bool) photonPlayer.CustomProperties[Constants.IS_READY])
{
Room room = PhotonNetwork.room;
room.SetCustomProperties(new Hashtable {
{Constants.IS_READY, (int) room.CustomProperties[Constants.IS_READY] - 1}
});
}
}

public void OnMasterClientSwitched(PhotonPlayer player)
{
AddToList(player, true); // list player in room
}

private void OnPhotonPlayerPropertiesChanged(object[] playerAndUpdatedProps)
{
PhotonPlayer player = playerAndUpdatedProps[0] as PhotonPlayer;
Hashtable properties = playerAndUpdatedProps[1] as Hashtable;

if (properties.ContainsKey(Constants.IS_READY) && ! player.IsMasterClient)
{
AddToList(player, false);

Hashtable roomProp = PhotonNetwork.room.CustomProperties;
if ((bool) roomProp.ContainsKey(Constants.IS_PLAYING))
{
// start game if player is ready and game has already started.
if ((bool) roomProp[Constants.IS_PLAYING] && (bool) properties[Constants.IS_READY])
{
player.SetCustomProperties(new ExitGames.Client.Photon.Hashtable {
{Constants.IS_PLAYING, true},
});
LoadScene();
}
}
}
}

private void OnPhotonCustomRoomPropertiesChanged(Hashtable roomProp)
{
PhotonPlayer player = PhotonNetwork.player;
Hashtable playersProps = player.CustomProperties;

// a different script sets this property once the master clicks on start room
if (roomProp.ContainsKey(Constants.IS_PLAYING))
{
if ((bool) roomProp[Constants.IS_PLAYING] && (bool) playersProps[Constants.IS_READY])
{
player.SetCustomProperties(new ExitGames.Client.Photon.Hashtable {
{Constants.IS_PLAYING, true}
});

LoadScene();
}
}
}

private void LoadScene()
{
StartCoroutine(loadingScreen.GetComponent().LoadMap(mapName.text, roomDetails.roomSettings.map.icon));
}
Loading Script
public System.Collections.IEnumerator LoadMap(string mapName, Sprite icon)
{
gameObject.SetActive(true);
AsyncOperation async = SceneManager.LoadSceneAsync("Example");
while (!async.isDone)
{
progressBar.value = async.progress;
yield return null;
}
}

DDOL Script
private void Awake()
{
photonView = GetComponent();
player = PhotonNetwork.player;
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}

private void OnSceneFinishedLoading(Scene scene, LoadSceneMode mode)
{
if (scene.name == "Example")
{
StartCoroutine(Wait());
}
}

private IEnumerator Wait()
{
// make sure everyone is in
yield return new WaitForSeconds(3);
photonView.RPC("SpwanPlayer", PhotonTargets.All, player.NickName);
}

[PunRPC] private void SpwanPlayer(string name)
{
Transform location = InMap.instance.GetSpawnTransform(Random.Range(0, 7));
GameObject GO = PhotonNetwork.Instantiate(Path.Combine("Male", "Default"), location.position, location.rotation, 0);
}

also i have PhotonNetwork.automaticallySyncScene = false;

Connecting a client on the same machine as Photon self-hosted server with Public Static IP

$
0
0
Hello,

I am running a self-hosted Photon server on a machine with a static public IP.

I can connect with external clients to this server, and everything works fine.

When I try to connect a client on the same server machine it failes, with connection refused error.

I tried to use the public IP, and 127.0.0.1 and both failed.

How can I make this work, or is this not possible?

Thanks.

Creating Lobby using Photon Chat Channel

$
0
0
Hi,

We have a live multiplayer game. Which uses Photon Realtime and Photon Chat. We have friends list coming from our server and using PUN Chat for online status and group chats.

Now we want to implement a lobby, where creator can invite his friends and then start searching / creating a room. I have an idea to do this using Photon chat channel. Please let me know if this looks good.

- Create a Chat Channel for Lobby and send name of channel to all selected friends
- Once friends subscribe to the channel, they appear in lobby.
- Here they can chat and master client can set game properties like map, mode etc
- Master client Searches / Creates a room with expectedUsers and sends room name to everyone in channel
- Everyone else joins same room because their slots are reserved.

I could just create a room and invite everyone to it but i wanted the ability to persist the group. And search for games and if there is no active game then create one.

Let me know if this approach looks fine. Or is there a better way of doing this.

Thanks
Viewing all 8947 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>