#archived-networking
1 messages ยท Page 16 of 1
I'm guessing so, afaik they added a bunch of new features but they're a bit too advanced for me so I can't really speak about it
Great I'll go with 22 then
New things to learn as well
If your project is already into development, I wouldnt upgrade
the only reason I suggested the new unity version is because I thought the ngo package version might be tied to it but if it's not don't bother
If this is a new project, then might as well
I started it today morning lmao
Ah ye then doesnt matter
to upgrade you just download the new version and then change it in the unity hub
Okk will be back after its done eating my 11gbs
Oh okk tysm
but then to fix the problem you had with the input system I think you should try this
I don't think it's a problem with ngo's version since it wasn't giving you any errors
I changed to new version now there is one new package netcode for entries do i use it? @candid ginkgo @shrewd junco
that depends on if you want to use ECS
but thats a whole other new system that you probably don't need for your player movement
Great
Also I wanted to ask there is a new check box sync player transform in network object itself so I need to use client transform or i don't need transform anymore or network transform works like cleint one now?
you still need to have a player transform component
not sure how it works exactly in the background but the docs mention that to use the networktransform component you need to have the sync transform checked in the networkobject component
either the clientnetworktransform or the networktransform
But I should use client side so it does not work for host only right?
Also now I am unable to drag my prefab to the network prefabs list why?
well the difference between client side and network transform is just who has priority over the movement
Isn't server side harder?
you have to create a networkprefablist object in the project files and then add it to that object
yeah idk why it got changed between versions
Well nvm- thanks tho
it's sorta harder but that's basically how 90% of multiplayer games work so I feel like it's something that can be interesting when doing a multiplayer game
but that's for you to decide
Well i couldn't find any tutorials that's y I don't know
yeah there aren't that many I had to use the docs for most of what I did
Okk I'll learn like this for now I'll when I get the hang of it then I'll try it
good luck, lmk if the script I gave you earlier helped or if it didn't change anything
Okok tysm
@candid ginkgo ya so apparently I did not do anything just used the old script just checking and it's working lmao
lmao nice
I think the child network object won't be spawned over the network
you probably have a child object which has the networkObject component which I don't think is necessary if the parent has one
Oh
Let me try
iit got fixed
but
if(canShoot)
{
GameObject spawned = Instantiate(bullet,point.position,gun.transform.rotation * Quaternion.Euler(0, 0, -90));
spawned.GetComponent<NetworkObject>().Spawn(true);
}
but it is not spawning
are you spawning the bullet from the server ?
I'm pretty sure clients can't spawn objects
but i m the host
oh mb
I guess just add prints evrywhere and see if it even goes in the if statement
I mean if anything it should be a server rpc since spawning is supposed to only be doable by the server
but idk if even the host doesn't spawn it it's weird
you did make your bullet a network object and added it to the prefab list right ?
maybe try making the 2 lines that spawn the bullet a server rpc just to be sure that the problem doesn't come from the fact that it might be called by a client
just as a way to clear that out
but codemonkey did it like this only
oh ok
also can a server rpc can be called through client
yeah that's the point
they're made so that client can run a bunch of code on the server
ohk let me try adding a rpc calla
but codemonkey also showed client and server rpc shouldnt it be the same then
wdym the same ?
what is the difference?
server rpcs are called by clients to run on the server and client rpcs are called by the server to run on the clients
no they are two different scenes technically
if I disable an object on my client it will still be enabled on the server
so if I wanted it to be sync'd I would disable it on my client and then send a server rpc that disables it on the server
no because a client rpc runs on code on a client
and spawning can only be done on the server
spawning is different from enabling/disabling/instantiating
icic ig i kinda get it so can i call a server rpc while being a client will it work?
it should but idk if in that case it will
y?
because since you were the host and the host it both a client and a server it should have worked anyway
true
might as well try to make a server rpc to be 100% safe
you'll need it anyway if you want other clients to shoot
icic
okk
let me
try adding a debug again
yes
:))))))))))))))))))))))))))))))
so
i m dumb
it was not being called
yes lmao
let me just implement rpc now
is multiplay the only place where i can host it?
idk about that I'm using steam so it's peer to peer
Yo how do I check if the player has connected to the server on StartClient?
You can add a debug in NetworkManager.Instance.OnClientConnected()..
No. In an if statement
Oh wait
Ok I see
Can someone tell me how , when using netcode for gameobjects , I can spawn a player object for both host and client when its bult for standalone but for android only the host spawns a player object not the client
GetComponent<NetworkObject>.spawn/despawn(true)
Make it a server rpc if u want other to be able to use it
Can someone suggest me a tutorial on how should I go about making a main menu and a lobbie list I can't find any on YouTube
if (_equippedSlot.childCount != 0)
{
ReturnEquippedItemToSlotServerRpc(_equippedSlotReturnLocation);
}
if (_slots[value] != null)
{
EquipItemFromSlotServerRpc(value);
}
}
[ServerRpc]
private void EquipItemFromSlotServerRpc(byte value, ServerRpcParams rpcParams = default)
{
Inventory inv = NetworkManager.ConnectedClients[rpcParams.Receive.SenderClientId].PlayerObject.GetComponent<Inventory>();
_slots[value].GetComponent<NetworkObject>().TrySetParent(inv._equippedSlot);
inv._equippedSlotReturnLocation = value;
}
[ServerRpc]
private void ReturnEquippedItemToSlotServerRpc(byte value, ServerRpcParams rpcParams = default)
{
Inventory inv = NetworkManager.ConnectedClients[rpcParams.Receive.SenderClientId].PlayerObject.GetComponent<Inventory>();
inv._equippedSlot.GetChild(0).SetParent(inv._slots[value]);
}``` how can i make other clients change or set a objects parent to a different player so if i set the parent of a item to the player i want other players to see the change how would i go about that im used to pun2 so im really lost
ik this setup would only inform the server but i cant find a way to let other clients see the change
using NGO
Hi I have a serverRpc that runs well and inside I had a function that only ran on client so I changed it to a serverRpc as well and now it doesn't run at all. It's on a NetworkBehavior with NetworkObject. Any ideas? ๐ฅด
what does [ObserversRpc] mean?
You can't call a serverrpc from a serverrpc
If you call a function from the server it will always be ran as the server, unless it's a client rpc
It doesn't matter that your client can call a function, as it will be ran with the clients variables anyway (which are either server authoritive, or not present on the client)
hi guys! for more complicated player prefabs how would you go about netcode for it? ie. for my player movement code i'm using a finite state machine, and most netcode explanations say to just check for owner, which im not sure how to do in this case
if(!IsOwner) return;
put that in the beginning of a method
that'll make sure to prevent any other clients interfering with other clients scripts
can someone help me with a netcode issue? willing to hop on a call and show them or just via dms
theres a problem with an item spawning thats meant to follow the player, yet it just either stays at the middle not registering for the other player, or just doesnt register
if u need more info dm me
How does it work??? Is it a method? if statement? Method call?
Anyone know how to check whenever a client has connected to a server?
OnClientConnected is a method call.. google searchit
Iโm new to Netcode for gameobjects. I wanted to know if there is an event or method which is called on the server when a new Client connects to the game. so that we can do some initial setup for that Client
I've been google seaching for a little while and smh didn't find this
Hey no worries
thanks tho
No problem , you can ask chtgpt also for an example usage in unity using c#.
I don't use ai, unfortunately. I like putting more pain on my shoulders
Yeah , its a nice tutor , good to bounce ideas off of
Dont suggest people use chatgpt. Anyone that suggests this just shows they dont really know what they're doing. Its trained off data last updated 2 years ago, and it has no clue about anything related to current ngo.
AI generated stuff also isnt allowed in the server
If you can show code, itll probably be easier to help. Sorry to say but no ones really gonna DM you to help you for free.
Shows what you know guy , it can provide updated info for a lot of stuff. And its not used as a crutch but as a tutor..
I'm a self taught and self published dev , i know enough
im not here to argue if it can be used as a tutor, i am saying that it quite literally has no info on NGO.
i dont care if you personally use it, just dont suggest others do especially for ngo. Its clear when code is written by AI, and its even worse when someone asks for help on code they didnt write or understand
That's what i use ai for explaining code to me and dissecting bugs
But i can also agree it doesn't always provide the best info. Like unity's new input system
I hope whatever Unity's AI project will be it'll include an AI that has been fed all the docs so it can give clear explanation and help with using recent systems
also nothing to do with that but anyone knows if there's a way to implement client side prediction for rigidbody movement without having to essentially rework the networkTransform component ?
the only part that should really matter is if your world has rigidbodies that your character is supposed to interact with, the actual client side prediction part/server reconciliation should just be the same where both are running the logic and the server corrects it if its wrong
if the client is supposed to predict how it work running into another rigidbody.. im not sure there because im trying to solve the same issue and i hate it
but to implement basic transform synchronization did you have to remove the networkTransform component and make your own ?
cuz I don't see how it's possible to keep using it since it only let's you change the transform from the server
same goes for network rigidbody
yes you dont need the network transform, there are some tutorials that go through how to implement it. also i havent actually implemented it myself, because with rigidbodies the velocity part is somewhat annoying if you need players to push stuff around
yeah from what I read it seems pretty doable for character controllers but physics seem to be a lot harder to manage
I don't think I'll have to care too much about predicting player's pushing around stuff since the main reason I used a rigidbody was to be able to maintain the player's velocity when doing certain actions
if you have any good tutorials would you mind sharing them I've seen a couple but they never actually used NGO so I'm wondering how it works implementing it in a ngo project
like does having synchronize transform checked matter at all or is it only useful for the networkTransform components
the thing is each player will see the others as if they dont have velocity
isn't that already the case when using NetworkRigidbodies since they are set to kinematic on clients ?
https://www.youtube.com/watch?v=WvYRtDJnkcg
this is one that i skimmed through when looking at resources for facepunch, its the only one i really looked at
yes, which is quite annoying for my game at least. I need players to push around stuff in mine
isn't there a way to temporarily make them not kinematic for your calculations ?
I saw this video where the guy doesn't really go too much into details about how it works but in the comments he linked a github page where he explained how he implemented it : https://www.youtube.com/watch?v=G93XdHNjONQ&t=12s
I have been working on client side prediction for 2 whole months now, and i finally managed to get it to work smoothly
my calculations will be pretty much every second, since my game is all physics based :p
there will be many resources, tbh it doesnt matter what you use because the concept is just the same
yeah fair enough
doesnt matter as long as they dont make a mistake i mean
I'm gonna have to read up on how physics simulation works on unity because I think the guy mentions that to have it properly work you need to stop the auto simulation which means fixedUpdate becomes unusable and use a tick system in the update instead
is there a good solution to having a "Pickup" of an object currently u can only have one networkObject on a prefab so i have one on the root, and u cant have one on the hand to parent to, so u have to either like fake the position or something? does anyone know a good workaround or solution to parenting a networkobject to a transform
saw something abount parent constraint or spawning the hand and parenting it under the player on network spawn
using NGO
I never tried doing any pickup systems but if you look into the client driven sample I'm pretty sure it has a pickup system
it's client side but it might still be helpful
alright ill check it out
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
i beleive on this i just looked and it parents it to the transform so just the root not a nested object so apparently unity thinks this is the best solution!! there smart
Does anyone here have experience with Photon Fusion? Do NetworkedObjects get destroyed when the network runner gets destroyed?
I have a NetworkSpawner object in a scene that gets destroyed when the network runner gets destroyed (i.e. when the host leaves). I want to stop it from getting destroyed. How do I do that?
The only way is way a custom network prefab pool. But generally you want to have them destroyed when the networked session ends as they will no longer function properly without the runner.
Also there's a Discord specifically for Photon you can join via the dashboard
Okay. Actually, I want to implement host migration. When the host leaves, we have to shutdown and start a new Network Runner. I am losing important data when my network spawner script is refreshing.
Fusion has built in host migration.
Which is the only proper way to implement this. It is much better than a manual implementation
I am using that. But from tutorials I understand that I have to make connection tokens to assign each player with their in game players
In my case, cars
Yo I'm kinda confused right now. I made a script where a ui enables and disables it self whenever a client triggers a collider. I didn't expect it to work cause I thought that I need to do some networking so that whenever a client triggers the collider it wouldn't enable or disable any other client's ui. But it seems like everything works fine. Why?
Oh wait I guess it makes sense. Without the networkObject or any code it won't send the changes to the server so it's all good
How do I despawn a collided object something like this?
I'm trying to despawn an object for everyone in the server
In Unity, you typically create a new game object using the Instantiate function. Creating a game object with Instantiate will only create that object on the local machine. Spawning in Netcode for GameObjects (Netcode) means to instantiate and/or spawn the object that is synchronized between all clients by the server.
I think I'm facing something also related to the prediction issue? but it behaves strangely so I'm not sure which part should I improve.
The child components of a prefab is pretty leggy and was not sync as a whole unit in other client's view.
I'm having issues with the serverRpc.
You can't pass a gameobject in a serverrpc, you can have a script on the gameobject which has a public destroyServerRpc function, which just despawns and destroys this.
This way you can call it from any client
I've seen that most people don't even use serverRpc function to despawn objects. Unless that was only in the oldest version of NGO
That worked thanks
Never mind it didn't
can you even despawn an object that was manually added to the scene in the editor?
You aren't handling that logic on the server
Sorry I didn't realise I didn't have the networkBehaviour on that script
topolgy
Im trying to play my coop game with friendsusing hamachi
but it doesnt seem to work
the tutorials I saw use zerotier but it doesnt open for me
what should I do
what ip does your coop game use to host the server? localhost=127.0.0.1? 0.0.0.0? you want 0.0.0.0 for opening it up to all network interfaces
Hi guys i am having this problem with Vivox,can you help me?
ipv4 or ipv6?
or am I misinterpreting something
that is ipv4
so I should set it to 0.0.0.0?
yes
thank you
yo! How do I find the player GameObject of the owner in a gameobject that contains all the clients? In UNet there used to be a NetworkIdentity but in NGO there isn't. Any other way to do this?
still doesnt work
can't tell your more without knowing specifics of your networking solution
does it work locally?
by locally you mean when I build the game and run it in editor at the same time
?
yes and on your local network with another machine
how do you try to connect via hamachi?
were just connect to the same network
I meant how does your lobby joining work? do you enter an ip and port?
I thought you could just press client
using fishnet
when connected to the same network
and thqat would work
I don't know about fishnet but no, you need to tell your game where to connect to. Have you every tried your game on different machines?
An ip address points you to another pc, you need to tell the game which pc the server is, if you only tested on your own machine it has a default value for hosting with localhost and the client will defaultly connect to that (atleast in most networking solutions, no clue of fishnet)
you need to change that and than the other person can join via the given hamachi ip adress
I always forget the reply thing @upbeat pine
I only tried on the same device but I reckoned it would work the same
Ill try that thank you
no it sadly doesn't and if you ever want to release your game, this gets more complicated
I wrote a more detailed explanation of how to do it without IPs here
@upbeat pine
?
how to spawn player at a given location in multiplayer in netcode
Never mind I figured it out. I got the object that contains all the players in my script and did a foreach loop and looked for the player that is IsOwner = true
Hi, between photon fusion and mirror. which one is better and why?
Scratch that. That is wayyyy to long. I used this instead NetworkManager.LocalClient.PlayerObject.transform
Hi, I'm trying to create shooting mechanic in my game. In short player spawn bullet locally then send rpc to other clients to spawn local version of bullet (bullet is not network object). As you can see on image it creates weird effect. I think it can be a problem with player position interpolation but I'm not sure. Do you have any idea how to fix it?
can you try how it looks when handling the spawning completly in the clientrpc?
so your playerWhoShoot variable would be used to determine to set data.damage and not to return
You can slightly reduce the differences by checking out the latency and adjust the bullet position accordingly. E.g. if a player has 1s lag, then after spawning his bullets you should simulate how the projectile would behave during this time, moving it further and potentially hitting something.
Btw, the starting parameters should be calculated on the server, unless you want to give cheaters an opportunity to modify the app to spawn their bullets directly inside of an enemy.
Bullet position is correct. Problem is with player position
Player position is interpolated so it can create that weird effect
Without interpretation shooting is correct but player move looking terrible
You should first in update check for input and if player can shoot and then if yes use serverRpc to spawn bullet
In your code shooting script only run on server
Got it, now I have a problem where if I shoot on the client, it wont rotate where the mouse is, just on the host:
you are only showing part of the relevant code
you don't show where rotZ is set, which is very very relevant to the issue
also none of the previous messages in this channel have been about your issue lol, they were sent hours ago
I deleted it it wasnt relevant
yes, so in your current code, only the client knows what their rotZ variable is
the server does not know
So it should become a networkvariable?
no
you should send it with the rpc, as was recommended in #๐ปโcode-beginner
as a parameter
you said it didn't work, but you need to show your attempt
Okay 1 second
Now it works like this @abstract copper :
If I shoot with the client it does rotate (the bullet), but it'll always shoot from one point
notice what you are passing into the RPC function
and whether or not it makes any sense
How do I make it so the player can see the bodies of other players in the game but can't seen his own?
I'm currently trying to use unity netcode and I made a working multiplayer where I can play together with Host and Client on my own PC. But when I try to start a Host on my pc and then join with Client on a different PC in the same network it doesn't work and the Client can't find the Host somehow. Does someone know what is the issue here or where I can find something about this topic. Because I can't find anything useful regarding this in a forum. thanks
Hi ๐ , I'm returning to Unity after a while and couldn't figure out if UnityWebRequst (https://docs.unity3d.com/Manual/UnityWebRequest.html) is part of the Netcode package or is deprecated . Should I use C#'s HTTPClient for example? I need to make simple GET/POST/DELETE requests.
does the free version of photon fusion automatically "lock" servers if more than 100 players are in them?
The free version of Photon Fusion only supports 20 CCU not 100
And yes it hard locks
Any one has an idea or best practice? Thanks.
swell. this means i dont need to input credit card information right?
Yes
great. is it 20 ccu per account or 20 ccu per project?
also when it says for non commercial use, if i dont add microtransactions to the game and make it free, is it allowed?
if you want to make multiplayer game try to first learn something about how networks work
you need to do port forwading on your network
or you can use unity relay
it doesn't say deprecated atleast, there is no webrequest method in ngo, so I can't say it will last forever but from what I can read there are no plans to retire it soon
Thanks. I might try using Polly too. I hope it works with Unity and mobile+webGL builds.
Most people buy a higher package when they release their game since they will have more than 20 users. And for any commercial purpose you have to as the ToS say. If you just do a hobby project / jam game and make it free don't worry about it.
Anyone else has experienced this sync problem with players? The players are hovering on different highest on each client
This can happen when the object has thresholds for sending another update for a given position axis without any extra logic for handling these kinds of cases.
Got it thanks. I just unticked Interpolate on the Client Network Transform
Is there someone who can help me with specified problem, I want to switch from Dedicated Server to Custom Server but I need Rigidbody, GameObject from API because I'm synchronizing Physical Object over network on server and sending position to clients. Is there solution for this? Hope you understand. I'm using LiteNetLib as Networking.
i just wanna make a small itch game that i intend to make 0 dollars from
bump
offering 100 โฌ for help
DM me
Are there any audit tools out there to check for unity vulnerabilities? Cause i seen some videos where the user could mod the info at front end and gives them advantage during gameplay
This depends on the networking solution you use. No tool can audit this, needs to be a human doing the test.
Hey guys, I am trying to add the Flatbuffers library to my Unity project and I want to build for Android and iOS
In all the tutorials I've seen the library is in a .dll so I think that would only work with Windows right?
I am basically trying to serialize data in the Unity client and send it using sockets to a C++ server, and viceversa. Is Flatbuffers a good library for that? Or are there better options out there?
Yo! How do I spawn objects? I tried to do something like this:[ServerRpc] public void SpawnObjectServerRpc() { GameObject weapon = Instantiate(weaponData.ItemData.weapon); weapon.transform.SetParent(weaponHolder); weapon.transform.localPosition = Vector3.zero; weapon.transform.localRotation = Quaternion.Euler(Vector3.zero); weapon.transform.localScale = Vector3.one; weapon.GetComponent<NetworkObject>().Spawn(); }
but it doesn't even call the method. I want so that whenever a client presses a key it'll spawn an object, but when I do that in the if statement where it checks if the client presses or no it gives me an error in play mode when I press the key that only the servers can spawn objects. Any help with this?
do I even need to do this in a ServerRpc?
Can explain you in DM add me
Why do I have to add you? (If your talking to me)
Can't you help me in here? I thought it'll be quick
?? Im not talking to u bud ๐
Problemo fixed
Hey All I am working to make a WebGL build. I need to have a scene be hosted on a server that will have a landscape and few NPC zombies using a script able object to keep track of everything happening in the scene. The WebGL will be using the client scene and will have a character with a name and different customisations and than will load into the zombie infested scene to go kill some and spawn back to the previous scene being the space the character is in.
What kind of service should I use for a prototype build and only like a max of 10 people playing it.
then in situation when ping is high bullet will show a while after you shot
public void OnTransformParentChanged()
{
if (transform.parent == null)
OnItemDropped();
else
OnItemGrabbed(equipSlot.Value);
}
[ServerRpc(RequireOwnership = false)]
public void SetEquipSlotServerRpc(ulong id, byte slot)
{
ItemTransform itemTransform = NetworkManager.SpawnManager.SpawnedObjects[id].transform.GetComponent<ItemTransform>();
itemTransform.equipSlot.Value = slot;
print("Setting value to " + slot);
}```
``` private void RaycastToItem()
{
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out RaycastHit hit, 5, layerMask))
{
if (hit.transform.CompareTag("Item"))
{
for (byte i = 0; i < _handItems.Length; i++)
{
if (_handItems[i] != null) continue;
if (hit.transform.TryGetComponent<NetworkObject>(out NetworkObject networkObject))
{
NetworkObjectReference reference = new NetworkObjectReference(networkObject);
networkObject.GetComponent<ItemTransform>().SetEquipSlotServerRpc(networkObject.NetworkObjectId, i);
PickupItemServerRpc(i, reference);
return;
}
else Debug.LogError("Failed To Get Component [NetworkObject] from Item");
}
Debug.LogError("Your Hands are Full!");
}
}
}```
i have the top script that is called from the players inventory script however the host can call SetEquipSlotServerRpc (on the second script) and it works perfectly but when a client does it i get no errors the network variable equipSlot just doesnt change and i dont know why
Is there a way to get The ping of each player and display it using a TMP using Mirror and FIzzySteamworks?
Hi! Any way to use NetworkVariables and assign a GameObject without getting the GameObject not supported error? I need to do that so that I could spawn objects through another script
FYI, there is websocket support in Unity Transport 2.0
https://docs-multiplayer.unity3d.com/transport/current/about/#requirements-for-unity-transport-2x
The Unity Transport package (com.unity.transport) is a low-level networking library for multiplayer game development.
I see thanks for pointing it out, I'm not using the unity transport (because I use facepunch instead) so I was unaware
Don't need it
wasn't reading the original message, busy with stduying for exams and only replied to the ping
what you could do is having a gameobject manager which takes a prefab, gives it an id, which you can than use in a network variable, thats how I handle my item spawning
I already did it
don't worry
I said I don't need it
I was kinda in a hurry so I phrased it like that. Sorry
Please guys, help me i need Head Motors based on IK, whos can help? Please.
With limit
hey all, can anybody throw me a few info bits if Unity's new NetCode is worth migrating to? Ive been out a couple of years... So many people use alternative network solutions nowadays (like Mirror)....
don't worry, I just wanted to share my approach in case you like that better
I did the same as you explained
That is good
Anyone know why my TrySetParent doesn't parent the object?
If needed I can give more code
It spawns the object but it doesn't parent it. No errors either
the "weaponHolder" is the clients characher's hand. The hand doesn't have a networkObject, only the player prefab has it
And that is the problem, you can't parent a network object under a non network object
I'll get an error if I'll put a networkObject on an object that is below another object that has a NetworkObject. I've seen someone instantiating and spawning an object inside the networkobject Gameobject with a networkObject and then spawning and parenting the item in that object (Good luck)
but I'm not sure if that works
Using a networkobject for you purpose is probably too much anyway, just send an rpc to all clients and let the weapon spawn locally. The position gets controlled from the animation anyway and if you need network capabilities you can just have them on the root player gameobject
And yea networkobject nestimg is only allowed in certain cases
are you saying I shouldn't even spawn it, just instantiate the weapon and add client network transform or something?
by send rpc you mean send the thing that got instantiated and make other clients instantiate the weapon and let the client network transform do the job?
Is that what you we're trying to explain?
The network transform can only be added to a network object. But if xou attach a weapon to your hand it is mostly moved by animations not by code, so using a network animator will solve your problems
But yea instantiate it not spawn it
I'll see
I have found another solution. Tbh there's quite a few solutions to it. I'll show what I did after I do it for anyone struggling with the same thing cause it seems to be a common thing
How would i sync one global variable with all clients? Iโm having trouble with that
Like, if there was one variable for, letโs just say, whoโs turn it is
If i have two players, and player one takes their turn, player two doesnโt get the message
How can I create own interpolation script to networkTransform?
Use Network Variable
Anyone with some networking knowladge ?
anyone can help me with some basic Networking setup ? i got a basic setup for multiplayer game, i got a moving platform, but can seem to move the players without lag, and when using the Client authoretive movement it has lag, anyone up for a bit of help ?
It didnโt work ._.
im trying to do a moving platform that players can turn on when it turns on it moves (like a big car) host players behaves well but remote client dosnt move with the moving platform
can i get an example of using network variables as a global variable?
For anyone that has a problem with spawning a GameObject and parent it onto an object of a character some where deep e.g. Hand. Since you can't parent an object in a GameObject that doesn't have a NetworkObject component instead of putting the weapon or spell or something else in the root of the player prefab do this:
- Make a new GameObject in the hierarchy create a new script and assign the script to the GameObject.
- Call an Awake and inside the Awake do
DontDestroyOnLoad(gameObject);. - Call a public serverRpc with RequireOwnership = false and serverRpcParams = default and call this script in another script where you want to equip a weapon, spell or whatever.
- Inside the ServerRpc do this
var clientId = serverRpcParams.Receive.SenderClientId; var client = NetworkManager.ConnectedClients[clientId]; - Make a ClientRpc with parameters
ulong playerObjectIdsomewhere in the same script and call it in the ServerRpc like thisClientRpc(client.PlayerObject.NetworkObjectId); - Inside the ClientRpc get the parent Transform and Instantiate the weapon/spell then parent it something like this
transform.parent = theParent;and then set the position, rotation, scale if you need to (Make sure to do that after parenting the object)
This way every single client in the server will instantiate the weapon on you.
No problemo
If you are making a game where people can join whenever they want don't use this since the players that joins after the object instantiates it's not going to instantiate for the new player. You can maybe try doing something but the best way to do this would probably be simply placing instantiating the object in the player prefab root.
I have a feeling that there's a way around it though. Like instantiating the weapon for the new player that joins. Maybe have a list that will contain the instantiated weapons and from that list the new player that joins will instantiate all the weapons from that list. I'll try to figure something out.
Anyone know if Vivox works with non-Unity multiplayer netcode such as FishNet or Photon Fusion?
Use unity docs
Hello I'm currently working on a player selection system to allow players to view each other's names and stat values(HP/MP). I'm trying to use raycasting to detect player tag, but this only works properly for the client that is running the server.(which doesn't quite make sense to me..) For other clients, the detection field is way off the player model but is somewhat constant, it's as if there's an invisible box above the player model that can't be adjusted. I'm using Fishnet for networking.
Here's part of the relevant code.
{
if (Input.GetKeyDown(KeyCode.Tab))
{
DeselectPlayer();
}
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
if (hit.transform.CompareTag("Player"))
{
NetworkBehaviour clickedPlayer = hit.transform.GetComponent<NetworkBehaviour>();
isHover = true;
if (clickedPlayer != null && clickedPlayer != this && Input.GetKey(KeyCode.Mouse0))
{
SelectPlayer(clickedPlayer);
}
}
else
isHover = false;
}
if (selectedPlayer != null)
{
UpdatePlayerInfo();
}
}
public void SelectPlayer(NetworkBehaviour player)
{
if (selectedPlayer == player)
return;
selectedPlayer = player;
UpdatePlayerInfo();
}```
Hello guys!!
I want to ask for a little help.
I'm currently making a small project about library management system.
The deadline for the project is really close and I'm stuck at networking.
I'm making a two projects for the system. One for library managing(Windows) and one for QR code scanner(Android).
The reason why I'm making a QR code scanner is I want to keep tracks of who enter or exit the library.
I got the idea of QR codes. I can scan a visitor's QR code and send it to unity and then to the database.
I used LAN connection with TCP. I tested it and it works really well.
The problem is I can't connect my android(Client) to my pc (Server).
I also can't connect from my friend's pc to my pc. It only works in the same device.
I searched for solutions for my problems, none of them works for me.
There is a interesting article which tell me that I need an access to my router and use port forwarding.
Is it true?I'm only using LAN. I saw some old games use this method. I don't think they need port forwarding or something like that.
One phone turn on hotspot and other player can join the game easily.
I will provide some of my codes. Please, help me.
I used this two scripts for connecting the projects. I got these from Unity forum.
I just have a few days before the deadline. Please, help me.
Particle system in netcode for gameobjects
Hello, im developing a realistic fps with multiplayer using netcode for gameobjects.
Im stuck at trying to get the muzzle flash effect to show for the other player, my particle system is attached to the gun and played with this function:
public void shoot_muzzleflash()
{
muzzleFlash.Play();
}
and im activating this function in an animation with an event.
I tried this:
[ServerRpc]
public void CmdStartParticles()
{
RpcStart_shoot_muzzleflash();
shoot_muzzleflash();
}
[ClientRpc]
public void RpcStart_shoot_muzzleflash()
{
shoot_muzzleflash();
}
public void shoot_muzzleflash()
{
muzzleFlash.Play();
} |
but then i cant choose the CmdStartParticles() as an event in the animation
im experienced with unity but not with netcode, so sorry if this is a noob question
Iโm not that good, but what if you just hooked up another function to the event, that just called cmd start particles
im asking how to do it, this doesnt work ive tried that
Your PC would have to port forward the port so that the router doesn't block connections, yes. If you could just randomly connect to people over the internet with no safety guards, all hell would break loose, so you have to explicitly tell your device that you are allowing connections on a specific port.
How are you supposed to parent and unparent Network Objects???
A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.
I was looking at this but I was still confused with what code would be used to โreplaceโ the setParent and I was also a little confused because I read something about transferring ownership of the network object and I didnโt fully grasp what it meant I will look at the documentation a bit more though
calling TrySetParent() on the network object should work. you can check out the Client Driven sample
https://docs-multiplayer.unity3d.com/netcode/current/learn/bitesize/bitesize-clientdriven/#reparenting
Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting
Gotcha will try that thanks!
Is SteamMatchmaking.RequestLobbyList blocked if you "spam" it by refreshing the list too often? It seems to be the case.
I just spammed it on purpose and it did not block me, so an error must be the cause.
Hello,
I am using PUN2 and Unity version 2021.3.16f1
I have a function called AddCoin(). This is called when the coin collides with the player. The purpose of AddCoin() is to add the amount of coin collected to the current amount of coin the user has.
It works great if the user collects one coin at a time. However, if the user happens to collect 2 coin at almost the same time, then only one coin gets added.
I included a debug log right before SetCustomProperties to see if the coin amount is correct, and the amount appears to be correct.
I read somewhere that SetCustomProperties takes time. Is there I can something I can do to make SetCustomProperties work if the player collides with 2 coins at the same time OR is there another approach I could try?
See Code.Png for AddCoin() implementation
See example.gif for the issue I'm describing. You can see the player collide with two types of coin, $5 and $25. Both coin got hit but the scoreboard only add $5.
I should mention I have a OnPlayerPropertiesUpdate() that sets the coin text in the scoreboard. See OnPlayerPropertiesUpdate.PNG. The GetCoin() function returns the coin that the player has. See GetCoin.PNG.
Did a bit more debugging, it seems like when 2+ coins are collided with the player. Both would read the current amount of coins. For example, say I'm currently at $180, and then I collided with a $25 and a $5. My logic seems to be reading $180 +$25= $205 and then $180+$5=185.
[EDIT]
I placed some breakpoints at where SetCustomProperties is called and where OnPlayerUpdateProperty is called.
What I thought the logic was when colliding with the coin is. Say current amount is $180
- Collide with 1st Coin
- SetCustomProperties - add the 1st coin say it's $25
- OnPlayerPropertiesUpdate() - updates scoreboard - add 1st coin value to current amount. $180+ $25 =$205
- Collide with 2nd Coin
- SetCustomProperties - add the 2nd coin say it's $5
- OnPlayerPropertiesUpdate() - updates scoreboard - add 2nd coin value to current amount. $205 + $5 = $210
- Result is $210
What is actually happening
- Collide with 1st Coin
- SetCustomProperties - add the 1st coin say it's $25
- Collide with 2nd Coin
- SetCustomProperties - add the 2nd coin say it's $5
- OnPlayerPropertiesUpdate() - updates scoreboard - add 1st coin value to current amount $180 + $25 = $205
- OnPlayerPropertiesUpdate() - updates scoreboard - add 2nd coin value to current amount $180 + $5 = $185
- Result is $185
So it seems like there is a delay between SetCustomProperty and OnPlayerPropertiesUpdate()
a powerful website for storing and sharing text and code snippets. completely free and open source.
Figured it out. It's really complicated so if you don't want to suffer, don't do this
I want to parent a NetWorkObject to a child of my Player Network Object but that doesnt work is their a workaround to parent NetWorkObjects to childs of your playter Network. sorry if this is worded weirdly lol
Hello, I'm thinking how to deal with player interpolation. When one player shot while moving, another player will see the gap between player one old position (because it is interpolated) and bullet. Do you have and Idea how to fix that?
You can't do that, what are you trying to do specifically? Like a weapon that is controlled via animation on your hand-bones?
my client is just floating there when it connects. any idea why?
the client can only look up and down and cannot move or do anything else
Alrighty I'm hitting a wall. Should SetCustomProperties be used for collecting coins in this case? Is it really because of the delay or is there a logic flow I'm missing here?
you probably have to provide your code, if you want help with figuring out what is wrong
Hi. I need shutdown server if host disconnects and disconnect client if client disconnects. In server case i understand what i need to do, but what about client, how to disconnect him?
private async void Start()
{
await UniTask.WaitUntil(() => UnitContainer.unit != null);
Singleton.OnClientDisconnectCallback += (client) =>
{
if (UnitContainer.unit.IsServer)
{
Singleton.Shutdown();
}
else if (UnitContainer.unit.IsClient)
{
// ???
}
};
}
is it possible to use my own dedicdated server for matchmaking
using Netcode & unity game services
Hello, im triying to collab with my friend with plastic SMC, and when he opens unity hub and search for "Open remote project" the project doesnt show up, even after i added him to the team, i tried a lot of things but nothing seems to work, could anyone help me please?
is Mirror Networking useful now?
or it is deprecated?
Unity Matchmaking currently only works with Unity Server Hosting(Mulitplay)
Depends on what you want, but it doesn't look deprecated.
Got significant commits within the last 12 hours and the primary author is still selling assets that rely on it
Hi, im building a casual game that uses physics and networking.
I added the network object, network rigidbody and clientnetworktransform scripts to my prefab and successfully instanciate and spawn it.
The problem i find is that the scripts that add forces to my rigidbody do not affect it because the rigidbody is automatically set to kinetic.
How am i supposed to solve this?
Removing the network rigidbody seems to "solve" it, but i dont know if this is a good aproach tbh
Only the owner can apply forces to their client Network Transform
I have a similar problem when I'm using a Client Network Transform and use the interpolate option the position of my character is not in the correct spot but when i turn interpolate off it works perfectly is their a way to fix this or should I brute force it and update the position through code?
Edit: I have figured it out, ty anyways
Hello, I have a question regarding tcp sockets
I have a server written in python which should accept connections from multiple clients in Unity
on the other side, clients should also receive data from the server
in python I avoid the blocking of socket.recv by using selectors
is there any elegant way of doing it in Unity or should I use select aswell?
I should state that speed is not important here, as it is a turn based game
There is a bug in Network Transform. Try enabling "Half Float Precision" on it
This worked but It looks weird so I'd rather use it as a last resort. Do you know the best way to update the positions manually with a Rpc to test out? (also thanks)
Network Transform uses Network Variables under the hood
O ok Iโm probably not gonna use the network transform and make a custom script for updating the player. I might blow up someoneโs computer updating the position every frame lol. If u know how to uhh not do that and make a custom script to update the position#s it would be appreciated if not Its fine I appreciated the help
how would i send a list<int> though an rpc?
Could you instead make the list a network variable?
Ooo my b
Network variables only update when they change
You can use NatvieList now
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/arrays/#nativelistt
Arrays of C# primitive types, like int], and [Unity primitive types, such as Vector3, are serialized by built-in serialization code. Otherwise, any array of types that aren't handled by the built-in serialization code, such as string], needs to be handled through a container class or structure that implements the [INetworkSerializable interface.
I might be misunderstanding u but could I make the player transform a network variable idk lol
You can make the position and rotation into a network variable. they update its value when the player moves
so for this, i just add "INetworkSerializable" to the top part? (inherit)?
(sorry if i'm cutting in)
Oooo thatโs perfect ๐thanks Iโm gonna go try that
yea. your class or struct has to implement INetworkSerializable
um
i put "public class PlayerManager : NetworkBehaviour, INetworkSerializable"
i'm getting "'PlayerManager' does not implement interface member 'INetworkSerializable.NetworkSerialize<T>(BufferSerializer<T>)'"
not your manager. whatever it is you want to serialize
uh
so the array? since i wanna pass a list<int> through an rpc
the rpc is in the class "PlayerManager"
sorry, i'm new to networking
i'm a little confused on how to serialize things, i've never done it before
if you just want to send ints then the easier way is to use NetworkList<int> see here
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/#synchronizing-complex-types-example
Introduction
network lists are just like networkvariables, right? it's just that they can hold lists
You might even be able to send NativeList<int> directly inside a RPC. I havent actually tried that
right they get sent automatically when they get updated
hm, interesting
sorry for all the questions
i'm very new
one last question: (hopefully), so since it's a networklist, that means that if a new client joins, they'll have the updated list, right?
yes. when they connect they'll get the full list. So its something to watch out for. If it gets too huge late clients could get bogged down
ah ok
thank youuuu
if i were to ask questions about networking here, would you often be online at this time
sure you can also hit us up on the Unity Netcode Discord
link is in the pin message
Ok thanks! so is this a good approach? Or should I have clients send rpcs to the server to add the forces to their ships?
What if two ships with two different owners collide?
You should keep all the physics stuff to the server/host. It may be laggy but it will keep things better in sync
Oh ok, so whenever a player hits the forwarded button I should send an rpc on each update?
Sounds intense
Ohh I could use network variables for that, right?
um, is something wrong? there's only four channels, and i can't do anything in any of them
Physics based game are tough to network
You'll need to choose a role first
whoops, i thought i already reacted, but i didn't ๐คฆโโ๏ธ
But yea. Net Vars can work for that
Yeah, figured it might be hehe, love a challenge!
Thanks for the assist
anyway, thanks evilotaku, i'm probably gonna ask you for help a lot in the future!
is it okay if i ping you around this time if i need help?
woo hooo
Hello everyone, could anyone help get my started on how I could have a player press a button and have it teleport ONLY the player who pressed it to a certain spot on the scene? Im using netcode for go btw.
hello guys, so i am making fps game and i wanna make the skin and animations invisable to me and appears to the other guys in the game so what can i type in search to have a tutorial im using photon pun 2
Are you using the player prefab feature?
with netcode for gameobject, theres a player prefab slot you can assign the network gameoibject to spawn on (server launch/ join), but how you do you for more than 1 model ?
Yes, but I may have found a fix myself.
You can't have more than one player prefab, but you can spawn network prefabs from the server by listening to NetworkManager.OnClientConnectedCallback
kk thanks will check that
@neat veldt what im looking to do is, have a different spawn of player prefab depending on what the player chooses, the code to allow the switch of character is ok, but i cant seems to switch player prefab with code before i join a server
You need to spawn the players yourself
I believe you can set an object to be the client's player after its spawned
With every new connection, Netcode for GameObjects (Netcode) performs a handshake in addition to handshakes done by the transport. This ensures the NetworkConfig on the client matches the server's NetworkConfig. You can enable ConnectionApproval in the NetworkManager or via code by setting NetworkManager.NetworkConfig.ConnectionApproval to true.
oh thnks ill look into that
Hello, I'm having trouble with rotation over the network (kindof) using netcode for gameobjects
I have an object thats being rotated by a client, and the rotation is being syncrhonized as expected on every other client + local client ...
but when I check the rotation through script transform.rotation.x/transform.localrotation.x or the direction transform.forward on other clients it says 0 even though on the inspector for the client (not local client) I can see the rotation from the owner client :\
Hi, I am trying to use this native library https://github.com/ValveSoftware/GameNetworkingSockets
on my Unity project. I compiled the .dll but since it's native it doesn't get recognised when I build on Android, could someone tell me how to build the library for Unity Android?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerMovement : NetworkBehaviour
{
public float speed = 10.0f;
void Update()
{
if (!IsOwner) return;
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
transform.position = transform.position + movement * speed * Time.deltaTime;
}
}
I have a linux VPS with a game server loaded up via Dedicated Server/Linux build and then a game clients loaded up via Windows on my local PC
The players spawn, but they don't register the other clients movements
player 1 falls -- gets moved to the left
Second window opened, player 2 falls on top of player 1 (whose movement to the left never updated to the server), moves to the right. First window shows player 2 idle on top of player 1's previous position
i suggest u start by following some tutorial like CodeMonkeys netcode tutorial. it covers the very basics including movement/syncing locations
@shrewd junco I'm already stuck...
I can't drag the player to the prefab slot and the prefab list
Only the prefab slot
ah that part was changed, you need to drag the default network prefab list (from your assets folder) into that
and you put your player inside the default network prefab list itself as well
pretty sure thats like the only difference
you need to create a network prefab list
Create a list in my assets folder? Or a folder in my assets folder
I've never made a list in my assets folder
it should just be created by default, but if not then yea right click in your assets folder
itll be there under netcode
Thanks ๐
im not sure why all the tutorails shows the default player prefab method how usefull is this , to have the players all look the same look
because the tutorial is just about getting netcode setup, they arent gonna go into connection approval (for changing the prefab) or custom spawning when people don't know how to move yet
true, but still no tutorials on that
im not good with documentation that is sorta vague
what i said is pretty much just how u would do it
https://docs-multiplayer.unity3d.com/netcode/current/basics/connection-approval/
you can change the prefab in here
// The Prefab hash value of the NetworkPrefab, if null the default NetworkManager player Prefab is used
response.PlayerPrefabHash = null;
that part
i followed a tutorial that make sure connection aproval wroks,, i can move and animation network authoritive i just need to change player prefab so they dont look the same for every player, sec ill check your link
if you scroll down, theres a part "changing the player prefab"
i did try to follow that but i ant make it to work
not sure if the script needs to be on network object
someone sent this earlier
yea just place the script on an object in your scene, give it a network object, and then follow the 2 steps listed. With the example on the docs, you may have to give some payload data. You can also get it working by just choosing a random index to give the player
instead of doing
var playerPrefabIndex = System.BitConverter.ToInt32(request.Payload);
just assign that to some random one for now to see if it works
Sorry @shrewd junco
WASD doesn't work when I launch client
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerMovement : NetworkBehaviour
{
public float speed = 10.0f;
void Update()
{
if (!IsOwner) return;
Debug.Log("Owner");
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
transform.position = transform.position + movement * speed * Time.deltaTime;
}
}
the axis probably does work, id assume its an issue with the actual movement. if you have it as server authoritative movement, then the client wont be able to move anything
Where is this setting King?
I don't see it in the Network Manager, Network Transport, or Network Object
server authoritative movement would mean you are using a network transform
Ahh...
if theres no network transform or client network transform, your position/rotation/scale wont be synced across the network
unless you wrote your own custom one
if you want client authoritative movement then yea
Anyone have any idea by any chance?
you are checking the x component of the quaternion, the inspector is showing you euler angles
It's working ๐
Thank you so much
Do you think the issue was the pre fab list then?
I tried client transform before to no avail
i cant really say without knowing the exact setup at the time, as long as it works though and you understand the setup then youll be fine for the future
Oh so transform.rotation.x and transform.forward are all based on the quaternion?
Are those not not synced with Network Transform? (I tried setting the quaternion synchronization on the component but didnt fix the issue)
rotations themselves use quaternions, but the rotation.x is the x component of a quaternion. In the inspector you are seeing the rotation.eulerAngles.x
the forward is just a vector
rotation is synced with Network Transform. But there is a bug in it currently that sometimes effects the y axis. Try setting the Network Transform to "Enable Half Float Precision"
Oh will try that thanks, it is the y-axis the only one thats being affected for me
Hello everyone. I am having an issue where I am using Netcode for GO and my player prefab that has a Client Network Transform. Attached to the base player prefab is a camera holder then a weapon object. The problem is that only the base player is visible to other players in the game. The client itself can see the weapon, but other players cannot see the weapon. Do I need to have a Client Network Transform on the weapon too? Am I missing something here?
If the weapon is not already part of the base prefab then it will need to be spawned and reparented to the player
I figured, thanks.
Is it possible to enable and disable a Network Transform through code at runtime?
You should be able to disable the component
I thought so but when I tried to access the component it wouldnโt pop up and when I looked online I couldnโt find anything. Maybe I wasnโt accessing it right because I was trying gameobject.GetComponent<> and looked for the Network Transform but couldnโt find it but maybe Iโm just being stupid
I'm having an issue with Rpc :x
I run the server and then I run the client
in the client, I have a UI button to simulate the "login" button; when that button is clicked, I call a method that has the NetworkManager.Singleton.StartClient();
after invoking the NetworkManager StartClient, I have this line that returns null
FindObjectsByType<Player>(FindObjectsSortMode.None)
will FindObjectsByType only work once the method that starts the client ends?
if I press the button again, the FindObjectsByType<Player> does return the player
You should wait until OnNetworkSpawn() to call any RPCs. If you are calling find objects immediately after StartClient, then the player hasn't spawned yet
ty ty will give it a try
Hey Im having a problem with my NetworkRigidbody.
Im using Unity Version 2022.3.5f1 and Netcode for Gameobjects 1.4.4 . I have one Player prefab with my Movement Script and a Network Rigidbody. On the host side everything works and the Rigidbodys are isKinematic = false but on the Client side its isKinematic = true. I dont know why. I tried to set the IsKinematic in the Await or the OnNetworkSpawn but both didnt work.
how can i make change scene on finish matchmaking
Hello everyone. I am having an issue where I am using Netcode for GO and my issue is that each player in a game has a gun and whenever they fire that gun it spawns a prefab of a bullet/projectile but I want to be able to syncronize those bullets over the network so that whenever a bullet hits a player that player knows and I also have a script where whenever a player gets hit with said bullet it kills them so I need these bullets to be networked. To go fourth in doing this would it be as simple as adding a network object and client network transform to each prefab, I am also using Relay so would relay interfere with that since im not sure if it automatically adds that bullet to the relay session. Anybody got any ideas. Im not even sure that the best way to detect if a player is hit by a bullet is just to check if it was collided with an object with a bullet tag. Thanks!
I had tried a raycast previously but I ran into the same issue of how can I let others players know that they have been hit by the raycast.
thats what a network rigidbody does, it sets rigidbodies to kinematic when you are not the owner of it. If you're not the owner, you don't need to do calculations for it because you wont be updating its transform or other variables anyways
the server would have to send out some rpc to clients to inform them
I figured. I have never really understood ServerRPC's tbh.
its something u just need to play around with, it gets especially confusing if you dont know where its running.
a server rpc (remote procedure call) means you are remotely calling the server to a procedure. To simplify: you are telling the server to run some code. Only a client can call this (a host is a client and server, so hosts can call it).
in your case you would likely want a client rpc, so the server is telling the clients that someone got hit.
Thank you.
is there a way of loading addressable scenes with NGO
addition to that only the server can call that
@ionic mantle
quick question should i switch from mirror to fish-net ?
I am using a player controller that uses to separate camera holder and player how will i use it as a prefab for photon pun 2
Learn more about the dynamic Prefab system, which allows you to add new spawnable Prefabs at runtime.
that's for prefabs, last i checked NetworkSceneManager basically has no addressables support yet so your options are to turn it off and do scene management manually or to go modify the NGO code yourself to hack it
Ah, you're right. Addressable scenes are not supported yet. I remember seeing it on the roadmap
does anyone know what mirror's networkserver.active equivalent for netcode?
I think NetworkManager.IsListening is what you're looking for
Hello everyone. So I am having an issue with a ServerRPC. I finally decided to learn how to use it yet im still after all this time still confused. This https://pastebin.com/xWh5yjLS is my code for Instantiating a bullet. The 4th line just created a game object (a projectile) and instantiates it and then spawns it at the firePoint. Then on the 6th line it gets the RigidBody of that projectile and makes it go fast like a bullet. But Unity is yelling at me telling me that it does not know how to serialize or deserialize UnityEngine.Transform.RPC. I new to networking and have no idea what that means so I looked it up and it told me to add INetworkSerializable after the class and I did then untiy yelled at me again saying it does not know how to implement a surface member of INetworkSerializable and I am unable to figure out why after looking it up, again I dont know at all what a INetworkSerializable is or why I need to use it.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
try calling with just the data you need like Vector3 position etc to the RPC instead of the whole Transform, it complains about INetworkSerializable because RPCs can not take references in arguments only data types like primitives and structs
Makes sense. Thanks
using the NetworkManager.SceneManager.LoadScene im trying to load into another scene the only problem is the server host loads in way before the clients even when load scene time out is set to 0 is their a way to make it so the scene only loads when all the clients are ready? the line im using to load the scene is below
NetworkManager.Singleton.SceneManager.LoadScene("MiniGame", LoadSceneMode.Single);
I believe the scene event LoadEventCompleted will tell you when all clients have finished loading the new scene
https://docs-multiplayer.unity3d.com/netcode/current/basics/scenemanagement/scene-events/#scene-event-notifications
If you haven't already read the Using NetworkSceneManager section, it's highly recommended to do so before proceeding.
Im currently trying to use that but I've never used something like that before so im struggling to figure out how to set it up so it would function something like this WaitWhile(SceneEventType.LoadEventCompleted); (i know its not a method but u get what i mean)
yield return new WaitWhile(() => SceneEventType.LoadEventCompleted.Equals(true)); I just did this I have no clue if this will work heres trying
No, you subscribe to NetworkSceneManager.OnSceneEvent like in the code smaple there. Then you can test if the scene event is LoadEventCompleted. After that you can continue running the scene
oohh ok also thanks for the responses over the past few days you have been helping me out a crazy amount I appreciate it ur the goat
sry to bother again but im struggling from dumbness ive been trying a bunch of different ways but I dont know why I cant subscribe to the event this is what i have been doing...
NetworkManager.Singleton.SceneManager.OnSceneEvent += SceneManager_OnSceneEvent;
TLDR how do I create the SceneManager_OnSceneEvent; in my script
I have created a multiplayer game using two separate Unity Editors, and have successfully connected to a Pun2 server. How can I connect both editors to the same room?
That's a function you create yourself. It just needs to have SceneEvent as an argument
Im using Lobby by unity can anyone help me fix this? providing code and console screenshot
public async Task CreateLobby(string lobbyName, bool isPrivate, string playerName)
{
Debug.Log("Creating Lobby");
Debug.Log(lobbyName);
Debug.Log(isPrivate.ToString());
Debug.Log(playerName);
try
{
Debug.Log("1");
CreateLobbyOptions options = new CreateLobbyOptions()
{
IsPrivate = isPrivate,
Player = CreateLobbyPlayer(playerName),
};
Debug.Log("2");
Lobby lobby = await LobbyService.Instance.CreateLobbyAsync(lobbyName, maxPlayersPerLobby, options);
Debug.Log("3");
hostLobby = lobby;
Debug.Log("4");
StartCoroutine(StartLobbyHeartBeat());
Debug.Log("Created Lobby");
}
catch(LobbyServiceException e)
{
Debug.Log(e.Message);
}
}
i think i found the issue
im logging in to slow
how do i fix this?
fixed it by making a while !ready loop that waits 1 second untill ready is true and i set ready to true after logging in
Hello everyone, Iโm having trouble with ServerRpc and ClientRpc methods not getting called
If anyone could help me out I would appreciate it!
The following code is attached to NetworkObject and the script is NetworkBehaviour:
// Is called from button click listener
private void ReadyToPlay()
{
isLocalPlayerReady = true;
OnLocalPlayerReadyChanged?.Invoke(this, EventArgs.Empty);
Debug.Log("CALLING RPC ");
SetPlayerReadyServerRpc();
Debug.Log("FINISH RPC ");
}
[ServerRpc(RequireOwnership = false)]
private void SetPlayerReadyServerRpc(ServerRpcParams serverRpcParams = default)
{
Debug.Log("IN SERVER RPC, ID: ");
Debug.Log(serverRpcParams.Receive.SenderClientId);
playerReadyDictionary[serverRpcParams.Receive.SenderClientId] = true;
bool allClientsReady = true;
foreach (ulong clientId in NetworkManager.Singleton.ConnectedClientsIds)
{
if (!playerReadyDictionary.ContainsKey(clientId) || !playerReadyDictionary[clientId])
{
//Player not ready
allClientsReady = false;
break;
}
}
Debug.Log("All players ready: " + allClientsReady);
}
// Even these test ones don't work
[ServerRpc(RequireOwnership = false)]
private void TestServerRpc(ServerRpcParams serverRpcParams = default)
{
Debug.Log("TEST SERVER RPC");
}
[ClientRpc]
private void TestClientRpc(ClientRpcParams clientRpcParams = default)
{
Debug.Log("TEST CLIENT RPC");
}
(I sometimes get this error too: [Netcode] Deferred messages were received for a trigger of type OnSpawn with key 0, but that trigger was not received within within 1 second(s).)
I am trying them as host and client with no success. Thanks again!
that [Netcode] Deferred messages thing should just be a warning not an error. I believe it happens when someone tries to update a value on an object that you despawn/respawned. Maybe theres more cases, but im not sure why you get it here.
Can you show your entire code? If your rpc's arent calling, the issue likely isnt in this code
the reasons its not calling is likely due to the network object changing ID's
Yea sure it's a little long tho:
use a !code website itll be easier
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
perfect will do that now
maybe try to separate out some things that you know arent relevant
is there anything that is calling despawn/spawn on this object
Nope nothing
a powerful website for storing and sharing text and code snippets. completely free and open source.
you should definitely separate out some of this logic, will make it a LOT easier to debug. seems like most of this is related to game mechanics
when you call the RPC, can you look at the network object ID and just see if it changes?
Yea I'm doing that now ๐
Sure one second
with the amount of logic in here, its hard to see if anythings really disabling/enabling or respawning the object but from what i saw it doesnt look like it
also when u are testing this, are u checking debugs on the host/server?
Oh wow, when it gets time to call for that it gives me where the network object is a "Spawn" button
yep
are u spawning this GameplayManager then dynamically, aka its not in the scene when u press play
It is attached to an empty object that is SetActive(false) by default and when they get to a specific part it goes SetActive(true)
But not spawning through server
i forgot how network objects work when that happens, let me try something
Thank you!
regardless the issue is still just that its not spawned/despawning somehow
which u can fix by calling the .Spawn() function
the only thing is something like this should be spawned already
Yea that's why I didn't think that would be an issue
Will try that now thanks!
ah yea i just tried, if its inactive when you start the scene its not spawned
which makes sense
So instead of SetActive(true) do I use the Spawn() function? or both?
I think you have to do both
Thanks so much fr I'll try that now and if something is still up I'll ping here!
the order shouldnt matter as long as this is after the network manager is listening
u can also ask in the ngo discord pinned in here. a lot more gets answered in there
Oh didn't even know there was one, will join
in netcode for game object can i not spawn the player objects as soon as the game starts and only later when i call a function if not can i not spawn player objects and then asign a player object to a player? i have code taht works by getting the player object so woud be helpful if someone cud help to find an answer
hey guys looking for experts in UX/UI for VR
@lunar urchin If you are looking to ask a question, ask in #๐ฒโui-ux , if you are looking for !collab:
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
all the network tutorials I see for a mmorpg is either with lobbies or steam ids...
what's the best way to host my server in a 3rd party platform, like amazon or w/e, and make the client connect to the server?
I did read about fishnet and the asset is free, right?
There's no limitation to relation with those. Any of the solutions allow you to run your own server. Check the pins for tutorials and links.
@drowsy thistle !collab for job posts etc.
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
you would have to remove the player prefab from the network manager. then handle your own spawning with SpawnAsPlayer()
Alr ty
So I'm having an issue with PUN 2
I enable the Offline Mode but it doesn't seem to use the callback OnConnectedToMaster like it says in the documentation.
I have a Debug Log in there that is never called, but it definitely sets the photon network to offline right away in Awake as long as I have the bool enabled.
Anyone know what I'm doing wrong?
private void Awake()
{
if (offlineMode)
{
PhotonNetwork.OfflineMode = true;
//InitConnect();
return;
}
//Player is already connected to the network, just return
if (PhotonNetwork.IsConnected) return;
//If it's a first boot, get mic permissions
if (askForMicPermission && !Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
Permission.RequestUserPermission(Permission.Microphone);
}
//Start the connection
InitConnect();
}
public void InitConnect()
{
ConnectToServer();
}
public void ConnectToServer()
{
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.GameVersion = GAME_VERSION;
PhotonNetwork.ConnectToRegion(DEFAULT_REGION);
Debug.Log("Attempting Connection to Server");
}
public override void OnConnectedToMaster()
{
Debug.Log("Connected To Network!");
//Connecting to the Lobby to load active lobbies
PhotonNetwork.JoinLobby();
}
Hi, what might be the reason why client is so laggy? i tried everything i know but its stilll laggy. theres no lag for host btw. Im using photon fusion
im using lobby by unity and if i try to join a lobby from a second instance of the editor it tells me im already in the lobby is that becose im on the same pc?
Yes, you need to switch authentication profiles when signing in anonymously
https://docs-multiplayer.unity3d.com/netcode/current/tutorials/testing/testing_locally/#ugs-authentication
Guide covering the available workflows for testing multiplayer games locally.
Ty
Also how can I run code when someone joins the lobby
You would use lobby events
https://docs.unity.com/ugs/en-us/manual/lobby/manual/lobby-events
But they don't exist tho
I tried a person had the same problem in this discord it also didn't existed for them
If you are using an older version of lobby then youll have to poll for updates with getLobbyAsync()
I think in using newset
Not home rn I will try when I get back
@swift pendant this guy might know how to fix your problem
hi, do you know how to use the latest version? I can't upgrade it from 1.0.3 to higher versions using unity package manager
Oh it might still still be in preview. You should be able to add it by name and specify the version. 1.1 I think
https://github.com/Unity-Technologies/com.unity.services.samples.game-lobby#ugs-events-beta-note
yeah thanks, but 1.1 didn't work, I used 1.1.0-pre.5
@woven cliff so add it with name, package manager add by name:
name: com.unity.services.lobby
version: 1.1.0-pre.5
Tysm was a pleasure cooperating with you I try it as soon as I get home
I figured out the issue, it would connect to master without calling the callback, so I just had to manually join a room after it connected
Hey i Wanna send From my phone App Data to the server which Runs my Game. The App is Build With js and i dont know How to approach this
Making it With sockets Would be an Option But Would Like to make it With a Unity Solution that Deals With data transfer
How do you send information to a specific client? when trying this code and plugging in the targetId of a different client nothing gets received on the other client.
UpdatePlayerPositionClientRpc(transform.position, new ClientRpcParams
{
Send = new ClientRpcSendParams
{
TargetClientIds = new ulong[] { TargetId.GetComponent<NetworkObject>().NetworkObjectId }
}
});
you want the OwnerClientID
id also just cache that client rpc params into a ClientRpcParams clientRpcParams
then call the function with UpdatePlayerPositionClientRpc(transform.position, clientRpcParams);
would be a lot cleaner on the eyes at least
plus you can save some memory allocations if your target id doesnt change often
Thanks that worked!
in unity lobby how do i run code when someone joins any lobby cus doing it when someone presses the join button is error prone cus there are multiple
cus from what i understand subscribing to events require the player to already by in some lobby
So is it not true that player objects are assigned their own ownership?
Thats what im currently working with. Using client network transform
You can view ownership details in the inspector on the clients, clients are given ownership of their player objects. If they weren't, you wouldnt be able to know which was yours. Your code is checking too early I believe, since it may be running before any network stuff has been setup. You should check OnNetworkSpawn
Also what you are doing in update looks very very wrong. You are adding code to an event every single frame by the looks of it, yet never removing any so this is gonna grow very quickly. The formatting of this seems very... different too
Sorry, itโs very dirty code, Iโm still in the prototyping phase but thank you for the insight
Ohhh and that makes sense
You should probably look at some single player stuff first, multiplayer in itself is a lot harder if you dont have a good coding background
Actually Iโve already completed multiple projects
Again, itโs prototype code, itโs not intended to be perfect, just enough to get things running
I use KR formatting, and I try to use Microsoftโs coding conventions.
As a matter of fact Iโve been working in Unity for two years now so savage
If I want to make multiplayer games Iโll need to make the step at some point
Didnt mean anything as an insult, sorry if it seemed so. I just generally assume people are beginners in this server
No worries, to be fair Id think the same with lambda events assigning in a loop
Iโm fairly embarrassed thatโs in there
Iโve been meaning to refactor this into 3 scripts anyways so maybe Iโll do that tomorrow.
I figured the ownership was the issue because at first it was setting it to kinematic.
I shouldโve looked at the method execution order before asking the question.
I want to make a skill based matchmaking system using photon.
Currently I have done so by
-> get all active rooms in lobby
-> filter all the rooms and only look at ones that are near my skill level
-> try finding a room who's MMR is close to mine
-> if can't find after 5 seconds, create a room
Is there a better way of achieving it?
in unity lobby how do i run code when someone joins any lobby cus doing it when someone presses the join button is error prone cus there are multiple
also in unity gaming services can i somehow log into a anonomys account with a specific id? so i cud use it accros multiple deveices?
Would also increase the Potential fitting skill Levels. So Over Time you will atleast Find a room
Yeah I ended up doing that only ๐
Filter rooms every 1-2 seconds and increase skill level range with each iterations
Try to filter x times, if found any room just join right away otherwise create my own
@somber geode I used photon
so im using photon pun and i wanna make it instantiate one gun in random place but it instantiate a gun for every player and idk why
this is the script:
public GameObject gun;
public float minX , maxX , minY , maxY , minZ , maxZ;
// Start is called before the first frame update
void Start()
{
Vector3 randomPosition = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), Random.Range(minZ, maxZ));
Debug.Log($"Spawning at: {randomPosition}", gameObject);
Instantiate(gun, randomPosition , Quaternion.identity);
}
Do you have anything that would prevent Start from running on all clients? Probably want to make sure to only run this sort of stuff on the masterclient.
private NetworkVariable<List<Card>> deckSync = new NetworkVariable<List<Card>>(); how i can create a networklist to manage a deck ?
i'm using relay and ngo
check my reply
how i can extend INetworkSerializable in my card class? is correct extend MonoBehaviour?
@frank stream pls u can help me, pls i need this game for university exam
did you look at the example ?
/// </summary>
public struct AreaWeaponBooster : INetworkSerializable, System.IEquatable<AreaWeaponBooster>
that's how you do it, look at the example
how do you have an exam on this but have no knowledge how to extend from a class implementation
yes i see the example but i have class not struct, i convert my class in struct, and this example i try before but not work for me
because struct are better suited for network transfer
you can just change it to struct, not much will change
Reference types are part of complex types though, make sure you read up on that too
yes i try but my english is not so good and example page is difficolt
then why do you have an exam on this ? have you coded a game before?
no never i code game but in my university last year we need 2 facoltative exam and game developer is a interresting
[System.Serializable]
public struct Card : INetworkSerializable {
public string cardName;
public Sprite image;
public int maxCard;
public Heat heat;
public Cash cash;
public Protection protection;
public Nirvana nirvana;
public Maledizioni maledizioni;
public Effects effects;
public bool inDeck;
public bool onBoard;
public int usedCards;
public GameObject UIimage;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsReader)
{
var reader = serializer.GetFastBufferReader();
reader.ReadValueSafe(out cardName);
reader.ReadValueSafe(out maxCard);
reader.ReadValueSafe(out heat);
reader.ReadValueSafe(out cash);
reader.ReadValueSafe(out protection);
reader.ReadValueSafe(out nirvana);
reader.ReadValueSafe(out maledizioni);
reader.ReadValueSafe(out effects);
reader.ReadValueSafe(out inDeck);
reader.ReadValueSafe(out onBoard);
reader.ReadValueSafe(out usedCards);
reader.ReadValueSafe(out UIimage);
}
else
{
var writer = serializer.GetFastBufferWriter();
writer.ReadValueSafe(out cardName);
writer.ReadValueSafe(out maxCard);
writer.ReadValueSafe(out heat);
writer.ReadValueSafe(out cash);
writer.ReadValueSafe(out protection);
writer.ReadValueSafe(out nirvana);
writer.ReadValueSafe(out maledizioni);
writer.ReadValueSafe(out effects);
writer.ReadValueSafe(out inDeck);
writer.ReadValueSafe(out onBoard);
writer.ReadValueSafe(out usedCards);
writer.ReadValueSafe(out UIimage);
}
}
my new struct
but i have this
write is wrong
well you picked the wrong part of game development
networking is extremely difficult to start with , let alone in a game setting where every bit matters
how can i delete a username password account cus i accidently deleted the player ID assosiated with it and i need to either assign a new one or just delete the username password and make it again how can i do that? using unity gamking services btw
eeeem i know but i work on this from 2 mouth and i cant change now
wowz why did you wait so long? didn't you realize networking was extremely difficult?
Idk mate you're in a difficult spot cause you're trying to race a F1 car without knowing how to drive
username and password from what?
unity gaming services
method of authentication
i posted there 10s of times i havent got a response once
your example is perfect but i need a card game so easy, not a rpg not a fps card game
u can help me ?
easier certainly but not Easy for networking.. how long do you have?
i need this for december or next year
ok did you build out the single player portion first at least?
i think i do singleplayer after i need change to much
i create strcut without error now but i use card class to link with gameobject now with struct i cant, is uselles link?
singleplayer comes first because it's easier and might help instill some good experience before transferring that same data over the wire
I really appreciate the advice but I think I should do the multiplayer version directly for timing
You would never do this
Here are the steps for a new feature in a multipler game
-think of a new feature
-prototype the new feature in singleplayer
-implement the feature in singleplayer while allowing the code to be easily modified for multiplayer use
-start syncing smaller parts of that feature
-test them
-slowly make the whole feature work over netcode while testing it
So I have a network variable that looks like this
public NetworkVariable<int> health = new NetworkVariable<int>(
value: 120,
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Owner);
and what happens is that whenever a person shoots someone it subtracts the health by the amount of damage a gun does. Then when it detects the players health is under 0 it kills them then resets their health back to normal. A client shooting a host works just fine and nothing goes wrong. But a host shooting a client does not work and the host gets the error Client is not allowed to write to this network variable even though the write permission is set to owner and the read is everyone. I also tried using Server instead of owner and it worked kinda, the host was able to shoot the client and the client was able to shoot the host but their health never got reset back to 0 and on the client this time was saying the client was not allowed to write to the network variable.
how can i make it im beginner
in unity lobby how do i run code when someone joins a lobby?
I mena when a person joins a lobby for the first time after booting the game
pretty easy write the health in a serverr rpc
void playerGetsShot() {
int damage = 7;
//rest of your code
applyDamageServerRpc(damage);
}
//this runs completly on the server
[ServerRpc(RequireOwnership = false)] // so you don't need to be owner of the object, you can also change that
void applyDamageServerRpc(int damage) {
health.Value -= damage;
}
hi everyone, this is my code https://pastebin.com/6evr2u5J I put in Unity transport my local address and tried to connect to the host from another computer from the same network, but couldn't. Any idea why ?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
have you seen the code monkey tutorial? He covers this slightly at the end, where he connects on his laptop
Yeah I checked it, but got same issue when trying to connect to host
you talk about this https://www.youtube.com/watch?v=swIM2z6Foxk ?
โค Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
๐ Get my Complete Courses! โ
https://unitycodemonkey.com/courses
๐ Click on Show More
๐ฎ Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubre...
this sorry
yea that one was what i was referring to
theorically you just need change the ip address to my local ip address
maybe you have to enable allow remote connections, sorry i havent specifically done this. Id just double check to make sure the address is correct, and that the client is trying to connect to the correct address as well
I thiked about this also, but in his tutorial he didn't activate it
i dont think it was a thing back then, his doesnt seem to have the option
"it is recommended to leave remote connections disabled for local testing t avoid exposing ports on your device"
In unity lobby how do I run code when you join a lobby for example to show the in lobby ui
you need to expose your ports, if it is doing what I'm thinking
also if you are developing on windows, it could be that you need to change some firewall settings
hey guys I am doing Photon PUN2 multiplayer game, first player creates a room then joins a game, second joins room and then the game, my problem is when the second player joins, his avatar spawns twice(when you are first player then you spawn correctly only once)
this is my code
the script is attached on a gameobject that is already on the map, so it instantiates the player, when he loads the scene
For local network also i need configure router ?
oh that is what is meant by that, I thought it was a button/checkboxing blocking incomming traffic, no you don't need that
than it will most probably be a firewall issue
please
I disabled it. Is it Allow Remote_Connection ? I have to enable it maybe ?
ok got it
did it work?
It seems working with only one computer, i need wait this evening to try on my other computer
only in one computer*
@nocturne vapor ok I tried, still the same problem
ok finally I found the solution
activate Allow Remote_Connection + disable firewall
i need to spawn a gameobject, but only the server is able to do so, the logical solution is to create a ServerRPC funktion. But here comes the problem, the server rpc funktion cant use refrences required to spawn objects
am i missing something ?
you can use a ulong to send a gameobject in the Rpc function
thank you, do you know how i can disable a gameobject that is a child of a network object so that it is disabled on all clients aswell ?
I dont know if this is correct but if you call a server rpc that calls a clientRpc with the gameobject I think that would work
I keep getting this error when trying to use the NetworkAnimator when I click on the error its telling me that
m_NetworkAnimatorStateChangeHandler on the actual NetworkAnimator script NullReferenceException: Object reference not set to an instance of an object
does anyone know how to fix?
So I think Praetor is suggesting I should move this issue here.
Networking Solution: UNGO
Issue:
So currently my player uses the PlayerInput and InputAction systems, along with Cinemachines free look component. When new players connect the camera pans over to the most recent player that connected, But as far as I understand this shouldnt happen as the camera is not a synced object, thus its a bug.
Intent:
My camera should maintain its currently viewed character in each instance of the game. My current solution that does not work is:
Have you raised the priority of the virtual camera component for the player the camera should follow?
I put in my playerscript something like ```[SerializeField] private CinemachineVirtualCamera virtualCamera;
[SerializeField] private int cameraPriority = 11;
if (IsOwner)
{
virtualCamera.Priority = cameraPriority;
}```
So if you're the owner of the gameobject then the camera stays with you, else it just swaps over to the newest player I think. If I'm understanding your problem correctly.
You are so correct, It was so obvious, and I hate my life
I shouldve known
Thank you so much
I wouldn't have known either if the course I did last month didn't tell me ๐ You're welcome.
I dont normally work with cinemachine, but its got a lot of baked in features I shouldnt reinvent so thanks for the help
You should normally deactivate the camera per default and enable it only for the spawned local player
Same goes for all the components that go along with it, like the cinemachine brain
Same for ui btw
Yeah that might even be better, my solution was more based on having just 1 camera in the entire scene, but I see now that you've placed the camera on your prefab .
My camera is on the scene level
my cinemachine freelook is on the character
the view you see is the prefab level
ah ok, the camera object is just an empty then ๐
I can't find the checkbox ๐ฆ
you probably need to do it via c# script, so in your network script
I can't find the desired property or method in NetworkManager.Singleton
If i destroy network objects there are still ghosts of them frozen in time on all other clients
Even if i call the networkobject.despawn funktion
whats a good udp libary do yall recommend that has built in reliable/unreliable data
answering that last question in #๐ปโcode-beginner here is how you can send custom data with unitys netcode for gameobjects.
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/
then rpc's have a reliable/unreliable version
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/reliability/
so how would i have the server call an rpc on the client when the server and client are in a different project?
you'll probably want to ask in the netcode discord pinned in here, im not too familiar with if theres any differences between making a server vs client build
Anyone have idea how to set parent of an instantiated prefab in Photon?
why does it instantiate whenever a player joins i want it to instantiate one time only im using photon pun
this is the code:
public GameObject gun;
public float minX , maxX , minY , maxY , minZ , maxZ;
// Start is called before the first frame update
void Start()
{
Vector3 randomPosition = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), Random.Range(minZ, maxZ));
Debug.Log($"Spawning at: {randomPosition}", gameObject);
Instantiate(gun, randomPosition , Quaternion.identity);
}
can i pass a TrailRenderer through a ulong ? same thing for a RaycastHit
Hi, I want to make sure my NetworkVariable will be updated immediately, in the docs https://docs-multiplayer.unity3d.com/netcode/current/learn/rpcvnetvar/ at the bottom there is this pic showing that I can update NetworkVariable with ClientRpc, but I can't get it working.
Choosing the wrong data syncing mecanism can create bugs, generate too much bandwidth and add too much complexity to your code.
you can just do it like this
what exactly isnt working
I have that method
void SyncVariableClientRpc(NetworkVariable<Output> currentServerState)
{
if (IsHost)
return;
this.currentServerState = currentServerState;
}```
this is called on the server, I make sure my `Output` is network serializable
[System.Serializable]
public struct Output : INetworkSerializable
{
public int tick;
public Vector3 pos;
public bool isMoving;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref tick);
serializer.SerializeValue(ref pos);
serializer.SerializeValue(ref isMoving);
}
}```
but in the console I get errors that unity dont know how to serialize NetworkVariable<Output>, so I've made that method
public static class SerializationExtensions
{
public static void SerializeValue<TReaderWriter>(this BufferSerializer<TReaderWriter> serializer, ref NetworkVariable<Output> val) where TReaderWriter : IReaderWriter
{
var o = val.Value;
serializer.SerializeValue(ref o);
val.Value = o;
}
}```
but it still not working
yes, but I want advantages from the both RPC and networkVariables
And on this pic they somehow are sending a and b as parametrers, and I assuming that a and b are netwrokVariables
you could just pass in the tick, pos and isMoving variables speratley. If it is a network variable you dont need to sync them manually. a and b ar just defaul inputs like ints or floats like any other funktion
But network variable aren't synced immediately, but I need that feature, and also when new players will join I want that they will know last state of other players, so I need somehow combine functionality of NetworkVariable and ClientRpc.
thats too complicated for me sorry
No problem, I am struggling with that for couple days ๐ and I'm starting to thinking that I will not be able to do this in that way
You don't normally use both RPCs and Network Variables at the same time
I have a throw command in my game that adds force to a RB but when my client uses the throw the rigidbody slides way further than when the server/host does anyone know why?
You'll probably have to show code for an exact reason why. I'd assume it's the way your client is calculating the force, are you doing this by some rpc? You would want to have the server just calculate it based on the clients input
well Im trying to find the problem by doing everything client side at the moment and im still running into the issue let me look deeper into the code because i think your right its probably a Rpc somehwhere calculating things wrong
You wouldnt want clients to add force in this way, especially not by rpc since they're more for events. You'll either want the client to have authority over its movement, or just have the server move everything purely based on client input
I tried something similar when learning, it doesnt go well because the clients dont see the correct values. For example if your client tried to add force to jump, it would likely try to apply it multiple times before the object even got off the ground server side
I just made it completely client authoratative and Im still running into the issue its weird its like the rigidbody linear drag isnt working correctly it could be the way im spawning in the object maybe the drag isnt updating
I made it completely client authoratative to check and its still happening
Is this like throwing a grenade?
yeah
It will need to have a client Network Transform and rigidbody as well as be owned by the client too
let me try that really quick
Hey, I was wondering about Netcode and multiple games on a single server. Is NetworkVisibility the way to go? Hiding GameObjects from each player according to their "room ID" or something? What about scene management? If I Load a scene per room, I didn't see a way in the docs for hiding scene loading events from certain clients (i.e. all players on the server will know that some other room is loading a scene).
hello any idea why the chat doesn't show text in other client https://pastebin.com/sAGdZi35
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
I have this error : Only the owner can invoke a ServerRpc that requires ownership!
UnityEngine.Debug:LogError (object)
PlayerNetwork:functionServerRPC (char) (at Assets/PlayerNetwork.cs:0)
PlayerNetwork:<Start>b__5_0 () (at Assets/PlayerNetwork.cs:22)
UnityEngine.EventSystems.EventSystem:Update () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:514)
It's possible but not really recommended. Usually it's one unity server instance per match. Your server hosting provider should handle running multiple instances per virtual machine
Sounds like PlayerNetwork is not owned by the clients. If it's a in scene object then it will be owned by the server. The server rpc would need to set to requireownership = false
Ah ! Yeah exactly. Thanks for that info will try it
Hello,
I am interested in developing a multiplayer game and I am currently collecting information about potential technologies and capabilities that I could incorporate. I have been looking into Unity Services, and I'm particularly interested in using features like authentication.
The ideal setup for my game includes a backend server which allows API calls. These API calls should facilitate actions such as claiming daily rewards and retrieving user information from a database.
The game itself will feature 1vs1 turn-based battles. All of these battles need to be authenticated by the server, and the players' stats should be updated on the backend after each battle. After the update, players should be able to claim their rewards. This is a high-level overview of my project.
However, there are still some aspects I'm unsure about. For instance, I want to understand how I can allow a server to modify player stats on the database through Unity's netcode. I'm also not sure which Unity services would best suit my project's needs. My experience with this is limited, so I'm also looking for a matchmaking system that could match players based on specific stats.
Could someone please advise me on which technologies I should be looking into, so that I can start learning about them? I would prefer to use Unity-based solutions wherever possible.
i have a question, i have guns with raycast hit detection and im using a Trail renderer that is instantiatet at the tip of the barrel and then moved to the raycastHit.point I want this line to show up for everyone but the problem is that only the host can spawn network objects and if i call a serverRPC that has a massiv delay and if you are a client and you shot you will see the line with a huge delay, how do other games do something like this
Assalam Alaikum.
In a drag race, a player's car reaches finish line. How can I then display a "You Won" and "You Lost" messages on the two different players using RPC calls in Photon?
Hey how can I use NGO for taking damage as aplayer if it collides with something?
Handle it on the server and have the health be a network variable
Clients should be able to spawn things that arent network objects, you can have a local one for the client
any idea why I have this in my chat system ?
i just wrote hello, and it showed hello =\n and blanck line
here the code https://pastebin.com/kGgwn0u3
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Maybe put \n in Single Quotes, specify encoding make the String a fixed length? Tried to find a Solution But idk where the = comes from.
Or try Environment.NewLine
@somber geode it is working well with only the host, but a client connect it doesn't. It seems
ok i finally found the solution, was missing if(IsOwner)
Whats faster, a client that calls a server rpc that calls a client rpc that causes an event or a network variable that when changed causes an event ?
Hey I have this, when I shoot on the client it will only shoot in one direction, not where the mouse is
since a client can only communicate with a server it should be about the same, if you go for the network variable just be sure to set the write permission to owner, if it is on the player otherwise you would have to server rpc->network variable -> variable on change
thank you
how exactly do i despawn networkObjects for everyone, since only the server can destroy it and i cant pass an object refrence trough the server rpc
and sinmply calling the destroy funktion leaves the object floating in the air
Do it in a server rpc
You can create a script on that gameobject which has a destroyServerRpc function which you call. That way the object executes it and there is no need for passing an reference
Generally if the networking framework doesn't automagically convert networkobjects to IDs, you can send the ID yourself and convert it on the other side
I use unitys networking framework
Yea either it works automagically or you do the sending and look up youself. Haven't used Unity's solution.
But marsimplodations idea should work
You can also use these to send a reference in a RPC
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/#networkobjectreference
Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects
it works, it is just a matter of how you want to do it, for me it is always a certain kind of stuff, which has a script anyway (buildables, trees, ...) so it was the easiest solution
Hello guys, i try to setup a character controller with NetCode, i succesed by sending the Inputs to the Server, calculate position on the Server, and send it back to client, Works perfectly, Then I added a little bit of Delay,Jitter and Paket Lost and the experience was awfull and beside that, i was sending RPC at tick rate (the input, and i dont know if this is ok or not)
Is this how things sound work?
And i try to make the player move its avatar, but cant really succed here, its like "Any move i make has to be on server"
Took a little break from this problem and revisited today. I resolved it by calling SetCoin() instead of AddCoin(). This resolves my issue because SetCoin() instantly updates the coin amount.
i don't know what to call this phenomenon, happens on instantiation of chess pieces... any name for this bug? i don't care about the position of chess pieces on player 2 but on player 1 the pieces are looping/lagging/whatever
How can i get the client id of the client that runs a script?
in unity netcode
or better said, i have a server -> client rpc and i dont want whatever hapens in the client rpc to happen for the person that called the server rpc, how would i do that ?
Thats the wrong channel I think
#archived-works-in-progress might be better suited
Uh sorry then
hi , i want to make my game to be able to hold up to 4 players in multiplayer, what are my best options, easier they are better they are. Latency and such stuff is not as important, its a co op. what is important that it is easy to set up, and that i can put it on steam after its all done, thanks
hi, i have a basic game that works nicely in single player, but i want to make it multiplayer, and since i am a pretty poor person i can't afford servers and stuff like that, so i found a solution : host the game on the players device by using their IP , (like some old games used to do) however i have absolutly no idea how to do that in unity (i tried to look similar ideas online but i did not see anything that helped which is why i came here), i you could help me that would be greatly appreciated.
Using a client network transform would be the easiest way to get something up and running and feeling smooth
Unity Relay service would work well for this. It has a free tier that you can use. There are other options like Steam or Epics P2P services
oki ty, i will look it up
i have a question about that, do i need to change a lot of code if i switch to steam
Not really. Its just a matter to switching Transports. Might be a line or two to change where you get the IP address. I've not used Steamworks before
how is unity netcode for gameobjects, has anyone tried it and can confirm its easy to set up?
It's good, but in terms of difficulty though that's entirely on you and what kind of game you're making. It's easy enough to just get players moving but theres often gonna be way more than just that
well im making coop zombie shooter, i first want to finish singleplayer aspect and then work on the multiplayer
so im wondering which one is best considering il have finished game that needs to be implemented to multiplayer
You'll end up rewriting a lot if you code the single player first
The steps I usually do are code 1 feature to work in single player just to make sure it works, then make it work in multiplayer
You need to handle all the steam stuff, like invited and lobby hosting. So you need additional code, I'll search up a tutorial real quick
This Unity Steam Multiplayer tutorial will teach you all about how to setup with Steamworks/Facepunch combine with Unity Netcode For GameObjects and get started with your own project!
#facepunch #unity #netcode #steamworks
Facepunch comma...
well i am aware but after the code is done i believe its gonna very easy rewriting it, no?
That is a hard no
and also if i want single player game to work in offline for example, it wont be able to work without a host etc. that netcode needs
I dont have much multiplayer experience, but generally if your plan is to rewrite something from the very beginning then you're doing something very wrong. It's possible, but a LOT will change
You would just run the game as a host and not allow remote connections for single player
yea but that means its still online game just with 1 player
i dont understand honestly what in the code will change that drastically
arent things just gonna be added to it?
i got very little experience with multiplayer i hardly understand how to make it but i kinda understand how it works
Well it wouldnt exactly be online if you dont allow people to join. When you test and develop, itll all just be local the same way you'd be playing single player.
but wouldn't the network manager threw an error if you are offline?
No it wouldn't you can host a game completly offline
ok thats cool
well im still in very early development of my game but i really want to make it endless co op zombie shooter with 2-4 players
preferably 2 tho
No basically any action that everyone should see will have to change. It really depends on if you use server or client authoritative, but you're gonna be adding a lot of logic in your code to make sure the wrong person isnt trying to update a value
Shooting, moving, swapping levels, reloading, building, all of these features will require a rewrite
Just as quick examples
well yeah but isn't that just adding network transform and network animator components?
i mean i dont know honestly i know something but il have to do alot of reading before i start it myself
i now have pretty much my character set and 1 npc and now im thinking will i go the way to develop it single player first or start working on multiplayer aspect of it
by character i mean whole gunplay(recoil,animations,reload,ammo,weapon switch,etc)
i made map design and added 1 mob and working on another
That's how you can sync components, but the same single player code wont just work. You'll be going back and adding a lot of network variables and stuff like if(isOwner). Its just way way easier to write by doing multiplayer the entire time
but IsOwner is still just adding to it
and variables is like 1 sec of rewrite
is it really that difficult?
I provided like the simplest rewrite as an example, but remember this is gonna have to be in a lot of scripts. If it really doesnt deter you that you would have to go edit almost every script you've made then you can try. I just dont think a single person out there would recommend doing it this way
Ok il listen to you , im like very neutral to this because i know very little
its not a problem for me to dive into it i think im pretty ready
but, can u tell me is netcode for gameobjects going to be simple to combine with steam
and is there something i should look after when aiming for it to be steam game
?
Like let's say you want to swap weapons, that's super easy locally, just activate/deactivate it. When it comes to networking, now you have to send some data to the server who sends this to all clients saying which one you equipped
yes that is true, but it will still only add to it i believe?
It shouldnt matter which networking solution you use I think, using steam will be the same roughly with all networking solutions. I set it up with ngo
Im unsure what you mean by only add. You would literally be rewriting the code
I can give you an example for a rewrite
My player inventory is local and thats the way I want it to be
To write to my database however the host needs access to all the data in it, so I needed to write a complete class which accesses the player inventory processes important identifiers (steamid, slotnr, itemname, item count) and sends them to the server. The host/erver will now have a copy of that inventory and can write it to the database
In order to retrive that same inventory I have to do everything in reverse, so it is not just adding network variables
what do you mean? I just need something that tells the server which gameobject is currently active for that person
and honestly i though network manager / network transform already had those included
And that is with allready making sure that the inventory only is written by the local player
i mean it sounds like its really just adding honestly, u had to ADD webrequest i assume to the ADDED hosting site ur on, from there you had to ADD script that reads out to the unity ur inventory, and if u set ur database right like inventory i dont see issue, u just take what u get back from that field into ur script that will then manage the rest
by probably ADDING something haha
But i do understand your points if u didnt prepare it well for those steps you probably had to rewrite some stuff
The problem is that you need to structure everything in a certain way and generally it is not recommended to add multiplayer to a game after you have written the core mechanics. You need to design these mechanics with multiplayer in mind
Thinking about where to execute what
yeah okay im all ears guys, but i do need advices thats why I am here
i really appreciate ur time but can u tell me where should i learn more about netcode for gameobjects
i saw a good tutorial by CodeMonkey on YT but i need to read more of it and understand it better
Codemonkey has a course on youtube and the rest is honestly reading the official docs and experimenting
Thats how I learned it
how long it took you?
honestly
to master it
i mean not to master it, but to be able to use it alone without googling much
or just using it
also im sorry for all questions, but how do you create rooms for your game?
with netcode
how does that work?
Oh and arguing with chatgpt. I find it very helpfull to share my thoughts with it.
Like describing a problem and than what you did to solve that problem if this is a good aproach
It is just to organize your mind and to get feedback
A month? Maybe two?
I still look up things in the docs
qq: does unity have any built in utilities for transfrom prediction based on previous samples? i'm looking for somethiing better than dead reckoning that will factor in angular velocity.
I'm using steam lobbies and a custom written script to convert steam lobby ids to invite codes
can i see how that looks like?
I don't think so, ngo is very basic when it comes to stuff like that
i've never had nothing to do with steam im pretty much a begginer and this is what i want to be my first steam published game
It is on my github, linked in my profile. You won't learn much about networking tho, it is just a base10 to custom base62 coversion with some binary magic
do you know of any third party assets or popular algorithms?
Sadly no
is it ok if i DM u if i get stuck somewhere?
It would be, but you will probably have more luck trying it here. I try to reguraly look into this chat and some others like evilotaku and bawsi do as well always ready to help
cool, thanks
Just curious, is the invite code gonna be the same thing for someone everytime? I was thinking of adding something like this but not sure since I dont want people joining friend groups randomly
If you join the netcode discord in the pins, itll probably be seen quicker/not buried away. This channel sometimes gets people asking for photon, mirror, etc
can you point it out?
No every lobby has a id attached to it, to identify it. Since steamids are also used for everything else alot of it is boiler plate, readable in the steamworks documentation and other places.
I have put in comments what stand for what.
A certain part of that id is truly unique, I take that part out of it, thanks to chatgpt and the good documentation I got the correct binary places, and convert these numbers into numbers and letters.
The important part is it is not hashing but base conversion so 1 to 1 and not with any conflicts. That way I can put it back into a steamid and join the lobby with that
So it has to do with the lobby not the owner and that id is not the same everytime
The pins button, then scroll down, it's the unity multiplayer networking one
im sorry but i dont see that?
Ah I see, I was thinking of having it based off steam ID then just apply some really simple encryption/decryption but I might just stick to only allowing friend invites through steam
The pins button or the discord link?
Here is the message itself
I do both, invite/join via steam ui and joining via code for less technical users or public lobbies
Ah
hi guys, begginer question, I have NGO installed, and when i run the game from host it works good, then i join client in, my host has no control he doesnt move at all while client moves freely as supposed, that is happening after i set if(!IsOwner) in the movement update, as if client is owner of his movement script but the host is not owner of his movement script , anyone knows why this is happening? when i remove the if(!IsOwner they both move on both client window and the host window.
I set up a tick system via code not knowing that Unity has a built in system for Netcode, is it okay to continue to use my own system or should I use the built in NetworkManager Tick system?
Is the host still the owner after the client joins? You can also check what happens when the 2nd client joins, I guess it might be either some issue with how your player objects are spawned. But not 100% sure, it's hard to pinpoint just from that
You can also try asking on Unity NGO's discord, people there are super helpful
can you give me a link?
it's here
host is host and client is client as far as i know, 2 buttons different functions for each, and now idk about how they are spawned im very new to this
i went back to 1.0.2 version and gonna try to follow the codemonkey video on yt to see if it fixes it then il go from there
As said, you can try joining yet another player, maybe this will give some clue. Player movement in multiplayer can be tricky, and once you get to stuff like client prediction and player interpolation... Things get fun ๐
i do love challenges, it makes u learn, but i hate being stuck on one for too long hahah
It took me quite some time to get my own movement script working in MP. And then a few months later I decided I want physics to work too, so I had to make movement server-side, and than once again was a lot of reworking. But that's a great attitude you have!
If you need some help, feel free to DM me. I can't answer 24/7, but maybe I can help with something, from what I've learned myself
sure , thanks ๐
btw why is physics hard to work? im gonna need ragdoll to work so im wondering
Unity Physics is nondeterministic. That mean two identical collisions on separate machines could have different outcomes.
oh and also, clientId:0 is a host right?
If you handle everything on the host then you have to deal with lag.
and yea. client 0 will always be the host
i am making co op game
well why is my client becoming id 0
if its not the host then its not id 0.
nope my bad hes not becoming id0 its just that the host is controling client and client is controling client i believe