Search Unity

Third Party Photon Unity Networking

Discussion in 'Multiplayer' started by tobiass, Aug 23, 2011.

  1. SiliconDroid

    SiliconDroid

    Joined:
    Feb 20, 2017
    Posts:
    302
  2. Dog-Gamer

    Dog-Gamer

    Joined:
    Nov 9, 2015
    Posts:
    36
    Thank you for the answer, please give me a sec to see if that solved my issue (Unity is opening, I also bet you that your answer will fix the issue)
     
  3. Dog-Gamer

    Dog-Gamer

    Joined:
    Nov 9, 2015
    Posts:
    36
    Yup that fixed it, many thanks
     
    SiliconDroid likes this.
  4. viodf

    viodf

    Joined:
    Apr 11, 2017
    Posts:
    1
    @Dog-Gamer : You are copying code that uses the old version of PUN asset, you will have many other problems if you follow an old tutorial, you can fix the error and the warnings that will follow by changing 'isVisible' to 'IsVisible' and 'maxPlayers' to 'MaxPlayers'.

    As I mentioned since you are following a tutorial for an older version expect some more issues like this, if you get any other errors/warnings I suggest you search PUN's release notes for changes regarding the functionality you are using.
     
  5. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    I guess you need to update to your v1.83. Sorry, v1.82 was buggy.

    If you want to set some values for a network-instantiated object, you can pass those values in PhotonNetwork.Instantiate() as final parameter. The clients that create the GO will run the scripts on those, so in any Awake() method, you can fetch the photonView.InstantiateData and use it (according to what you stored).
    These values can't be changed but sometimes that's just OK.
     
    Last edited: Apr 18, 2017
  6. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Ok that sounds great, but can´t happen how to understand how its done. Does it actually pass params or a generic object?

    I tried this:

    Code (CSharp):
    1.  AI_tankObj = (GameObject) PhotonNetwork.Instantiate ( (keyVal.Value.model.ToString ()),AI_Spawnspot.transform.position, AI_Spawnspot.transform.localRotation,0,keyVal.Value );
    And for the non-master clients was expecting to get the data this way:

    Code (CSharp):
    1. TankProperties[] _AI_TP = (TankProperties) transform.GetComponent<PhotonView>().instantiationData ;
    But I can not even sen the data/object...

    EDIT:
    I guess this is the answer:
    http://forum.photonengine.com/discussion/1577/how-to-use-photonnetwork-instantiate-with-object-data

    I really can´t understand what these &# symbols mean... sorry not a pro. gonna do via RPC as I instantiate the obj I get its photon view and pass the params in teh rpc call individually.

    EDIT2:
    I decided to revisit the object[] approach just in the name of science as I was seeing other ppl asking for the same and still no clear answer clearing the issue. Its quite simple so lets go.

    the data field is an array with type-->object.
    https://msdn.microsoft.com/en-us/library/9kkx3h3c.aspx

    in this type you can basically fit any kind of data type. Only tried with simple types did not try with a custom class ( might work).

    Silly sample:
    Code (CSharp):
    1. object[] instanceData = new object[1];
    2.                             instanceData[0] = "hello";
    3.                             AI_tankObj = (GameObject) PhotonNetwork.Instantiate (keyVal.Value.model.ToString(),AI_Spawnspot.transform.position,AI_Spawnspot.transform.localRotation,0,instanceData );
    Basically, you create the array and add a string data field (could have been an int, float...)

    Where done here.

    In your instantiated object, you can then retrieve the data this way:
    Code (CSharp):
    1.  
    2.        pV = transform.GetComponent<PhotonView>();
    3.  
    4.         object[] data=  pV.instantiationData;
    5.         print ("instance data = " + (string) data[0]);
    This will print "instance data = hello" in the console
    ;)
     
    Last edited: Apr 20, 2017
    Kennai likes this.
  7. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    I did the RPC thingie and data is sync correctly.

    Now I'm having an issue that I was expecting to happen with PhotonView.Owner.name but not with the net id.

    Apparently, each client has a unique and one only name and net id. I was expecting that the photonplayer.ID would be unique per instantiated object and is not.

    Long story short... how should I identify in a unique way the bots from the masterclient player itself for stats, who hits who etc pursposes?

    EDIT: found this:
    transform.GetComponent<PhotonView>().instantiationId
    Is it persistent across al clients?
     
    Last edited: Apr 19, 2017
  8. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Hi,

    I'm making a 2 player game.

    I'm using PhotonNetwork.Instantiate to instantiate three game objects for each player in Awake() and try to deactivate the go's with SetActive(false).

    But only the go's from the master client are deactivated.
    The go's from the remote client stay activated and there's no input control anymore(drag&drop script on the go's).

    Where does this anomaly come from?

    Cheers,
    Nikola
     
  9. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    @ Nikola

    You need to start thinking in a "networky" way.

    For instantiation, as you say use PhotonNetwork.Instantiate
    For destroying PhotonNetwork.destroy()

    Regular unity methods will only apply to the client calling them locally and will not be synced.

    Aside from instantiation you can call events that instantiate stuff via RPC, for example you whant to fire a cannon bullet instead of instantiating the bullet itself it is much better to call a function that triggers the bullet firing locally in all the clients and run the physics etc locally
     
  10. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Hi,
    Thx for your reply.
    On a later moment in the game I want to activate the player's game objects again, so PhotonNetwork.destroy() is not an option.
    When I Photon.Instantiate in Awake() and do a RPC in Start() to deactivate the game objects ( this.go.SetActive (false)) I get a few of these warnings for ID2001,2002,2003: "Received OnSerialization for view ID 2001. We have no such PhotonView! Ignored this if you're leaving a room".
     
  11. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    @ Nikola

    OK I see, can´t tell exactly what's is going on in your case but what I would do certainly is an RPC driven action.
    What I suspect is that when you set active false your object you're deactivating the object with the PhotonView attached as component and that is a good reason for it not to be reachable.

    What I would do in your case is manage these kinds of calls from the transform.root object. Have in there some kind of manager script that receives this kind of RPC calls and activates deactivates specific objects of your character.

    This script of course needs to have a direct reference to these gameobjects so you could 1) make a public variable where you drage these on inspector 2) if they have an specific and unique script attached, in the Awake do a getcomponentinchildren<the script>().gameobject.

    Hope this helps.
     
    Last edited: Apr 20, 2017
  12. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Ok, thx, I'll have a go with this.
     
  13. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
    If you need to use the "gameObject.SetActive" during active network gameplay, it is better to collection photon instantiate in the collection of GameObject.
    In the drag and drop you call the RPC function in it, all players know the index number of the GameObject you want to hide(gameObject.SetActive(false))
    In my post there is an example of how to find the desired index of the collection of RPC(rpc "delete")
    https://forum.unity3d.com/threads/saving-traffic-movement-bots-pun.463821/#post-3024674

    I want to tell you about my pack update. I added a simulation of network behavior of the players to it. Using it, you can observe how network behavior is transmitted.
    By creating a different number of players and different amounts of spawn by the bullet, you can find out when the network data overflow queues occur.

    If you want to know more, click on the link below
    https://forum.unity3d.com/threads/updated-rush-2d-online-tutorial.454400/#post-3039446

    About bugs in the PUN . Very often a red error occurs - "Ev Destroy Failed." Could not find PhotonView with instantiationId" . In points of active network gameplay. When the object photon instantiate during its deletion tries to send network data or change its own, etc.

    And in this project I also get out the same error when the missile hits the player. Not always and sometimes
     
  14. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    @Kurtav,

    Ok, thx, I see where you're going, I'll have a look at it too.
     
  15. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
    https://forum.unity3d.com/threads/saving-traffic-movement-bots-pun.463821/#post-3024674

    There is a collection of photon Instantiate (bot[])

    All players have synchronized indexes of this collection.

    I can sketch three options:
    1)
    example
    The first bot - killed five
    Second bot - killed two
    String kill = "5_2";

    Those who are currently in the room, you initialize them to these data changes, for example through RPC "kill".

    Those who enter this room(new players) - get the property of the room = string kill = "5_2"
    bot[0] = kill[0] ; bot[1] = kill[3];

    But here the problem is - if the new player enters the room where the string kill is actively changing, then it is possible to get out of sync at this point
    You need to lock the game to everyone when a new player comes in, so that nobody interferes with the synchronization of the initialization of the string kill = "5_2"

    2) The easiest option but also the most expensive in terms of traffic transfer
    Each bot has its own variable int kill in OnPhotonSerializeView

    3) General OnPhotonSerializeView for all bots where we pass every second of the line change in which all the kills = "5_2", etc. In One OnPhotonSerializeView
    I can not tell in detail about this example because it is in my paid package of asset store which will soon be released)) excuse me
     
    Last edited: Apr 20, 2017
    TooManySugar likes this.
  16. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    I ended up doing the way you recommended, not that RPC did not work but the way you say has a similar structure to the player properties and the code is cleaner and easier to understand once is revisited. The major drawback of this for me is that it can not be updated so stuff like the name, which in my case is created for the bots AFTER instantiation well, not sure yet how I'll handle that situation. Likely and RPC, not big deal I hope. XD. Also need to find a robust persistent ID solution for the bots, have to check suggested solutions.I Updated my post cause your instructions and the post I found where not too clear so any other noob like me will see easier how to use the instantiation data which is pretty simple once you get the idea.
     
    tobiass likes this.
  17. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    I think the solution you gave me in the other link regarding ohter matter is the best for the Ai bot indexing.
    I will probably keep as is the Human players stuff that now use an index I call neid witch is the photon player.ID. Witch is unique and persistent across clients.

    now the way I look in the stats is :

    Code (CSharp):
    1. if(!_GC.offlineMode  ){
    2.                foreach(PhotonPlayer pp in  PhotonNetwork.playerList){
    3.                    if(pp.ID==bulletDat.killerTankNetID) killerTankName = pp.name;
    4.                }
    So I'll add a property in teh bullet that tells if the bullet belongs to a bot or not to filter it so that I can simply do the same
    but instead of pp.ID use the NetID against the ids stored in a custom list.

    I'll rethink what I wrote tomorrow but in any case it looks like whe're getting somewhere XD.
     
  18. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
    Check whether the bullet is a scene object :
    Code (CSharp):
    1. bullet.GetComponent<PhotonView>().isSceneView
    Bots shoot bullets (objects of the scene (PhotonNetwork.InstantiateSceneObject))
    Players shoot bullets (player objects(PhotonNetwork.Instantiate))
     
  19. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    INteresting! I did not know about -->PhotonNetwork.InstantiateSceneObject
    I should have used this in the first place for instantiating the bots....

    As this caused the PhotonVies.Ismine to return true for the bots true and so I had to add an "AI-Bot" bool for the bots and reinforce the isplayer check with this new param.

    Now I shoot via RPC and that part I like but the instantiation definitely should have been the other way.

    Now that I've all the stuff modified I'll keep my original idea but the good way to do the things is the one you suggest.

    4 my next game... XD.
    EDIT:
    ok,crazy enough--> I already had a bulletdat.owner value. 0 1 2 --> 1 for AI..
     
    Last edited: Apr 21, 2017
  20. FiveFingerStudios

    FiveFingerStudios

    Joined:
    Apr 22, 2016
    Posts:
    510
    I'm using PUN Voice allow with PUN. When I change scenes, PUN Voice unlinks between players.

    Question: When changing scenes, whats the easiest way to make sure the PUN Voice connection is maintained?
     
  21. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
  22. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Hey ppl a quick question...

    If I run the application twice is it ok that I get the same photonplayer.id? I thought it was per instance but may be its like per "computer".
     
    Last edited: Apr 24, 2017
  23. FiveFingerStudios

    FiveFingerStudios

    Joined:
    Apr 22, 2016
    Posts:
    510
    Thanks, I will try putting DoNotDestroyOnLoad for PUNVoice
     
  24. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    That ID is per room, so I assume your second client was not in the same room.
     
  25. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    I think we missunderstood.

    Me running the game twice to test it. I've a netID variable for each player to identify it. The AI bots net id is generated on spawn and passed on the instantiation data, that is ok. But the netID of each player is photonplayer.ID witch I was expecting to be different betwen two instances of the game and is not. May be its because both instances are running on the same computer?

    edit: ok I was using:
    PhotonNetwork.player.ID;
    aparently that did the trick for how the code was before but what I'm in the need for was:
    pV.owner.ID
    Because I was running this code at the top of the object and printing value to the console so it was giving the local player id instead of the tanks owner id for all the tanks...
     
    Last edited: Apr 25, 2017
  26. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    Everyone: We're working on an update to PUN with breaking changes. We will add proper namespaces, fix naming of members and will get rid of useless baggage that might drag someone down.

    If you thought "well, that's missing in PUN" recently, now is the time to let us know. Code, docs, samples?
    Let us know. Mail to developer@exitgames.com for more complex topics.
     
  27. FiveFingerStudios

    FiveFingerStudios

    Joined:
    Apr 22, 2016
    Posts:
    510
    I would say docs that give a bit more detail on use cases for certain Photon options.
     
    tobiass likes this.
  28. Artaani

    Artaani

    Joined:
    Aug 5, 2012
    Posts:
    423
    No local server and Direct IP connect?!

    Hello.
    Currently our game working on old Unity network and we want to move it on more modern technology.
    Since new UNET turned out very raw and incomplete we started to looking on solution from Asset Store.
    First I was super excited while reading of features of PUN, it looks like advanced and polished old Unity network which is great!

    Until I discovered the fact that PUN is cloud only!

    So I can't just host a game on my computer and invite friends to join me via my IP?!
    Any game should be able to do it!

    Why we should pay for CCU if we want to play on our local server?

    Despite this, if two players located in the same city or even room and they are want to play together, why they should create a server which located very far away? It means bad ping, no matter how good PUN is optimized.

    I hope I misunderstood something, but if not, such small flaw completely ruins entire PUN and its features.
    What a shame, because I like how similar PUN to old Unity network and it could be completely replacement of old network and even UNET.
    But lack of local servers is unacceptable! If the game do not allow to host local server - it is disrespect for its users.
     
    Last edited: Apr 29, 2017
    Romenics likes this.
  29. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Asked zillion times:

    http://forum.photonengine.com/discussion/6237/lan-with-pun
     
  30. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    @ tobiass
    Requests for the new PUN,
    1)Make the upgrade "easy". as happened back in time witch did autoupdate the calls to punrpc etc...
    2)RPC send to specific player, like target.masterclient but target.playerid(id) or similar.
    This would have been usefull recently:

    Player enters the game, --->on player connected()--->master client sends information to all the players on the bot count, bot types, and otehr params. The data I send is a serializable dictionary I send as a byte[] as parameter. Sending it to all I think is a total overkill. Being able to get the latest player id for using it with an rpc that is send-able to ansspecific player would do the trick.

    3)Reliable RPC. one of my biggest fears is that an important RPC gets lost such as game over call or similar. A way to ensure an RPC has reached all clients and if not perform a resend. For totally important events such as someone dies, game end etc..

    4)Be able to force players to have latest version of your game by not allowing the server players with olders versions. Have an error callback so error can be displayed properly.
     
  31. R1PFake

    R1PFake

    Joined:
    Aug 7, 2015
    Posts:
    540
    Hello, i have a question about the .net SDK, i want to make a small game which runs in Unity but also on a a normal .net WPF application, so instead of using the PUN SDK, i would like to use the .net SDK and integrate it in the common .net dll of my game, so it would be used from the wpf version and the unity version. But my question: is the .net SDK at the same "level" as the PUN SDK or would you not recommend to use the .net SDK because it's older / not supported anymore? I already already downloaded the .net SDK and checked the example solution, and i saw all the code to create/join lobbies and send custom events and a very important question about the offline mode from PUN, i couldn't find the offline flag/property in any of the .net SDK classes, is the offline mode flag only available in the PUN SDK?
     
  32. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    It's not "Cloud Only" but it's "dedicated servers only". While this is obviously far from meeting your requirements, it's good for other situations.
    You could give Bolt a try.

    The plan is that you would use it for new projects, rather than updating. We add namespaces, try to improve the naming of variables and drop some baggage. Just adding the namespace is difficult to auto-update easily...

    This should be possible in PUN already. However, if you send something to just one player, make sure the game continues if the target player leaved before acting on the data/RPC.

    You should use Custom Properties for this. Then you a) update existing players when things change and b) every new player gets those automatically on entering.

    Done. All RPCs are reliable (unless the target gets destroyed beforehand or a client leaves before this can be executed).

    Good point.

    @R1PFake: Yes, offline mode is only in PUN. Some other features (anything revolving around PhotonView) also.
    Aside from that, you could implement it (as PUN is based on LoadBalancing) and the SDK is not outdated...
     
  33. R1PFake

    R1PFake

    Joined:
    Aug 7, 2015
    Posts:
    540
    The .net SDK from your website is Version 4.1.1.6 but the Version in the PUN Asset Assets/Plugins says Version 4.1.1.11 that's why i wasn't sure, but i checked again and the dlls have different names, that would explain why they have different versions :D
     
  34. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    The versions are related but we take the liberty to skip a Unity SDK release here and there ;)
    It's "new enough" to not be outdated and easily updated, too.
     
  35. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Hi there,

    I have an issue with user input control and 'isMine'.

    On the instantiated game object for each player is a 'drag and drop' script which makes use of a LayerMask.
    The draggable Layer is for all players the same. When the local player drags his own game object everything works fine, but it is also possible to click on another player's game object and drag it in a blurry way for a second or two.

    You can see in the code below that the local player (if photonView.isMine == true) indeed can do a raycast and so can have a hit within the draggable Layer (and thus also the other player's game object).

    Is there a way to avoid being able to touch and 'blurry drag' the other player's game object in this case?

    Code (CSharp):
    1. void Update()
    2. {
    3.      if(!photonView.isMine)
    4.            return;
    5.      if (Input.GetMouseButtonDown(0))
    6.     {
    7.      //See if we hit any draggables
    8.     Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    9.     RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, draggableLayer);
    10.  
    11.     if (hit.rigidbody != null)
    12.     {
    13.      //do the dragging..
     
  36. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
    Well, you threw the raycast. Then I caught the objects with this raycast. Then once again do the check - hit.transform.GetComponent<PhotonView>().isMine , so as not to drag the extra
     
  37. Kumar_saki

    Kumar_saki

    Joined:
    Sep 27, 2016
    Posts:
    2
    Hi, i want to create a tournament system for chess game multiplayer where i can host the game. Currently my knowledge is limited to photon multiplayer where i can host in a lobby. Can u give me guidance how can i achieve my goal?
     
  38. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
    Make the tournament system just in one room.
    Players join the "tournament" in the lobby. But in fact they go all in one room.
    Just a room for the tournament.
    The property of this room says who is playing first in the tournament
    This same property of the room draws a table
     
    Last edited: May 14, 2017
  39. Deleted User

    Deleted User

    Guest

    I want to start making a multiplayer game with max. player size of 8 people. Is it possible that one of the players host the game (client+server) while others join that host? And if the host disconnects, can someone else take the role as the host without disconnecting every other player (host migration)? What product should I use, Photon Bolt? How much will this cost / how much will I save when using this P2P system instead of real servers?
     
  40. SiliconDroid

    SiliconDroid

    Joined:
    Feb 20, 2017
    Posts:
    302
    In PUN, when the original room creator user leaves, the other users remain connected. Host migration is entirely possible it all depends on how you choose to represent and manage game state. Myself, I use a distributed democratic game state that doesn't need to be migrated, only instantiated for new users, provided there is >=1 user in room it just keeps plodding along regardless of who connects/disconnects.

    I could be wrong on some of this, but here's my understanding:

    For price, check asset store.

    If you intend to use photon cloud servers with Bolt then the benefit of bolt is reduced bandwidth useage, but you are limited to 100CCU, be they connected P2P or Via relay.

    If you intend to host your own Zeus server for bolt then CCU is unlimited, however you need a server with 4 public IP addresses to optimize NAT traversal. Also hosting your own Zeus... well some players will not be able to connect simply because NAT traversal is not possible for their routers or mobile phones.

    Photon cloud server with bolt ensures 100% connect ability (same as PUN).
     
    Deleted User likes this.
  41. Stanchion

    Stanchion

    Joined:
    Sep 30, 2014
    Posts:
    269
  42. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Thx! Better than what I had (hit.transform.gameObject.GetComponent<PhotonView>().owner == this.photonView.owner).
    For the moment the input control script is on the player's game objects. I thought, Photon-wise, it would would be easier to keep the input control on the instantiated game objects. But when I make the LayerMask 'draggableLayer' a static, on a trigger event, 'draggableLayer' doesn't change for the input control scripts on the player's other game objects. Or should I work here with SendMessage events?
    But actually 1 input controller script is enough (as long as the player's game objects have a rigidbody2D, they can listen to the script). To try this, I made a scene object with the input control script and a photon view attached. But in this case, it only works for the master client. This looks the way to go, but I can not find why the other player can not drag his game objects.
    For which design should I choose?
    EDIT: In the second design (one input control script for all the player's game object), I can make the dragging work for both players with leaving out the first 'isMine' bool:
    Code (CSharp):
    1. void Update()
    2.         {
    3.             //if(!photonView.isMine)
    4.                 //return;
    5.  
    6.             if (Input.GetMouseButtonDown(0))
    7.             {
    8.                 //See if we hit any draggables
    9.                 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    10.                 RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity, draggableLayer);
    11.  
    12.                 if (hit.rigidbody != null && hit.transform.gameObject.GetComponent<PhotonView>().isMine)
    13.                 {
    14.                     //start with the drag
    But, on a trigger event, the draggableLayer gets changed for both players. So it comes down to how to get the script to work separately for each players.
    So to work around this, in my game manager, together with the player's game objects, an empty game object with the input control script is instantiated. So I get a input control script for each player. The dragging works fine. But, with a trigger event on the remote player, the draggableLayer gets changed on the master client and it applies for both players. The remote player's script is not used in this case.
    How can I make the draggableLayer work for each player separately?

    Cheers,
    Nikola
     
    Last edited: May 15, 2017
  43. o0neza0o

    o0neza0o

    Joined:
    Sep 6, 2015
    Posts:
    165
    guys, im really struggling to get the camera to target the instantiated player. So far i have this -

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.Collections.Generic;
    5. using UnityEngine.UI;
    6.  
    7. /// <summary>
    8. /// This script automatically connects to Photon (using the settings file),
    9. /// tries to join a random room and creates one if none was found (which is ok).
    10. /// </summary>
    11. public class ConnectAndJoinRandom : Photon.MonoBehaviour
    12. {
    13.     /// <summary>Connect automatically? If false you can set this to true later on or call ConnectUsingSettings in your own scripts.</summary>
    14.     public bool AutoConnect = true;
    15.     public GameObject player;
    16.     public Cell cell;
    17.     public Camera ourCamera;
    18.     [SerializeField]
    19.     private GameObject[] spawnPoints;
    20.     public byte Version = 1;
    21.  
    22.     /// <summary>if we don't want to connect in Start(), we have to "remember" if we called ConnectUsingSettings()</summary>
    23.     private bool ConnectInUpdate = true;
    24.  
    25.  
    26.     public virtual void Start()
    27.     {
    28.         PhotonNetwork.autoJoinLobby = true;    // we join randomly. always. no need to join a lobby to get the list of rooms.
    29.     }
    30.  
    31.     public virtual void Update()
    32.     {
    33.         if (ConnectInUpdate && AutoConnect && !PhotonNetwork.connected)
    34.         {
    35.             Debug.Log("Update() was called by Unity. Scene is loaded. Let's connect to the Photon Master Server. Calling: PhotonNetwork.ConnectUsingSettings();");
    36.  
    37.             ConnectInUpdate = true;
    38.             PhotonNetwork.ConnectUsingSettings(Version + "0.1" + SceneManagerHelper.ActiveSceneBuildIndex);
    39.         }
    40.     }
    41.  
    42.  
    43.     // below, we implement some callbacks of PUN
    44.     // you can find PUN's callbacks in the class PunBehaviour or in enum PhotonNetworkingMessage
    45.  
    46.  
    47.     public virtual void OnConnectedToMaster()
    48.     {
    49.         Debug.Log("OnConnectedToMaster() was called by PUN. Now this client is connected and could join a room. Calling: PhotonNetwork.JoinRandomRoom();");
    50.         PhotonNetwork.JoinRandomRoom();
    51.     }
    52.  
    53.     public virtual void OnJoinedLobby()
    54.     {
    55.         Debug.Log("OnJoinedLobby(). This client is connected and does get a room-list, which gets stored as PhotonNetwork.GetRoomList(). This script now calls: PhotonNetwork.JoinRandomRoom();");
    56.         PhotonNetwork.JoinRandomRoom();
    57.     }
    58.  
    59.     public virtual void OnPhotonRandomJoinFailed()
    60.     {
    61.         Debug.Log("OnPhotonRandomJoinFailed() was called by PUN. No random room available, so we create one. Calling: PhotonNetwork.CreateRoom(null, new RoomOptions() {maxPlayers = 4}, null);");
    62.         PhotonNetwork.CreateRoom(null, new RoomOptions() { MaxPlayers = 4 }, null);
    63.     }
    64.  
    65.     // the following methods are implemented to give you some context. re-implement them as needed.
    66.  
    67.     public virtual void OnFailedToConnectToPhoton(DisconnectCause cause)
    68.     {
    69.         Debug.LogError("Cause: " + cause);
    70.     }
    71.  
    72.     public void OnJoinedRoom()
    73.     {
    74.         PhotonNetwork.Instantiate (player.transform.name, Vector3.zero, Quaternion.identity, 0);
    75.         player.GetComponent<Cell>().enabled = true;
    76.         GameObject ourCamera = GameObject.FindWithTag ("MainCamera");
    77.         if (ourCamera != null)
    78.         {
    79.             CameraFollow follow = ourCamera.GetComponent ("CameraFollow") as CameraFollow;
    80.             if (follow != null)
    81.             {
    82.                 follow.target = (GameObject)Network.Instantiate(player, Vector3.up * 5, Quaternion.identity, 0);
    83.             }
    84.         }
    85.  
    86.         player.GetComponent<Cell>().enabled = true;
    87.         Debug.Log("OnJoinedRoom() called by PUN. Now this client is in a room. From here on, your game would be running. For reference, all callbacks are listed in enum: PhotonNetworkingMessage");
    88.     }
    89.  
    90.  
    91.  
    92.  
    93. }
    94.  
    the controller for the character

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.Networking;
    6.  
    7. public class Cell : Photon.MonoBehaviour {
    8.  
    9.     public Camera ourCamera ;
    10.  
    11.     public float Speed ;
    12.  
    13.     private Vector3 Target ;
    14.  
    15.     public float degreesPerSecond;
    16.  
    17.     private bool running;
    18.  
    19.     public float speedWhileRunning = 10.5f;
    20.  
    21.     private float runStart;
    22.  
    23.     private float secondsCanRun = 3.0f;
    24.  
    25.  
    26.     void Awake()
    27.     {
    28.         photonView.RPC ("ChangeMyName", PhotonTargets.AllBuffered, PhotonNetwork.playerList.Length.ToString ());
    29.     }
    30.  
    31.     [PunRPC]
    32.  
    33.     void ChangeMyName(string myNewName)
    34.     {
    35.         gameObject.transform.name = myNewName;
    36.     }
    37.  
    38.     void Start ()
    39.     {
    40.  
    41.         // if ourCamera is null then set the Main Camera to the variable ourCamera
    42.         if (photonView.isMine)
    43.         {
    44.             ourCamera = Camera.main ;
    45.         }
    46.  
    47.  
    48.     }
    49.  
    50.     void Update ()
    51.     {
    52.         Running ();
    53.  
    54.         if (photonView.isMine)
    55.         {//        DrawRay ();
    56.             Vector3 Target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    57.  
    58.             Target.z = transform.position.z;
    59.             Vector3 direction = Target + transform.position;
    60.             if (!Mathf.Approximately(direction.sqrMagnitude, 0))
    61.             {
    62.  
    63.                 float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    64.  
    65.                 transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    66.             }
    67.             transform.position = Vector3.MoveTowards (transform.position, Target, Speed * Time.deltaTime / transform.localScale.x);
    68.         }
    69.     }
    70.  
    71.  
    72.     void Running()
    73.     {
    74.         if (Input.GetMouseButtonDown (0))
    75.         {
    76.             runStart = Time.time;
    77.             Speed = speedWhileRunning;
    78.             running = true;
    79.         }
    80.  
    81.         if (Input.GetMouseButtonUp (0) || (runStart + secondsCanRun > Time.time))
    82.         {
    83.             Speed = 5f;
    84.             running = false;
    85.         }
    86.  
    87.     }
    88.  
    89.  
    90.  
    91.  
    92.  
    93.  
    94. }
    95.  
    Camera
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class CameraFollow : Photon.MonoBehaviour {

    public float interpVelocity;
    public float minDistance;
    public float followDistance;
    public GameObject target;
    public Vector3 offset;
    public Vector3 targetPos;

    // Use this for initialization
    void Start () {

    targetPos = transform.position;
    }

    // Update is called once per frame
    void FixedUpdate () {

    if(photonView.isMine)
    {
    if (target)
    {
    GameObject.FindGameObjectWithTag("GameController");
    Vector3 posNoZ = transform.position;
    posNoZ.z = target.transform.position.z;

    Vector3 targetDirection = (target.transform.position - posNoZ);

    interpVelocity = targetDirection.magnitude * 5f;

    targetPos = transform.position + (targetDirection.normalized * interpVelocity * Time.deltaTime);

    transform.position = Vector3.Lerp( transform.position, targetPos + offset, 0.25f);

    }
    }
    }

    }
     
  44. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    Not sure if I'm missing something.
    When an object gets "network-instantiated", there is a callback for that. In it, you could check ".isMine" in your "dragable"-script and disable/enable it according to that value. If the object doesn't change it's owner, this sets who's controlling it with a one-time check.
     
  45. tobiass

    tobiass

    Joined:
    Apr 7, 2009
    Posts:
    3,066
    @o0neza0o Don't get me wrong but, to have any chance of getting help, explain what's going wrong and where you think the error could be. There are too many self-made problems around, to debug anyone's code, let alone guess what to look for.
     
  46. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Hi @tobiass,

    Thx for your reply.
    The objects do not change owner.
    When a trigger on the player's first game object is fired, I try to disable the respective object by changing the LayerMask. So that the player goes on with his second game object in the changed LayerMask.
    This works actually fine, except that the LayerMask is also changed for the other player, which is not my goal.

    So I thought to enable/disable the player's game objects by using the LayerMask but I can of course enable/disable the rigidbody2D on the objects themselves. In my current design, I can not enable/disable the input controller script, there I use one for all the player's objects. Or should I attach the input control script directly on the instantiated objects so I can enable/disable it per object?
     
  47. o0neza0o

    o0neza0o

    Joined:
    Sep 6, 2015
    Posts:
    165
    Ah, sorry i wasn't clear about explaining. Basically, the problem i am getting is where the camera cannot folow the network instantiated player and well, in the camera the follow script asks for the game object so in the resource folder i dragged and dropped the player into the camera follow script and it still doesn't pick up the player.

    sorry if it doesn't seem clear i struggle to word things XD
     
  48. Kurtav

    Kurtav

    Joined:
    May 24, 2015
    Posts:
    93
    There is one camera in the scene with the "MainCamera" tag
    On the prefab of the player such lines of code -

    Code (CSharp):
    1. public class Control2d : Photon.MonoBehaviour
    2. {
    3.     Transform cam;
    4.  
    5.     void Awake()
    6.     {
    7.         if (photonView.isMine)
    8.             cam = Camera.main.transform;
    9.     }
    10.  
    11.     void LateUpdate()
    12.     {
    13.         if (!photonView.isMine)
    14.             return;
    15.        
    16.         cam.position = new Vector3(transform.position.x, transform.position.y, -5);
    17.     }
    18. }

    I'm reading your comments I see myself two years ago)) I really liked the network but I had a panic and nerves when the players came into my code and everything was mixed up))) and I was confused)
    When anyone studies the network, a multitasking problem occurs. Who controls and how all interact with each other.



    It's okay. More practice and everything will turn out)
    PUN line of code on this topic -

    Code (CSharp):
    1. photonView.isMine
    2. photonView.isSceneView
    3. photonView.owner
    4.  
    5. [PunRPC]
    6. void test(PhotonMessageInfo info)
    7. {   if (info.sender.IsLocal)    }
    8.  
    9. void OnPhotonInstantiate()
    10. {
    11.       object[] objs = photonView.instantiationData;
    12.       bool variable = (bool)objs[0];
    13. }
     
  49. Nikolasio

    Nikolasio

    Joined:
    Dec 6, 2014
    Posts:
    59
    Hi @Kurtav,

    :) I see that my problem lies in the instantiation of the game objects. I'm working on it, thx.
     
  50. JosephHK

    JosephHK

    Joined:
    Jan 28, 2015
    Posts:
    40
    Hello,

    I would like to ask whether it is possible to let the server only remember the LATEST RPCs but not remember all the RPCs with photonTargets ending on Buffered?