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

Room object controller problem when joining new room

$
0
0
Hello everyone.
First of all, i am sorry for my bad english.

Since a week, i found a problem/bug on PUN 2.
I have a scene where there are a lot of photon views. As we know, scene photon views are controlled by the master client.

When i join an existing room (where there is another player who is the master client), i can't control scene photon views. And this is normal.
Next, let's imagine the master client leave the room. I'm now alone, so i become the master client, and the controller of all photon views (yup, i can control them at this moment)
Until there, everything is fine !
Now, i want to leave the room. This is ok, not a problem.
And this is THE bug : i want to create a new room. Fine, i create it. I am now in my new room and I am the master client !
But... all photon views controller are... null... i am not their controller... In inspector, isMine show "false" on EVERY photon views.

PlayerTtl and EmptyRoomTtl are at their default value.
I have the latest version of PUN 2 (v 2.34.1)

So, i really think this is a Photon bug... really annoying and not understandable.

I would like to thanks the person that will help me in advance.

Send an instantiated variable over to a client side float

$
0
0
[
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class NetworkPlayerSpawner : MonoBehaviourPunCallbacks
{
private GameObject spawnedPlayerPrefab;
public float healthintshared; //network characters health to be sent to the client player

public override void OnJoinedRoom()
{
base.OnJoinedRoom();
spawnedPlayerPrefab = PhotonNetwork.Instantiate("Network Player", transform.position, transform.rotation); // Spawn network character

}


public override void OnLeftRoom()
{
Debug.Log ("Player left the room");
base.OnLeftRoom();
PhotonNetwork.Destroy(spawnedPlayerPrefab);
}
void Update()
{
healthintshared = spawnedPlayerPrefab.GetComponent<health2>().healthint; //Sync Network characters health with client player
}
}
]

I'm new to photon and generally pretty new to unity aswell so sorry if this is hard to understand.
I have a gameobject (Network player) that mimics the movement of my games client side player. The Network player also calculates health inside of a script that lists it as a pubic float (healthint). I need some way to copy the value inside of that public float from the instantiated NetworkPlayer to the client side float (healthinshared). Line 27 should be copying the value over but instead im getting the error "Object reference not set to an instance of an object"

Any help would be greatly appreciated, this seems like it should be so simple but nothing I've tried has worked.

Can Pun and Photon Sever be used together

$
0
0
I need Photon Sever to make a local server and I need to open the game after creating the room (like a board game).

I see that I need to use PUN to create a room, but I don't know if I can use PUN when I am using the local server.

Also, I was wondering if it is possible to make an Android app for multiplayer games using a local server?

Unity Photon Pun connect to Photon Server (Self-hosted) on WebGL

$
0
0
Hi, I have downloaded the Photon Server v5.0.12.24499 and follow this guide https://doc.photonengine.com/en-us/server/current/getting-started/photon-server-in-5min. On the Android platform works fine, I can connect to my server by home IP 127.0.0.1, but on the WebGL platform it says UriFormatException: Invalid URI: The format of the URI could not be determined.
In forums I found the solution to add ws:// protocol prefix to the URL after that I get the error Exiting receive thread. Server: ws://127.0.0.1:0 Error: An exception has occurred while connecting.

Has anybody had the same issue?

Thanks.

Can't set a players hat sprite for other players using rpc

$
0
0
In the game I'm making I'm trying to allow the player to change their hats in the game.

I'm trying to do this with an rpc.
The rpc takes input of an int which tells it which index of the hat array all players have in their script to pick.
This int x is then used in the rpc by:

hat.sprite = Instantiate(hatSprites[indexs[x]]) as Sprite;
hatTransform.localScale = new Vector2(1, 1);
hatTransform.localPosition = new Vector3(0, 0, -1);

this is meant to set the child object of the player prefab to the hat sprite from the array, however no matter how I try it never works, I have even tried using the sprite renderer of the main player object but it still does not work.
I know the rpc is working cus I have tested and am able to disable the character whos hat needs changing animator which syncs across the players and its child avatar sprite.

i always get the message :
NullReferenceException: Object reference not set to an instance of an object
at CharacterController2D.spriteTransform (System.Int32 s1) [0x00092] in C:\Users\Fraser\Unity Projects\Hidden\Assets\Scripts\CharacterController2D.cs:196

the 196 line being: hat.sprite = Instantiate(hatSprites[indexs[x]]) as Sprite;

any advice please would be very helpful been stuck on this for a couple days, let me know if u need to see anymore code, the rpc is called by:

myPV.RPC("spriteHat", RpcTarget.All, s1); (s1 is the int of the hat index).

RPC method not found

$
0
0
Using RPC throws an error:

RPC method 'HandleHumanoidDead(Boolean)' not found on object with PhotonView 1018. Implement as non-static. Apply [PunRPC]. Components on children are not found. Return type must be void or IEnumerator (if you enable RunRpcCoroutines). RPCs are a one-way message.

The method is not static, there's no same named method, the parameter is correct, and photonView exists, and the script is attached in the game object that both have photonView and this script, and also has [PunRPC] attribute.

I only tested with offline mode and but it is supposed to work here too.

Here's the code:
protected override void OnDead(DamageType damageType, float damageGiverDistance) {
    base.OnDead(damageType, damageGiverDistance);

    bool carnage = damageType == DamageType.Explosive && damageGiverDistance <= 2.5f;
    photonView.RPC("HandleHumanoidDead", RpcTarget.All, carnage);
}

[PunRPC]
void HandleHumanoidDead(bool carnage) {
    if (carnage && GameSettingManager.Instance.BodyAmputation == BodyAmputation.On) {
        ExplodeBody();
    }
    else {
        PlayDead();
    }
}

Already tried to clear and refresh the RPC list, but doesn't make any change. Unity 2019.1.0f2 and PUN2 4.1.6.3.

How to connect to your friend room in pun 2?

$
0
0
Hi guys I am using pun 2 as you can tell from the title and I want to ask how can I join to my friend party?
I have a list of my friends but I do not know how to do it pls help I am stuck on it a lot of time. I know there is a thing that called expected players and I check the Matchmaking Guide. didn't understand it ):

Problem with Room.SetCustomProperties not working

$
0
0
I've been trying to update custom properties after a room is created and having trouble. SetCustomProperties does not seem to return a value and when debugging cannot be stepped into. If I remove virtual from the definition of SetCustomProperties, I can step into the function but it does not fix the problem. In the example below, all the print statements up to "set id for lobby" will print and the last two print statements will not print.

By default, the room is created with the custom property "id" equal to 0 and any players that join will see the default id and not the updated one. If anyone has insight into this problem it would be appreciated.
ExitGames.Client.Photon.Hashtable properties = curRoom.CustomProperties;
print("before adding id");
properties["id"] = steamLobby.Id;
print("set id for lobby-------------------" + steamLobby.Id + curRoom.Name + PhotonNetwork.CurrentRoom.Name);
print(PhotonNetwork.CurrentRoom.SetCustomProperties(properties));
print("after set custom prop-------------------------------------------");

An annoyance With PhotonNetwork.Destroy()

$
0
0
Hey Guys! I am trying to find a way to fix my Issue. I do not know why but for some stupid reason Photon Decided to not add a time parameter to PhotonNetwork.Destroy So I have to find a way around delayed destruction; I am trying to make a gun that shoots (Which is simple enough) but not in Photon.. Here is my code so far.. [code]using UnityEngine; using System.Collections; public class Attack : MonoBehaviour { public GameObject Bullet_Emitter; public float Bullet_Forward_Force; void Start() { } float maxTimer = 1; float maxReloadTimer = 5; float timer = 0; float reloadTimer; float intervealTimer; float maxIntervealTimer = 2; int shotsTaken = 0; bool timerIsOn = false; bool reloadFase = false; bool Shoot = false; void Update() { intervealTimer -= Time.deltaTime; if (reloadFase) reloadTimer -= Time.deltaTime; if (timerIsOn) timer -= Time.deltaTime; if (Input.GetKeyDown(KeyCode.Mouse0)) { if (!reloadFase) { shotsTaken++; timer = maxTimer; timerIsOn = true; Debug.Log("Shots" + shotsTaken); Debug.Log("Timer" + timer); Shoot = true; } else { Debug.Log("ReloadFase On"); Debug.Log("Reload Timer" + reloadTimer); } } if (shotsTaken == 3) { reloadTimer = maxReloadTimer; reloadFase = true; shotsTaken = 0; } if (reloadTimer < 0 && reloadFase == true) { reloadFase = false; reloadTimer = 0; } if (Shoot && intervealTimer < 0) { GameObject Temporary_Bullet_Handler; Temporary_Bullet_Handler = PhotonNetwork.Instantiate("projectile", Bullet_Emitter.transform.position, Bullet_Emitter.transform.rotation, 0) as GameObject; intervealTimer = maxIntervealTimer; Shoot = false; } if (timer < 0 && timerIsOn == true) { PhotonNetwork.Destroy(); timerIsOn = false; timer = 0; } } } [/code] My problem is on line 80, as you can see I cannot get Temporary_Bullet_Handler.. this would be much more simpler if Photon added the delay feature. What the script is in short: The player can shoot in 3 bursts (shotsTaken) once shotsTaken is true, reloadFase turns true which turns on the reload timer, reloading it. The timer is how long it takes to destroy the bullet, and timerIsOn is just double checking that the timer is on. I have no real way of despawning the bullet with a delay (Well of to my knowledge) Please Help!

Shooting RPC sometimes not called on other clients

$
0
0
Hi, I am currently making an FPS game and I have run into an issue.
Currently, my player is able to shoot raycasts and stuff. However, whenever I move at high speeds and shoot another player, the shots do get registered on the client to fired the shot, but often not on the other clients.
Here is my RPC_Shoot code:
[PunRPC]
        private void RPC_Shoot()
        {
            switch (playerSetup.currentWeapon.name)
            {
                case "Pistol":
                    pistolSFX.Play();
                    break;
                case "M69 Assault Rifle":
                    rifleSFX.Play();
                    break;
            }

            RaycastHit _hitInfo;

            if (currentWeaponObj != null)
            {
                Referencer weaponRef = currentWeaponObj.GetComponent<Referencer>();
                weaponRef.particleObj.Play();
            } else if (avatarWeaponObj != null)
            {
                Referencer avatarWeaponRef = avatarWeaponObj.GetComponent<Referencer>();
                avatarWeaponRef.particleObj.Play();
            }

            if (Physics.Raycast(rayOrigin.position, rayOrigin.forward, out _hitInfo, 1000))
            {
                Debug.DrawRay(rayOrigin.position, rayOrigin.forward * _hitInfo.distance, Color.yellow);
                //Debug.Log("Ray hit an object");
                if (_hitInfo.transform.tag == Constants.Tags.PLAYER && _hitInfo.transform != transform)
                {
                    Debug.Log("Hit a player");

                    PhotonPlayerSetup _playerSetup = _hitInfo.transform.GetComponent<PhotonPlayerSetup>();
                    int _damage = playerSetup.currentWeapon.damage;

                    _playerSetup.Damage(_damage, transform.GetComponent<PhotonPlayerSetup>());
                    Debug.Log("Player Took : " + _damage + "; Current Player Health: " + _playerSetup.playerHealth);
                }
            }
            else
            {
                //Debug.DrawRay(rayOrigin.position, rayOrigin.TransformDirection(Vector3.forward) * 1000, Color.white);
                Debug.Log("Ray didn't hit an object");
            }
        }
For some info, I am using a Rigidbody View with velocity and angular velocity synced, I do find it kind of weird that I have to sync my camera with a Transform view as well.
I highly suspect that the client isn't synchronizing fast enough for the client to cast the ray onto other clients.

I have been trying to solve this problem for a long time and this is probably the only big problem in my way currently.
Any help would be greatly appreciated!

P.S. I don't really know how to write a question like this sorry if I am being unclear...

How do I view the custom room properties of multiple rooms before my client joins the rooms?

$
0
0
I'm somewhat new to photon so apologies if there's an obvious answer.

I'm trying to implement a method of checking version just for testing purposes. I want the host of a room to add their version to the CustomRoomProperties hash table so if another client tries to join and has the wrong version then they know that they need to pull the latest build of the game from git.

I'm using this code to set the version in the custom room properties.
public void CreateRoom()
    {
        RoomOptions roomOptions = new RoomOptions()
        {
            IsVisible = true,
            IsOpen = true,
            MaxPlayers = (byte)roomSize,
        };

        ExitGames.Client.Photon.Hashtable customProps = new ExitGames.Client.Photon.Hashtable();
        customProps.Add("v", float.Parse(Application.version)); // v stands for version and is the key for the table

        roomOptions.CustomRoomProperties = customProps;

        PhotonNetwork.CreateRoom(PhotonNetwork.LocalPlayer.NickName + "'s Room", roomOptions, TypedLobby.Default);
    }

Here's my code for the OnRoomListUpdate.
public override void OnRoomListUpdate(List<RoomInfo> roomList)
    {
        if (roomList.Count > 0)
        {
            for (int i = 0; i < roomList.Count; i++)
            {
                Debug.Log("Custom properties: " + roomList[i].CustomProperties?.Count);
                // This has been returning 0 and I can't access roomList[i].CustomProperties["v"]
            }
        }
    }

The issue I'm having is that when I try to access the CustomRoomProperties of the room from this function the hash table is empty. I'm not sure what I'm doing wrong and I know there are other ways to achieve what I'm trying to do but I would like to figure out the solution to this problem.

Thanks!

Check Players In Room

$
0
0
Hello everyone! I'm trying to create a little multiplayer videogame in C# with photon and Unity... I want that (when player is in a room) there is a text on screen which show the numbers of players in the room. Is it possible? Thanks, LeoMantooo.

Photon cloud returning Regions mismatch error today

$
0
0
We suddenly started getting this error from photon's cloud servers in all our branches today, anyone else seeing this?

OperationResponse 230: ReturnCode: 32767 (Regions mismatch). Parameters: {} Server: MasterServer Address: 5.188.110.5:5055

Prefab disappearing.

$
0
0
Hello,

So i am trying to use PUN for my unity networking. And i am starting my game and my prefab in my launcher script disappears but when i comment out PhotonNetowrk.ConnectUsingSettings();

The prefab stays

does anyone now why this is


Thanks
Yeahyeah213133

PhotonNetwork.ServerTimestamp reads completely different values

$
0
0
I read a discussion that using PhotonNetwork.ServerTimestamp can replace wrapping issues in PhotonNetwork.Time. So after implementing PhotonNetwork.ServerTimestamp I get this value when I am outside the room "187996267", and after joining the room I receive "-1687035466". Both values are completely different, what is the reason for that? anyone, please explain it.

Having only one if the same gameobjects in a scene

$
0
0


Hi!

I am making a multiplayer game in unity for the first time and In the game I have a SpawnEnemies gameobject that spawns enemies. Here is the SpawnEnemies script:
using System.Collections;
     using System.Collections.Generic;
     using UnityEngine;
     using Photon.Pun;
     
     public class SpawnEnemies : MonoBehaviourPun
     {
         public GameObject enemy;
         public EnemiesLeftBarScript enemiesLeftBar;
         public PlayerController[] players;
         public int maxEnemies = 50;
         public static int enemiesLeft;
         public Transform[] SpawnPoints;
     
         private void Start()
         {
             enemiesLeft = maxEnemies;
             enemiesLeftBar = FindObjectOfType<EnemiesLeftBarScript>();
             enemiesLeftBar.photonView.RPC("SetMaxValue", RpcTarget.All, maxEnemies);
             StartCoroutine(SpawnEnemyCoroutine());
         }
     
         IEnumerator SpawnEnemyCoroutine()
         {
             players = FindObjectsOfType<PlayerController>();
             if (StartGameScript.gameIsStarted && enemiesLeft >= 0 && players.Length > 0)
             {
                 PhotonNetwork.Instantiate(enemy.name, SpawnPoints[UnityEngine.Random.Range(0, 4)].position, Quaternion.identity);
             }
     
             yield return new WaitForSeconds(1);
             StartCoroutine(SpawnEnemyCoroutine());
             StopCoroutine(SpawnEnemyCoroutine());
         }
     }

The problem that I am having is that when you play multiplayer there will be several SpawnEnemies gameobjects and more enemies than intended will spawn because of that. How could I fix that? I'd greatly appreciate any help. :)

RaiseEvent or Update Custom Room Properties

$
0
0
Hello,
I'm developing a quiz game, for 2 players, where both of them should answer a given question simultaneously on a limited time. After time ends, I want to collect answers, and display for each player the answer of the opponent.
I'm facing some difficulties to decide whether I should raise events to the server, or just create some custom room properties and update them accordingly?

What is the right approach here?

Client Timed Out Problem

$
0
0
Hello , so I am getting Client Timed Out , i did some research on why this is happening (i dont know if this is the real issue) and come up with The cause of the problem is it has to simulate and sync all player data to all clients, have to reduce simulating data size, maybe by changes data structure.

so should I check only the data structure of the RPC methods only? also is there a way to see which method using the most usage of the internet leads to disconnect (Client Timed Out Error).
any help will be appreciated

Why RPC's don't execute in additive scene?

$
0
0
I load main scene and via script load additional scene with UI.
void Start()
{
        photonView.RPC("LoadUI", RpcTarget.MasterClient);
}

[PunRPC]
private void LoadUI()
{
      SceneManager.LoadSceneAsync(UISceneName, LoadSceneMode.Additive);
}

There is a script in the UI scene that allows masterClient to start and stop a timer that is reflected to all players. Starting and stopping are done via RPC methods.
public void StartTimer()
{
    StartButton.gameObject.SetActive(false);

    photonView.RPC("ShowTimer", RpcTarget.All);

    StopButton.gameObject.SetActive(true);
}

[PunRPC]
public void ShowTimer()
{
    Timer.gameObject.SetActive(true);
}

public void StopTimer()
{
    StopButton.gameObject.SetActive(false);

    photonView.RPC("HideTimer", RpcTarget.All);

    StartButton.gameObject.SetActive(true);
}

[PunRPC]
public void HideTimer()
{
    Timer.gameObject.SetActive(false);
}

When the UI was not a separate scene, everything worked fine, but after the separation the RPCs doesn't execute.

Photon Round System

$
0
0
Hi I'm doing a round system and I want to make that if I kill all the other teams and when I kill all of them I get a point, I did an int for the two teams, and then if it reaches 0, you add a point, but the problem is that I try but if someone leaves Photon takes 1 from the two teams with the PlayerLeftRoom, but there is also another problem and it is that sometimes I will say that there are 3 in the red team but in the game, there is 1 in the red team and 2 from the blue team, so I don't know what to do if someone knows another way please tell me
Viewing all 8947 articles
Browse latest View live


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