#archived-networking

1 messages · Page 26 of 1

ripe mesa
#

there is one from asset store, you can host the server itself and another one is from #1180170818983051344

#

let me find it for you

final laurel
#

It's already terrible that I have to migrate from photon PUN because it's not supported anymore

#

migrating again if the unpopular tool gets discontinued would be painful again

ripe mesa
#

alteruna multiplayer

abstract siren
#

Yo, im new into Unity how long would it take to, like start knowing the engine?

abstract siren
#

sry

ripe mesa
#

try to ask Bobsi, he creates a lot of video on it

final laurel
untold anchor
#

Does anyone know how I can fix this, I have been stumped on this for DAYS (2).
Using Unity's Relay and Network Manager to grab the Relay join code and redisplay it when a server/host is activated on the host's screen

proud schooner
#

Is anyone else having major issues with the new Starter Assets 3rd person and netcode for objects? I just cant get it working at all. When I do, I get one character falling through the world and can only control one character, will not control the other clients. I am using cinemachine on all characters. Is it a known issue with the new starter assests controller or just me?

final olive
#

Hello

#

Guys i make project with fishnet but when i realize the video dont explain what i want and idk if there video explain what i want with fishnet

#

So i want ask here how can i make menu for lobbys with fish net

#

Sry for my english

dim smelt
final olive
#

Okay i want ask what is the asset to help me make online game photon or netnode or something else?

sharp axle
# proud schooner Is anyone else having major issues with the new Starter Assets 3rd person and ne...
GitHub

A collection of smaller Bitesize samples to educate in isolation features of Netcode for GamesObjects and related technologies. - Unity-Technologies/com.unity.multiplayer.samples.bitesize

proud schooner
#

@sharp axle Ahh thank you, I will look into that one.

old mural
dim smelt
#

@final olive There are many networking assets. I use Fishnet myself, but the others are also good. Mirror, Photon, NGO, etc. There's a lot of different solutions. Your best best is to download them, look through each one comparing how RPCs, sync variables, etc. work, and pick the one you like. Many have demos that come with them. One of the most important things is support and being able to ask questions. Fishnet, Mirror, etc. have their own discords with 24/7 help. Pretty good free help for everyone.

blissful jay
dim smelt
#

To each their own. Nothing wrong with trying out every option and seeing for yourself.

blissful jay
dim smelt
#

When my wife was alive, I didn't think she was a good person many times. People say hurtful things or do things they regret. But, I still stayed with her because I liked the features of the asset and it was the best 10 years I had in my life. Have to take things with a grain of salt and find what works best for you.

blissful jay
#

you liked the features of the asset?

#

pls don't bring your personal life matters into a gamedev discussion

dim smelt
#

Best feature was her kindness. Cared for everyone no matter who they are and what they had done in the past. That rubbed off on me over the years.

blissful jay
#

took it for the admin

dim smelt
#

No one is deleting anything. Stop trashing people and be nice. I know you are upset for some reason, it's okay. Everyone gets to pick the solution they want to use. Let people choose on their own. It's important they look at every option regardless of opinion to make a good decision with information they see for themselves.

blissful jay
dim smelt
#

pls don't bring personal conversations into gamedev discussion

blissful jay
ripe mesa
#

I think its too far to say that

blissful jay
#

@ripe mesa ngo is good or bad?

ripe mesa
#

Mirror is a wiser choice

blissful jay
ripe mesa
# blissful jay really?

both are not really differ, but for a game more than Indie I recommend Mirror.
I have seen couple of good NGO Games, but they are small coop games..

#

While Mirror has been battle-tested, I've seen and played several games with it including the MMO

ripe mesa
#

Heartwood online

#

the pixel art kinda not perfect: resolution and style consistency, but I find the game is solid

final olive
ripe mesa
#

all depends on your need

final olive
#

I want something like vr chat but without vr a game for real life talking sit you can call it Simulation

#

And sry for english

ripe mesa
final olive
final olive
ripe mesa
#

photon fusion, shared mode

  • Free 100CCU
  • No Server Required
final olive
#

Maybe I will add some mini games like cards later

#

K ty for your time

untold anchor
white torrent
#

can i still use a player input manager to detect if a device was connected/disconnected or is being used even if i'm making a networked game?

white torrent
#

i mean thinking about it it should stay local

sharp axle
#

it probably should. as a client, why would I care if some other remote player plugged in a controller or not.

white torrent
sharp axle
white torrent
sharp axle
white torrent
final olive
#

nvm

cedar cloak
#

What .dll should I use in order to set up a websocket and make an API call?
Currently I've read about WebSocketSharp and NativeWebSocket but they seems deprecated... am I wrong?

spring crane
#

I don't think either of the ones you mentioned are deprecated

#

WebSocketSharp has been getting daily updates for the past week month and NativeWebSocket is used by a commercial multiplayer framework.

cedar cloak
#

Ok then I'll try websocketsharp first

#

are there any restrictions on doing this kind of request on webgl builds?

spring crane
#

Not aware of any. The data is piped from WASM to JS, so if you can do it in JS, it should be fine.

spring crane
cedar cloak
sharp axle
sleek laurel
#

does anyone know how your supposed to spawn local objects using unity netcode for gameobjects?

i keep spawning local objects using new GameObject() but every time a new player joins they seem to get deleted when i dont want them to?

Only solution i seem to come across is adding a NetworkObject component to them and then spawning them using NetworkObject().Spawn() and then changing visibility per client, but this would require me to rewrite my entire chunk system and is just a lot of hassle.

covert gull
#

Do co-op non-compeititve games such as lethal company, deep rock galactic, phasmophobia, etc. use client side prediction? Is client authoritative movement okay? I'm not so much worried about cheating, but more so worried about how the experience will be if someone has a laggy connection

dry maple
# covert gull Do co-op non-compeititve games such as lethal company, deep rock galactic, phasm...

I don't think they use it.

Client-Side Prediction is not only about cheating, it also helps with making interactions between players and the environment more accurate.

Because clients are preparing their inputs ahead of time to a certain future tick in the server, that means actions between players are going to line up better than when clients are just doing things as they wish (client-auth).

It also means you can avoid other players looking laggy for good connection clients. Because the server can simulate their characters even if they have packet loss and their inputs are being lost. So with non-CSP games, you usually see laggy players teleport. In CSP games, if a laggy player was falling, it will keep falling nicely for other observing clients when that client has packet loss/jitter, because the server is still simulating gravity for them.

Also if you want somewhat accurate physics interactions and collisions, CSP is the best way to handle this.

But for a simple co-op game, this could be overkill or not needed.

sharp axle
sleek laurel
#

im only trying to create the object locally

#

but when other players join, the local objects get deleted

#

when there is nothing in my code deleting them

sharp axle
sleek laurel
#

ive seem to find a semi work around which is just doing it as childs of my player object

#

and that seems to work

#

but idk why i have to do it like that in the first place

tame slate
sleek laurel
#

it happens if i use an empty prefab too anyway

tame slate
#

Right. Makes sense.

#

I'm not sure about Netcode but Mirror does not like when scene hierarchies are out of sync between the server and the client.

#

My guess would be that Netcode is the same.

ripe mesa
#

Man if only people said "NGO" instead of "netcode"

tame slate
ripe mesa
#

this is the correct wording:

  • csgo netcode is good
  • is there a game with a good netcode?
  • how to build a good netcode for games?
tame slate
#

He mentioned in his original message that he was using NGO. Pretty sure he knew what I meant. Netcode is a perfectly acceptable short form in this context lol.

ripe mesa
#

I just felt like its too criminal to refer it as ngo

sharp axle
spring galleon
#

Hello all! It's me again 😁
I finally got the ClientNetworkTransform to work which then made me able to control the client player. However., when the host hits the puck, it responds properly. But when the client does, it kinda moves glitchy back and forth before bouncing off to the properly predicted position. This position isn't reflected on the host. And when the host hits the puck, the clients copy telelorts to the host copy's location

#

Host - right
Client - left

#

I need to know how to fix it so the puck syncs properly thru the host and client

covert gull
#

I'm trying to use multiplayer play mode, but when I check the Player 2 Virtual player, it just keeps spinning and saying activating. Am I missing something?

sharp axle
sharp axle
covert gull
#

I am getting this error with the multiplayer play mode:
An error occurred while resolving packages:
Project has invalid dependencies:
package: The file [...\Packages\package\package.json] cannot be found

covert gull
covert gull
sharp axle
#

oh the minimum Unity version for it is 6000.0.3f1

covert gull
#

Got it. I'll try

#

I'm on 6000.0.4f1

#

Same error

sharp axle
# covert gull Same error

If you are still getting invalid dependencies then you might need to reimport the project or just delete the Library folder

covert gull
#

I'll try deleting the library folder

spring galleon
sharp axle
# spring galleon Yh, anticipatedNetworkTransform, it's what I used to go this far
GitHub

A collection of smaller Bitesize samples to educate in isolation features of Netcode for GamesObjects and related technologies. - Unity-Technologies/com.unity.multiplayer.samples.bitesize

tame slate
# spring galleon Hello all! It's me again 😁 I finally got the ClientNetworkTransform to work whi...

You should probably take a step back before worrying about Client Side Prediction. NGO is more than capable of running a 2D air hockey game with essentially no desync and very little delay for clients. You should be aiming to get to the point where the puck is not teleporting on either host or client, and the client's puck should only be slightly behind the host's. This obviously may not be good enough for your final product, but it's where you should aim to be before adding in stuff like Client Side Prediction.

#

Adjusting your NetworkManager's tick rate, your NetworkTransform and your NetworkRigidbody sync settings like interpolation + thresholds and probably most importantly making sure your local code + your networking calls are as perfect as they can be.

#

For your final product you may want Client Side Prediction (especially if you're letting players hammer the puck super fast 😄) but again, NGO definitely is capable of allowing you to make a perfectly fun air hockey game (with just a little bit of delay for clients) even if you don't decide to use it.

#

The first two games I made with NGO were before 1.0.0.. CSP didn't even exist as part of the package. You had to code it yourself! Which I never bothered doing because of the reasons I stated above. If you play within the bounds of the library, you can still have basic physics sims with little delay that most players will hardly even notice.

spring galleon
#

I would try your idea though. Everything is a solution as long as it's not giving up 😁

tame slate
#

Even more reason to leave Client Side Prediction until later. A lot of game development is about building blocks. You can't add the top of the tower before the base is solid. Game engines are powerful tools and if you love games it's hard not to just want to jump right to the final product and have the best game you can imagine. But it's all about iteration, don't get discouraged!

tame slate
#

Not sure how new you are, but to help with iteration and the testing of your own code.. Attributes are really helpful so you can change values in inspector instead of directly in your scripts.

#

[Space] - will create a space between variables in the inspector
[Header("HeaderNameHere")] - helps you label and/or group your variables
[SerializeField] - exposes private variables so they can be seen and edited in inspector while maintaining their access level in your code

spring galleon
tame slate
#

ah, just Unity AND Networking. Gotcha 😄

old mural
#

Anyone have tips to figure out how many server processes can fit on a particular host? I’m curious if anyone has gone through the exercise of figuring this out for themselves.

I’m using AWS gamelift, which ultimately runs on an EC2 instance. I’m not 100% sure how many server processes to start up per EC2 instance, or how to determine the type of ec2 I should want to use.

The game itself is a death match multiplayer looter shooter, if that helps at all.

austere yacht
# old mural Anyone have tips to figure out how many server processes can fit on a particular...

You have to test that for your specific game. Besides cores which can be mapped exclusively you also need to consider other hardware resources that are shared, like the network adapter(s). Typically you can expect 1 process per real core to work out nicely, given your server is designed well and doesn’t rely on multithreaded code or saturates the NIC. If it does, all bets are off. For HPC nodes with lots of cores you can probably make it work for multithreaded servers but it’s likely better to run multiple smaller nodes as they are more isolated from each other.

old mural
sharp axle
covert gull
#

Is it a bad idea to have client authoritative movement for a co-op game where players are on a ship that can pitch and roll in an ocean? My concern is that if the ship’s pitching and rolling is server side, and if a client has an unstable connection, other players will see the client potentially hovering in the air or clipped into a wall. Because of this, I’m wondering if I should use server authoritative movement for everything with clientside prediction. Is this a good idea, or overkill for a co-op game where I’m not concerned about cheating? I just want the game to be accurate and reactive for players

spring crane
sharp axle
# covert gull Is it a bad idea to have client authoritative movement for a co-op game where pl...

You can run the network simulator to test against poor network conditions
https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/

The Network Simulator tool allows you to test your multiplayer game in less-than-ideal network conditions, enabling you to discover issues in simulated real-world scenarios and fix them before they surface in production. It facilitates simulating network events, such as network disconnects, lag spikes, and packet loss.

rich meteor
#

How do I handle any kind of resource collection over multiplayer with client prediction? So say a player has insane ping, collects 4 coins, updates coin counter locally. The server then registers all that and sends confirmations to the client with their current coin sounter value. So now the player sees their counte go to 4, then to 1, then slowly to 4 again. Should I instead just return a boolean from the server indicating whether the player successfully collected the thing and if no, just deduct it back on the client instead of sending the entire state?

white torrent
#

I'm trying to spawn my players at a custom position, but no matter what i try they still spawn at their local position. Why?

[SerializeField] private Transform spawnPointParent;
private List<Vector3> spawnPoints = new List<Vector3>(); 
private void Awake()
{
    var networkManager = gameObject.GetComponent<NetworkManager>();
    networkManager.ConnectionApprovalCallback += ConnectionApprovalWithSpawnPos;

    for (int i = 0; i < spawnPointParent.childCount; i++)
    {
        spawnPoints.Add(spawnPointParent.GetChild(i).localPosition);
    }
}

private void ConnectionApprovalWithSpawnPos(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
    response.CreatePlayerObject = true;
    if ((int)request.ClientNetworkId <= (spawnPoints.Count - 1)) {
        Debug.Log("expected spawnpoint is: "+ spawnPoints[(int)request.ClientNetworkId]); //This fires.
       // response.Position = spawnPoints[(int)request.ClientNetworkId]; 
        response.Position = new Vector3(100,100,0); //debug code, playerObject still spawns at his position
    }
    response.Rotation = Quaternion.identity;
    response.Approved = true;
}
white torrent
#

i'm guessing this doesn't work for the host. that's my issue, don't know how to fix it

dry maple
#

Depending on your game, you might need to respawn the player again in the future.

So that way the system will behave more appropriately for the entire life cycle of the game.

dry maple
# covert gull Is it a bad idea to have client authoritative movement for a co-op game where pl...

I think it's a bad idea only in respect to having to enable PhysX prediction which is quite costly.

Other than that, it will make the gameplay experience way better overall, assuming you are using a proper CSP implementation.

Though, if you choose to not use CSP, there are probably many ways to workaround your problem, like parenting, etc. They will all suffer from certain limitations that wouldn't otherwise exist if you were using CSP.

dry maple
# rich meteor How do I handle any kind of resource collection over multiplayer with client pre...

This is not how client-side prediction works.

The behavior you described is a failure of prediction.

A proper client-side prediction system will make this entire process invisible to the player, the game will just play as if it's a single player game

But that's only when the client does not experience outward packet loss, or some other things that cause high degree of non-determinism.

Which means its inputs are getting lost and thus the server simply never executed those movement inputs that led the client to collect those coins, thus causing the mis prediction that might cause the coins counter to rollback.

However, usually games don't predict things like that, because of continuous possbility of other clients collecting the coins before you, causing the misprediction. But usually it's only a real problem if things like the movement of your character or other important gameplay aspects are affected by what you collect.

remote remnant
#

I have a C++ game and a Unity clientside. Is there anything out there people recommend for reliable udp/networking between Unity and a C++ program?
The Unity project will run on a Meta Quest (Android).

I’m not sure how simple it’d be to get C++ working in Unity as a native library for Quest 3, but several networking libraries are single header C++ files that should be straightforward to compile if only I knew the right build steps.
Would anyone be open to helping with this?
Thanks!

#

Alternatively, a reliable udp library with both up-to-date C and C# implementations?

dry maple
remote remnant
#

What part?

#

This isn’t a preference. It’s a requirement. Existing C++ application (server) and Android Meta Quest 3 client (Unity Engine client)

#

I’d like some existing networking solution if there is one, hopefully. I’m flexible otherwise.

dry maple
#

Why is the server in C++?

remote remnant
#

Because I chose to write it years ago. The serverside is a full thousands of lines program. Meta Quest applications are easiest to write in Unity C# projects rather than native.

Are you suggesting there’s no cross-language solution that is actively maintained?

#

I was looking at enet

#

and valve’s sockets library

#

but eh..

dry maple
remote remnant
#

enet has a single header version

#

I am just unfamiliar with how to make a native android plugin to slot into Unity

#

valve’s library is probably more robust, but it looks painful to use

#

The point of this experiment is to fo some cross-device experience

remote remnant
#

That’s kind of what’s making me doubt this

#

It’s too bad Unity doesn’t have a builtin codegen thing to let you just add a C++ file

dry maple
#

You use the C# version of ENET, and the C++ version in your C++ server.

remote remnant
#

There’s no up-to-date C# version of Enet

remote remnant
#

The versions would conflict

#

I think

dry maple
#

Try it.

remote remnant
#

probably there’s no C# equivalent for that one

#

If they change the protocol it’s probably not good but ok I can give it a shot

#

but maybe it’s better to “own” the build process?

dry maple
#

Yea I didn't notice that, may not work.

remote remnant
#

also standard enet doesn’t support the fork’s features

dry maple
#

What about LiteNetLib

Use the exact C# version with this C++ version

remote remnant
#

Are there any good references for just building it myself? I’m on mac, so I don’t know if Unity included a build tool. I assume I need some Android build tool.

#

“As of now, library can be built with MSVC on Windows and with GCC on Linux. OS X support is planned in the future releases.”

uhhh unclear if Android’s supported and I pretty much need mac support.

#

But okay I see what’s happening

#

I should just survey the libraries available a little better

#

But it would still help to know if anyone’s figured out a nice workflow for building native plugins cross-platform

#

maybe another channel?

dry maple
remote remnant
#

fair enough

#

thanks for the links though

dry maple
remote remnant
#

Oh

#

I could straight use the files already in there

#

nice

#

I just have to figure out how to build this though…

#

All it says is to use NDK. That’s very unspecific when it comes to how to set up the project… hmm

fringe spire
#

Hi, i have two player both of which are gameobjects.
How do i detect collision between them ?

#

they handle collision between other surfaces with rigidbodies well but between each other they just simply pass through

sharp axle
fringe spire
#

what else needs to be done for that ? i have added rigidbody and colliders on the player

#

i am not sure what you meant by handled ?
if a client fires a bullet that is a network object and it should bounce off from colliding another network object that how should i handle that on server ?
the best i can do is add collider and rigidbody on both of them. Is there anything that i am missing ? because the bullet is passing through the player object

sharp axle
# fringe spire i am not sure what you meant by handled ? if a client fires a bullet that is a n...

Are you using Network Rigidbody? On the server, all collision events will happen as normal. It might be delayed on the clients due to latency
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/

There are many different ways to manage physics simulation in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.

fringe spire
#

yes i am using network rigidbody

#

i have these components on my object.

sharp axle
fringe spire
#

found the issue, edge collider was giving me problems, if i changed to box collider the collisions were happening

#

i used the edge collider because i wanted a triangular collider

#

will try with polygon collider

#

it worked

#

thanks for the help @sharp axle

junior flower
#

I have followed along with the unity API reference for Half Vector3 but it didn't work and the player's position was not synchronized over the network. Can anyone help me out? Both method #1 and #2 doesnt work at all.

white pine
#

Hello. I am trying to create a multiplayer game where people can host servers and let others join with a code (Something like the game "muck")

Are there any good free solutions for a multiplayer game like this?

#

Also, I currently already have the singleplayer version completely done, so hopefully something where I can easily transition from single to multiplayer

white torrent
#

i made the same mistake once

#

yeah no you're gonna have to basically rebuild at least a good 60% of your game

#

and for servers it depends, if you want like player hosted custom rooms you could do it, but if you want like independent servers you'd have to pay that

white pine
#

I decided on using Mirror

#

I guess its the easiest option

white torrent
white pine
#

So far ive tried out fishnet and mirror but IMO mirror is way more convenient

dry maple
# white pine Hello. I am trying to create a multiplayer game where people can host servers an...

You can check out Netick too, it's the highest performing networking solution for Unity, bandwidth-use.

Easy to use and has a very easy to use Client-Side Prediction system, if you are into that.

GitHub

Netick is a C# networking solution for Unity. Contribute to NetickNetworking/NetickForUnity development by creating an account on GitHub.

dry maple
white torrent
rich meteor
#

I ended up just doing all the management on client with server permission

#

"I spent 3 of this resource"
"Ok"
"And this"
"No, this one doesn't add up, revert that operation"

#

And then sync it up occasionally, like when the server explicitly changes player's resource amount

#

Is this a good way to handle this?🤔

raw stormBOT
vital hill
#

So I have a script that can change the position of an object when you hold the right mousbutton. the objekt will Lerp to the PakageHolder. problem the host can do it but the client not. the pakage objekt has a client transform commponent and a Network Gameobjekt commponent.

raw stormBOT
vital hill
dry maple
#

What I'd personally most likely do is not predict the action of collecting coins.

rich meteor
rich meteor
#

You mean

dry maple
#

Yep

#

Rocket League, for instance, does not even predict collecting the boosters.

rich meteor
#

My case is more like minecraft

#

Where .1 delay between placing blocks would defo be noticeable :\

#

And minecraft itself does prediction on this side I imagine

rich meteor
#

Main issue is handling inventory

dry maple
#

Is your game also voxel-based?

rich meteor
#

Deduct resources, give em back, whatever

#

No, just the rapid building being possible

dry maple
#

I see

#

Yea, I'd predict it then.

rich meteor
#

I see a couple reasons for the server to explicitly tell the client how much they have: When they's a clear error (Player thinks they have enough resources, but they don't) and on initial join

#

Otherwise, since the resources change from the permission of server anyway, it should mostly be in sync

dry maple
rich meteor
dry maple
#

Ah I see

#

You can sync the full state of each object in the game each second, to check for desyncs.

rich meteor
#

Like, I read up on how old rts games were made

dry maple
#

Yea, that's like a bad solution, but an easy one

rich meteor
#

It's basically 90% simulation

dry maple
#

They use lockstep, they only sync inputs.

rich meteor
#

Yep. Would be hell to sync up entire state back in the day

dry maple
#

Because when you have +1000 objects, you can't just sync the pos/rot of all of them, it will kill the bandwidth.

#

But this is very hard to do in Unity.

#

Because almost everything is non-deterministic.

#

So you will need to roll your own solutions for even things like AI navigation.

#

Though another solution to the problem of syncing objects is to use Delta Snpashots.

rich meteor
#

Eh, those can be server side I guess. I won't have thousands of units in my game

dry maple
#

Which means you only sync changes to the networked state.

rich meteor
#

It's just that responsiveness is kinda critical in this specific system

dry maple
#

Another one is Optimistic Replication (Eventual Consistency), Photon loves this method, but I think it's bad and has tons of problems.

dry maple
dry maple
#

That you keep going through and sending parts of it, each update.

#

So with enough time you would have resent the whole thing.

#

And it won't use a lot of bandwidth. Just latency.

#

It's to check for desyncs.

When new changes happen, you just send them directly.

#

Or, when the client changes something, it marks that property as awaiting server confirmation, after X seconds the server didn't confirm, you rollback to authoritative values.

rich meteor
#

What I'm doing right now is that whenever client does something that would change the resource count, it immediately changes it locally, awaits confirmation from server, and if never receives or receives reject just undoes that change

#

Because if the server confirmed and changed it on server side as well, they should be in sync

#

However, when the server explicitly changes client's resource count, it sends the entire thing yeah

dry maple
rich meteor
dry maple
rich meteor
#

🤔

sharp axle
#

Something like an Area of Interest manager would probably help with that. Photon Fusion has one built in. Netcode for Entities has a Priority system where objects closer to you will get synced more frequently than objects farther away. You can look to them for some inspiration

drowsy terrace
#

ah ok, do you know one that can be hosted inside unity ? we do not want to have an external server

tame slate
drowsy terrace
cedar cloak
#

So I enstablished a simple Websocket connection to a testing url (echo.websocket.org)

Here's the code: https://pastebin.com/ja4eNd2D

Now I've tried to use the url I actually need to connect to but I always get "error 1002 can't perform an handshake" and I can't figure out why, the request syntax should be very simple.
Can somebody please help me to figure out what's wrong?

Here's the documentation: https://dev.hume.ai/reference/empathic-voice-interface-evi/chat/chat
This is the url I should point to: wss://api.hume.ai/v0/evi/chat

tame slate
# drowsy terrace Ah because we are working in an offline environment and there is no network conn...

Right. Interesting predicament.. You're going to be hard pressed to find a solution that already exists. If you're not going to want to code your own custom solution, you could maybe just try using one of the handful of Networking Libraries for Unity that are out there? Theoretically you could put the output of a camera on to a RenderTexture, convert that in to bytes, send it to connected clients and then convert it back on their end. I'm not sure what kind of quality or frame rate you'd be able to realistically achieve doing this, but.. I can't think of much else you could try.

#

@drowsy terrace you said you have two devices you want to stream the camera between.. do you happen to a computer not in use that isn't one of these two devices?

drowsy terrace
drowsy terrace
#

but I like your idea of raw byte streaming, I will give that a go over TCP

delicate parrot
#

Is there a way to make a NetworkTransform sync on manual request rather than automatic?

#

I know you could do it via rpc calls but wanted to use a networktransform for the simplicity and reliability if it's an option

sharp axle
delicate parrot
#

ah ok, is there any documentation on when networktransforms send out their info?

#

was curious timing wise (eg. fixedupdate,update,lateupdate and all that)

sharp axle
visual cypress
#

JKim I am still on the fence. Can you help me out in your decision?

digital stag
#

If a user logins on the web page outside Unity content. Is it safe to pass the token through js to Unity? How can that be best handled when login outside Unity?

old mural
old mural
granite rose
#

Hi guys I have a question about the network animator. I'm encountering this error:

[Netcode] [DestinationState To Transition Info] Layer (0) does not exist!

I tried searching online for a solution, but I couldn't find anything. Do you know how to solve this?

white pine
wanton brook
#

Hello, I am updating to 2022.3 on my Mac. On loading game I am getting a proxy error from Package Manager. Has anyone dealt with this before?

I have been adusting my network proxy settings Manual suggestions yet with no success. Yet I have never dealt proxy settings before and maybe in error some where.

austere yacht
wanton brook
ripe mesa
quick flame
#

Hi, I am planning a game, I would like to ask some questions about multiplayer here :).

I am going to use Netcode for Game Objects, the game will have 1 vs 1 matches and there may be some players spectating the match (think of clash royale).

I am not sure if I should have a dedicated server or one of the players should be the host. If one of the players is the host, is it too much workload for the device to "stream" for the spectating ones? (the device may be a mobile) I would probably limit the spectators to 6 or something like that.

If I use a dedicated server (unity services server), with netcode approach I would need 1 game instance running per 2 players and I don't think this scales too well.

I know this is somehow stupid to ask but is it easier to kind of hack the game if the server is the client? (netcode host)

In clash royale, there is a delay of 1 second when you use a card, I assume this is to make sure the card appears in both devices at the same time, is this easy to do? I assume there is an rpc that sends the client time to the server and the server resends it to the other client but how accurate is it the client server time synchronization? Not sure if I explained myself, sorry.

Are rpc methods tcp and network variables udp or something like that?

Thanks in advance 🙂

ripe mesa
#

Are rpc methods tcp and network variables udp or something like that?
I dont think we can treat them that way but merely,

RPC = Reliable
Variables = also reliable too actually

quick flame
sharp axle
quick flame
quick flame
# ripe mesa quantum is going to be the perfect approach for this

about quantum, it really fits the needs but I feel it is a different game engine almost. The game does use some unity key features at runtime like terrain generation and nav mesh generation, I am not sure how well quantum will integrate with that.

Not sure about this but you must use their servers to use quantum i would say

ripe mesa
quick flame
#

but it is in the way the user interacts

#

there will be like actions you can take, so the input is discrete.

quick flame
sharp axle
quick flame
#

yea, I see, thanks

visual cypress
haughty heart
#

!mute 343032164469702666 3d You've been told already not to bring this up or you will be muted.

raw stormBOT
#

dynoSuccess stinkysteak was muted.

blissful jay
haughty heart
#

They saw the same message

delicate parrot
#
    [ServerRpc]
    public void RollNewSeedServerRpc()
    {
        currentRandomSeed.Value = UnityEngine.Random.Range(0, 1000000);
        GameNetworkManager.AddLog("Setting Seed To: " + currentRandomSeed.Value);

        RollNewSeedClientRpc();
    }

    [ClientRpc]
    public void RollNewSeedClientRpc()
    {
        random = new Random(currentRandomSeed.Value);
    }

With this code, is the order of execution with these network calls consistent? will clients recieve the new networkvariable value before they recieve the clientrpc call?

cedar cloak
dry maple
delicate parrot
#

oh yeah theres def routes i can go about solving it if it doesnt. I'm just new to networking and wasn't sure if it works in a way where like it adds them to a stack in order yknow

dry maple
delicate parrot
#

like i know both these calls will get sent to the clients at a unpredictable amount of time but because of the order im calling them here would #2 ever run before #1 when the client gets these

dry maple
#

But again, not all networking solutions offer what it requires for this to be easily possible.

delicate parrot
#

this is the networking channel in the unity discord 😛

dry maple
delicate parrot
#

that doesnt seem likely at all

dry maple
sharp axle
# delicate parrot that doesnt seem likely at all

I'm one of the mods on the Unity Netcode Discord. The devs do post occasionally. But for legit bugs posting a GitHub issue would be better

To you question though, RPCs are sent in a reliable channel be default so order is guaranteed as long as they are called on the same object. You can change RPCs to unreliable delivery or change the sync rate of network variables in the latest version of NGO 1.9.1

delicate parrot
#

I know how unity order of execution works just nothing too deep about netcode stuff

sharp axle
timber bluff
#

Hi, I just joined the unity discord server and wanted to learn about multiplayer. but there are so many terms i need to learn such as fishnet, netcode for gameobjects and photon. Can anyone wanted to explain to me what are those?

delicate parrot
dry maple
timber bluff
timber bluff
#

ok thank you, i want to learn to build fps game maybe with 16 players, is the tutorial good for it

dry maple
timber bluff
dry maple
timber bluff
#

thank you mr karrar

dry maple
#

Lol, Mirror is the most used networking solution for Unity.

old mural
#

<@&502884371011731486> Flagging @lunar leaf as a possible guerilla marketing account for fishnet - please investigate? Apologizes if I'm wrong. Flagging because I don't like the manipulation of this style of marketing

oak flower
#

!ban 1180838287733182528 Marketing spam

raw stormBOT
#

dynoSuccess carzyckq_52366 was banned.

old mural
#

Thanks for investigating!

timber bluff
#

@old mural whats wrong with fishnet?

#

my friend keeps recommending it to me, maybe I should investigate it

#

what guerilla marketing, my english not good

oak flower
#

No patience for it here.

timber bluff
#

if story is true, i tell my friend

old mural
#

@sharp axle Thank you so much for sharing https://gamenetcode.com/. I've been reading through the articles and watching the talks on that site and they're just so high quality. Still working my way through but have been reading since you shared it about a week or two ago. Just wanted to loop back and share some appreciation.

timber bluff
#

i myself is gay, i cannot accpet homo hater

dry maple
old mural
haughty heart
#

@timber bluff Please don't dredge this up. We're not going to drag their drama here, thanks.

timber bluff
haughty heart
#

You will be kicked from this server if you keep up with it. No, we an inclusive here.

oak flower
grave snow
#

Afternoon, anyone using ai bots with photoncloud for webGl ? I wonder if a websocket could handle e,g, the masterclient controlling lets say 8 ai bots ?

onyx locust
#

(Netcode for gameobjects) I have a network animator, and the transitions arent syncing, when i test in unity the transition is there, when i try with another player it doesnt work

tribal condor
#

Hey guys, i'm developing a counter strike like shooter and wanted to hire someone to develop the guns for the game. What should I be looking for when hiring? let's say 10 guns at Call fo duty quality.

sharp axle
raw stormBOT
finite dove
#

Is this the correcct place to ask about multiplayer services for my game? I have a top down shooter game that I'm looking to add multiplayer to with a simple capability of create match / join lobby with code integration (maybe option to make lobby publicly joinable and show a list to others if thats not too hard)

Not sure if its reasonable to continue using playfab which I'm currently using for user authentication/account tracking, economy, leaderboards, etc. or if I should go with something else like the Unity multiplayer packages which seems simple to implement from what I've seen. Pricing is also a factor. I can't tell what the pricing is like between the options

sharp axle
finite dove
sharp axle
white torrent
#

I'm using NGO. Started to have weird problems with the OnClientConnected callback, after using it for weeks now, it started to give errors. I reinstalled NGO, and now this pops up: Library\PackageCache\com.unity.multiplayer.tools\Adapters\Ngo1\Ngo1Adapter.cs(46,13): error CS0123: No overload for 'OnClientConnected' matches delegate 'Action<NetworkManager, ConnectionEventData>'

Why?

sharp axle
covert gull
#

Why is the property HasAuthority unrecognized on my class which inherits NetworkBehaviour?

covert gull
#

Nevermind, I was looking at the experimental documentation

white torrent
sharp axle
old mural
#

Any tips for a kill cam, like call of duty?

How to record the state changes over time before the kill cam recording? How to handle the real time replay (initial thought: stop rendering other players on the level except for the relevant players for the kill cam performance)?

Make buffer of state changes for 5 second kill cam, and allow replay when a player dies?

Thanks for help. Just trying to wrap my head around any possible implementation for kill cam.

junior flower
#

Hi, can anyone help me out for this HalfVector3 not being synchronized over the network.

Here`s the script :-

void FixedUpdate()
{
    if (!IsOwner) return;

    float h = Input.GetAxisRaw("Horizontal");
    float v = Input.GetAxisRaw("Vertical");
    Vector3 move = new Vector3(h, 0, v).normalized;

    controller.Move(move * 6f * Time.deltaTime);

    Vector3 full = transform.position;
    HalfVector3 half = new HalfVector3(full);

    MoveServerRpc(half);
}

[ServerRpc]
void MoveServerRpc(HalfVector3 p)
{
    MoveClientRpc(p);
}

[ClientRpc]
void MoveClientRpc(HalfVector3 p)
{
    if (IsOwner) return;

    transform.position = p.ToVector3();
}
dry maple
# old mural Any tips for a kill cam, like call of duty? How to record the state changes ove...

This will be much easier and effortless if you don't depend on any RPCs for how players are rendered in the client.

So basically you make it so that the entire logic state needed to render characters is contained in networked state (network variables), and events are just reactions to state changes, using On Changed, if it exists in your networking solution of choice.

So that you can simply reset the players and replay them from your buffer.

Potential issues: if the networking system you use does not ensure all network variables are synced together (for a certain behavior, at least), then you might experience desync issues that could ruin the visuals of the character. Like a character being stuck in a certain pose, for example. It depends on the specific logic though.

mint ether
#

Hello! I'm very new to Unity and learning about the UnityAethentication service
I followed the guide https://www.youtube.com/watch?v=XVqYIFcjhLE and was successfully able to login
However, I am unable to write the Sign-out and make it work, every time I try to sign in again after Signed Out it responds with:

PlayerAccountsException: Player is already signed in.
Unity.Services.Authentication.PlayerAccounts.PlayerAccountServiceInternal.StartSignInAsync (System.Boolean isSigningUp) (at ./Library/PackageCache/com.unity.services.authentication@3.3.1/Player Accounts/Runtime/PlayerAccountServiceInternal.cs:60)
Habillage.AuthenticationUnityPlayerAccountsControl.InitSignIn () (at Assets/Scripts/Authentication/AuthenticationUnityPlayerAccountsControl.cs:43)
Habillage.AuthenticationUI.LoginButtonPressed () (at Assets/Scripts/Authentication/AuthenticationUI.cs:46)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <b11ba2a8fbf24f219f7cc98532a11304>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <c5ed782439084ef1bc2ad85eec89e9fe>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <c5ed782439084ef1bc2ad85eec89e9fe>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <c5ed782439084ef1bc2ad85eec89e9fe>:0)

This is how I write my SignOut Task

public async Task InitSignOut()
{
    try
    {
        AuthenticationService.Instance.SignOut(true);
        AuthenticationService.Instance.ClearSessionToken();
        PlayerPrefs.DeleteAll();
        PlayerPrefs.Save();
        Debug.Log("Signed Out");
        OnSignedOut?.Invoke("Signed Out Completed");
    }
    catch (AuthenticationException ex)
    {
        authenticationUI.ShowMessage(ex.Message, AuthenticationUI.ResponseMessageType.error);
        Debug.LogException(ex);
    }
    catch (RequestFailedException ex)
    {
        authenticationUI.ShowMessage(ex.Message, AuthenticationUI.ResponseMessageType.error);
        Debug.LogException(ex);
    }
}

0:33 - Installing Authentication Package
0:58 - Connect Project
1:14 - Adding Player Accounts to Identity
1:27 - Client ID from Dashboard
1:40 - LoginController script
3:26 - UILogin script
6:40 -Testing
6:55 - Google Login
7:05 - Logged In
7:21 - Exporting to android
8:22 - Testing Android
8:34 - Matching Ids

Edit 5/2/2024

Code used in the ...

▶ Play video
rocky willow
#

Need Help on Consulting

Hi everyone,

This is my first time on this server. Recently, there's been a "community issues" regarding Fishnet community. We have several games in production that use Fishnet, but my Discord account was banned from the Fishnet server.

The reason for the ban was because I asked what was happening within local Fishnet communities. FirstGearGames then asked about the footage of our shipped games. Unfortunately, due to the our B2B games and a non-disclosure agreement (NDA), we couldn't disclose that information.

As a corporation, we are looking for the safest option for both our internal team and our customers. Our recent experience with Fishnet is negative.

As a result, we're currently looking for alternatives to Fishnet. We're aware of Mirror, Coherence, Netick and Normcore, but Which ones do you think we should expore. we're open to other suggestions as well.

PS: We only used Mirror for briefly and other such as Photon PUN, and Netick.

Here're the one of the game specifications:

  • The game is teaching about how to operate a mining site with real-time interactions such as vehicles: trucks, excavator and stockpiles
cedar cloak
#

So I've set up a script to make and handle a websocket communication with an api service

   {
       Debug.Log("WebSocket message received: " + e.Data);

       // Deserialize the JSON data to a BaseMessage object
       BaseMessage baseMessage = JsonConvert.DeserializeObject<BaseMessage>(e.Data);

       // Check the type of the message
       switch (baseMessage.type)
       {
           case "chat_metadata":
               //Debug.Log("Message type received: Chat Data");
               break;
           case "assistant_message":
               Debug.Log("Message type received: Assistant Text");
               HandleAssistantText(e.Data);
               break;
           case "audio_output":
               Debug.Log("Message type received: Assistant Audio");              
               HandleAssistantAudio(e.Data);
               break;
           case "assistant_end":
               Debug.Log("Message type received: Assistant End");
               break;          
           default:
               Debug.LogWarning("Unknown message type received: " + baseMessage.type);
               break;
       }
   }```

It works but the problem is when I call methods from there to process the data I receive, I get this error:

"Exception: UnityEngine.UnityException: FindObjectsOfType can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function."

How can I solve this?
fluid walrus
#

presumably the deserialization is happening on a different thread, were you aware of that?

#

without seeing where you're doing that it's a bit hard to say but either you want to ensure you do it on the main thread, or you need to schedule the processing code to run on the main thread after the thread that's deserializing the data finishes

cedar cloak
#

Here's the code contained in the method that generas the error:

   {
       var message = JsonConvert.DeserializeObject<AudioOutputMessage>(jsonData);
       string base64String = message.data;
       Debug.Log(base64String);    

       SaveText(base64String);
   }```
Is is indeed a deserialization
#

Btw the deserialization of the Json I receive isn't generating any issue

#

The problem are the method I call after, to elaborate that data, such as storing a string or turning that string into an audio file

sharp axle
cedar cloak
#

also keep in mind the true method that generates the error is this one, I forgot to include it cause it was temporarly commented:

    {
        string filePath = System.IO.Path.Combine(Application.persistentDataPath, "clipboardText.txt");
        System.IO.File.WriteAllText(filePath, content);
        Debug.Log("Clipboard text written to: " + filePath);
    }```
#

I have no knowledge on this topic since I've never had this need before

#

I read that I should use something like this:
UnityMainThreadDispatcher.Instance().Enqueue(()
but I'm not quite sure on if it will do the job and if it works at all

old mural
dry maple
# old mural Gotcha. At time of death, have server somehow send over the stream of state chan...

Yea, it can be tricky.

I am currently working on a Rocket League inspired game. The way I'm planning on doing replays is by simply replaying the game in the server and it will simply synchronize to clients.

But for a COD-like killcam, you will want to do this in client-side. So yea, store a histroy buffer for all players. One issue with this is that if you had packet loss while playing the game and other players looked laggy, the replay will also look laggy.

Or, you can make the server handle this per client basis, which will be the most annoying solution.

old mural
# dry maple Yea, it can be tricky. I am currently working on a Rocket League inspired game....

Hmmmmm. HMMMMMmmmm.

What netcode lib you using? Is the state change buffer built into the lib or is it something you’ll have to write yourself?

When player dies, it then makes an RPC call to server to have the server stream state changes from right before kill… is that the gist of your proposed solution? How does one switch from default behavior of SyncVars, which streams live/current delta compressed values from server to clients, to instead stream from history?

dry maple
# old mural Hmmmmm. HMMMMMmmmm. What netcode lib you using? Is the state change buffer buil...

I am using Netick, my networking solution.

Yes, it's built into it, it's a 1.2 second buffer (by default) of the entire networked game state, in the server. But it's meant mainly for delta compressing the entire network state of the game. I have a code gen system that combines the entire networked game state contiguously in memory. So copying it around is costless. But currently there is no API to access the internal buffers, I will expose it soon.

I will also add a Disable Authoritative Updates to my NetworkObject, so I can safely change around objects in the client while ignoring all incoming server states, which is ideal for doing COD-like kill cams. But all that state is already stored in an authoritative buffer. So by simply disabling the option, the object will get synced again. The idea of streaming from histroy is pretty cool, I will think about adding that built-in.

Though, you can still do all of this yourself anyway without the need of internal support. Just do a rolling buffer of a struct of all the needed state to replay the character properly.

I don't know how SyncVars work. But I don't think SyncVars are delta compressed in Mirror or NGO. They simply use the underlying transport reliability option for it (I think), which is not the same thing to what Delta Compression means in game networking.

sharp axle
sharp axle
dry maple
# sharp axle In NGO 1.9.1, Network Variables are using delta compression. Or at least they ar...

They mean instead of sending the whole collection each time an element changes, they will only send the specific changed fields/values.

While delta compression (delta encoding) means delta-encoded serialization, which means you are sending the specific bits of the specific changed fields. And it's usually meant as an operation that acts on the entire game. Which is what's meant by consistent replication.

So in NGO, if you have a network variable of Vector3 type. When it changes, it will be sent in full, so all 3 fields.

While in delta compression, only the specific bits will be sent.

Delta compression is a complex feature that can't just be added in an update/patch. It requires an architecture built from the ground up to support it.

https://en.wikipedia.org/wiki/Delta_encoding

#

Mirror support delta-encoding in their NetworkTransformReliable, but it's not useful because it uses reliable transfer to send the data.

So by adding even a bit of packet loss, you will have huge delay.

old mural
# dry maple I am using [Netick](https://github.com/NetickNetworking/NetickForUnity), my netw...

I stand corrected. I assumed delta compression. Woah, surprised.

In netick, you can switch which “stream” of state is being sent from the server? At some point the state will have to change from LIVE to HISTORIC for that one player; that’s the part that’s kinda tripping me up right now.

I.E. the game server knows the player dies so it’d have to somehow know to send down the different stream of state, but just for that one dead player and only for as long as the kill cam feature is happening. Just curious… how? Feel free to speak in netick.

dry maple
# old mural I stand corrected. I assumed delta compression. Woah, surprised. In netick, you...

Doing it as a client-side only operation is way easier.

But streaming it from the server is tricky. The way I will do this is by making a "kill cam" network behaviour which will have all the state needed to replay the characters. And it's per-client, so if the game has 16 players, you will have 16 kill cam network behaviour. And I will use Interest Management to only replicate each one to its specific target client.

So, in a simple way:


// per-client
public class KillCamState : NetworkBehaviour
{
  [Networked(16)]
  public NetworkArray<CharacterState> Characters => new(16);
}

I will only change Characters in the server. The server can use its own rolling buffer or the internal system buffers to apply data to these arrays. Most likely a custom rolling buffer since we want it to be longer than 5 seconds, and we can only change the internal buffers for the whole game, so it will a lot of useless memory usage. In the client, I will simply apply each state to its player.

public override void NetworkFixedUpdate()
{
  for (int i; i < 16; i++)
    CharactersObjects[i].ApplyState(Characters[i]);
}

Though as I said, you will want to disable incoming server states, so you will enable Disable Authoritative Updates on the players, in the client, during the killcam.

I will not use RPCs for this at all. Because RPCs don't support compression, and I am just against them 90% of the time as they are just the wrong way to sync gameplay.

Thinking about it more, I think this is the most optimal solution. Support for this as a netcode feature is not worth it and will complicate things even more since you might want some things to not replay.

old mural
fringe imp
#

(putting this in netowrking because maybe the other players gamamnager is interferring?

fringe imp
#

sorry i didnt have my coffee yet

#

it was a simple mistake

#

@tame slate dont destroy on load, didnt properly handle the singleton, had an instance in every scene

brittle valley
#

anyway i can use websocket client on android, and connect to a server running on my pc?

sharp axle
zenith pagoda
#

Hey in NGO using the Relay system is there anyway to set a custom JoinCode or do you have to do it through the lobby system?

scarlet latch
#

Hey guys I have a finished game (3rd person shooter PvE) with a narrative storyline and endless wave mode
Realistically, how difficult will it be to implement a seperate PvP mode (multiplayer) aside from rebalancing mechanics

sharp axle
zenith pagoda
sharp axle
zenith pagoda
sharp axle
zenith pagoda
scarlet latch
#

or would this also become affected

sharp axle
ripe mesa
#

Im free 🤟 @blissful jay

umbral knoll
#

Hey, im currently working on a game and just started with netcode so i barely know anything about it.
I got the connection part of the players working but right now im trying to make name tags above the player and im struggling to get it working.

If anyone could point me into the right direction that would be awesome

#

I tried using network variables but i don't quite understand how they work yet

ripe mesa
faint idol
#

I got this error when i call an API ```Curl error 60: Cert verify failed. Certificate is not correctly signed by a trusted CA. UnityTls error code: 7

sharp axle
#

Syncing usernames

faint idol
#

request.certificateHandler = new BypassCertificate();

white torrent
#

I'm trying to port my interaction system from single player to multiplayer. Right now it's basically an interactor script on the player prefab that whenever finds an interactable object runs this code

    private void OnInteract(InputAction.CallbackContext context)
    {

        if (_interactable != null)
        {
            _interactable.Interact(this);
        }
    } 

and then the Interact function of the object runs the code like this

    public bool Interact(Interactor interactor)
    {
        
        Debug.Log("Interacted!");
        this.gameObject.GetComponent<MeshRenderer>().material.color = Color.black;
        DisableInteraction();
        return true;
        
    }

I tried making OnInteract() a ServerRpc and Interact() a ClientRpc but I got numerous errors since the Interactor type is "non-serializable", and even if i removed it, obviously since the code of the OnInteract() function was running on the Server, the _interactable.Interact(this); line would give nullReferenceException. What would be the best solution to this? I'd still like to keep the reference to my interactor

#

i'm using ngo

scarlet latch
sharp axle
white torrent
sharp axle
faint kraken
#

Does anyone know any good tutorials on making multiplayer? I'm making a first person horror game that's going to be single player and multiplayer. Need to know the basics

sharp axle
haughty berry
#

is netcode for gameobjects good solution for adding multiplayer

#

why would i use netcode instead of pun 2 for example

sharp axle
faint kraken
sharp axle
ripe mesa
#

sometimes certain network library wont suit your needs

ripe mesa
#

PUN is good for light games.
NGO is good for coop games

keen plover
#

Hello everyone, I am trying to make Inventory but it doesnt work, I want it that when I pickup an item it will go to the first empty slot and change icon according to item I picked up, I want it to be able to pickup other items while Im holding my item and that other items will be assign to remaining empty slots. And I want it to switch between them with numbers from 1-5 and when I press G on item Im holding it will drop it from hand and inventory. This is Item script thats attached to items:https://hastebin.com/share/ozagayorev.csharp and this is Inventory script attachted to gameobject holding 5 slots(which are 5 ui images): https://hastebin.com/share/uficaziniw.csharp and this is interaction manager script: https://hastebin.com/share/afabehexiq.csharp

#

This is for multiplayer project using PUN

faint kraken
ripe mesa
keen plover
wicked karma
#

I'm trying to do Matchmaking. It does receive tickets but not match

#

Does anybody know more about this who maybe can help me?

keen plover
#

@ripe mesa in the // are it is something that I tried with chatgpt his solution that didnt work

sharp axle
wide flare
#

I have a game that I'm making that works like this. 0 gravity basket ball in 2d basically. I have set up multiplayer but am struggling figuring out how to let everyone interact with the ball (being able to grab and throw it) At the moment I have it so the ball can be grabbed and thrown by the host, and so that everyone else can see the ball but not interact.. Wanting direction as to where I should look, at the moment been trying to serverRpc but not sure if I should keep trying or do something else.. Here's how I spawn it in currently:

        if (Input.GetKeyDown(KeyCode.B))
        {
            SpawnBallServerRpc();
        }




    }

    [ServerRpc]
    void SpawnBallServerRpc()
    {
        Ball = Instantiate(BallPref);
        Ball.GetComponent<NetworkObject>().Spawn(true);
        BallRB = Ball.GetComponent<Rigidbody2D>();
        BallNetworkObject = Ball.GetComponent<NetworkObject>();
        BallNetworkObject.ChangeOwnership(NetworkManager.LocalClientId);
        foundBall = true;
    }```

and some other stuff I've tried implementing

```c#
    [ServerRpc]
    void HoldBallServerRpc(Vector2 handPos)
    {
        BallRB.MovePosition(handPos);
    }

    [ServerRpc]
    void SetBallVelServerRpc(Vector2 vel)
    {
        BallRB.velocity = vel;
    }```

And some other stuff for when I grab the ball

```c#
else if (HoldingOntoBall && foundBall) {
            Debug.Log("Holding");
            // Move the hand to the desired position
            HandRB.MovePosition(towardsPosition);
            //Move the ball via server rpc
            HoldBallServerRpc(HandRB.position);
            // Calculate velocity
            Vector2 velocity = (towardsPosition - BallRB.position) / Time.fixedDeltaTime; 
            Vector2 clampedVelocity = Vector2.ClampMagnitude(velocity, MaxBallVelocity);
            //Set Velocity
            SetBallVelServerRpc(clampedVelocity);```

Let me know if I need to include other important parts of the project I may have over looked. Thanks in advance for at least reading this 🙂
gusty thicket
#

Hey !
I have a question, i create an MMORPG and I was wondering if create an GameObject with all script relative to Player and have a gameobject "Player" with only visual component and controlling script it's not better for control and use all script (Stats of player, level,...) to make it easier to use the scripts together

orchid pendant
#

if i wanted to use steam networking do i have to pay them?

fringe imp
#
public async void CreateRelay()
{

    if (IsServer) return;
 ... Other code to start relay

i dont want players to be able to start relay if already connected. Server is getting shut down but it seems the game still thinks im server? Creating game works first time but then after shutting server down and trying again it still thinks im server

tame slate
fringe imp
# tame slate How are you creating a game? How are you shutting it down?
 public async void CreateRelay()
 {       
     OpenHostMenu();
     await UnityServices.InitializeAsync();

     if (!AuthenticationService.Instance.IsSignedIn)
     {
         await AuthenticationService.Instance.SignInAnonymouslyAsync();
         Debug.Log("You Signed In" + AuthenticationService.Instance.PlayerId);
     }

     try
     {
         Allocation allocation = await RelayService.Instance.CreateAllocationAsync(4);
         generatedRoomCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
         NetworkManager.Singleton.GetComponent<UnityTransport>().SetHostRelayData(allocation.RelayServer.IpV4, (ushort)allocation.RelayServer.Port, allocation.AllocationIdBytes, allocation.Key, allocation.ConnectionData);
         GameManager.instance.StartHost();
         RoomCodeFieldBox roomBox = FindAnyObjectByType<RoomCodeFieldBox>();
         if (roomBox != null)
         {
             roomBox.ApplyRoomCodeToDisplay();
         }
         hostBackButton.interactable = true;
     }
     catch (RelayServiceException e)
     {
         Debug.Log(e);
     }
 }
 public void ShutDownServer()
 {
     OnServerDisconnectCallback(OwnerClientId);
     NetworkManager.Singleton.Shutdown();
     MenusManager mm = FindAnyObjectByType<MenusManager>();
     if (mm != null)
     {
         mm.CloseAllMenuPanelsAndOpenMM();
     }
 }```
tame slate
#

Nothing looks out of the ordinary to me.

#

Do you switch scenes or anything after Shutdown?

fringe imp
tame slate
#

I'd probably just try destroying the NetworkManager and making a new one.

sharp axle
tame slate
#

You can poll NetworkManager.ShutdownInProgress to know when it's finished.

subtle bloom
#

Hey!
I am working on a multiplayer game for the first time, and I am wondering how you can get a well working UI setup for multiple players?

I have problems with them either not getting the UIs properly for each, or having a synced UI?
How can I have a script where I can modify a players UI seperately for each players?`

I am using the Mirror package for the multiplayer!

tame slate
subtle bloom
subtle bloom
tame slate
#

What do you need to be different?

#

(between clients)

subtle bloom
#

Nothing really...
Would I just do like I would do in a singleplayer game?

I am trying to make like a TAB menu to see all players if that makes sense lol

tame slate
#

Right

#

You'd probably want every client using the same UI

charred musk
#

is this the channel for multiplayer and stuff

tame slate
#

and just use a SyncVar for their names

tame slate
#

basically all you need to have set up for values like a player's name to be synced to all clients

subtle bloom
#

( I deadass didn't know about TargetRPC, and stuff finally started appearing 🙏 )

Thank you, I'll see what I can cook up now 🔥

tame slate
#

That's why you want to use SyncVars with hooks most of the time

zealous seal
#

What to do if when I enter the lobby the PhotonView is mine but when another player enters it is no longer mine ?? (both from the same computer)

cinder beacon
#

How does Input system works with Unity netcode for gameobjects ? I am at the beggining of my investigation. I have a fully working local coop game that instantiate prefabs on player join. But now it seems i also have to instantiate prefab when they join by network. How does people mix these 2 packages together ?

sharp axle
solemn zephyr
#

I'm using Netcode and I have a problem with RPCs, I have this RPC:

[Rpc(SendTo.NotMe)]
public void EndPlatformPlayersCallRpc() {
    GetComponent<Rigidbody>().position = new Vector3(BASE_X_SPAWN, BASE_Y_SPAWN, BASE_Z_SPAWN);
}

And I'm calling it like this:

public void EndPlatform(bool callOthers) {
    // [...]
    if (callOthers) { EndPlatformPlayersCallRpc(); }
    // [...]
}

I have a spawn platform where everyone spawns and an ending platform, beneath the starting platform, and when someone arrives to the ending platform, EndPlatform(true) is called, and it calls EndPlatformPlayersCallRpc which does stuff but primarily should teleport everyone on the starting platform, but it doesn't work for some reason, it only works for the person that has called EndPlatform(true)

Any idea why it happens and how to solve it ? (please ping me for responses)

mortal pecan
#

Hello!
I'm testing basic networking for my game and connecting to another machine using Hamachi.
Whenever the other part tries connecting as Client, this error gets thrown
"Cannot start client while an instance is already running" even when no other instances are running.
What could be the cause of this?
(Host/Client setup)

sharp axle
keen yarrow
#

hi!

solemn zephyr
#

That's the first thing I tried but I found nothing

keen yarrow
#

i'm trying to do some uga booga level networking, i just want to send a object from one PC to another inside the same LAN in unity, how would i do that?

keen yarrow
sharp axle
# solemn zephyr How would I do that ?

You can loop though all the Connected clients dictionary on the server
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/#finding-playerobjects

A NetworkObject is a GameObject with a NetworkObject component and at least one NetworkBehaviour component, which enables the GameObject to respond to and interact with netcode. NetworkObjects are session-mode agnostic and used in both client-server and distributed authority contexts.

solemn zephyr
#

oh, thanks

#

I'll try it tomorrow, if it doesn't work or I need more help would you be ok with me pinging you ?

sharp axle
keen yarrow
#

That's the same for UDP i supose

sharp axle
solemn zephyr
#

thanks

keen yarrow
#

thx

ornate zinc
#

!code

raw stormBOT
ornate zinc
#

Hey everyone. I am getting this error sometimes, when using Nakama and sending Rpc Calls. https://paste.ofcode.org/kYbEDCUs2Q5pmv6Ptvmb4M
From my knowledge, there seems to be something wrong with the returned value of the server while executing? Is there anything I can do to prevent or fallback. Simple try catch did not work, because it does not break to execute but meanwhile it is awaiting the call I guess.

pearl girder
#

Working with Netcode For Entities, I'd like to handle server dc's nicer, but following the example's when the server shutsdown the client obviously stops getting updates, but then just kind of hangs or crashes after it timesout. I'd like to be able to handle that and load the player back to our pre-login scene and clean up their entities.

Is there any good examples of this? I haven't seen any in the docs/samples yet.

weak plinth
#

One message removed from a suspended account.

weak plinth
#

One message removed from a suspended account.

#

One message removed from a suspended account.

pearl girder
#

i'd start with some null checks, don't see a single one

weak plinth
pearl girder
#

every reference, it's basic defensive programming.

example:


            string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);```

vs 

```Allocation allocation = await RelayService.Instance.CreateAllocationAsync(7);

if( allocation != null) {
            string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
}```
#

Even RelayService.Instance can be null

weak plinth
#

One message removed from a suspended account.

pearl girder
#

that will help you identify yes, but keep in mind, depending on what platform you are on, it's also possible for things to become unexpectedly null.

#

For example: some mobile platforms will reclaim memory if they are running low and that can hit your references

#

to be safe you generally want to always check if a reference is null before you access any methods or members on it

#

think any time you use a dot to access a member, if the thing on the left side could be null you'll get an exception

#

somethings will just crash and you won't get an exception

#

but especially with asynchronous code, the code is being executed, and then paused, and the CPU is then executing other things before coming back to that code, the state of memory can change during that time

solemn zephyr
#

@sharp axle It half works, now when the host touches the end platform, only him gets teleported on the start platform, but when it is a client that touches the platform, everything works perfectly

Here's my code:

public void EndPlatform() { EndPlatformServerRpc(); }
[Rpc(SendTo.Everyone)]
public void EndPlatformServerRpc() {
    if (!IsServer) {
        round++;

        if (round > ROUND_THRESHOLD) { LoadSecondPhaseRpc(); }
        else {
            roundText.text = $"{roundTextBase}{round}";

            lifePoints = BASE_LIFE;
            healthText.text = $"{healthTextBase}{lifePoints}";

            rb.transform.position = new Vector3(BASE_X_SPAWN, BASE_Y_SPAWN, BASE_Z_SPAWN);
        }
    }

    foreach (KeyValuePair<ulong, NetworkClient> id_player in NetworkManager.Singleton.ConnectedClients) {
        var po = id_player.Value.PlayerObject;
        var pob = po.GetComponent<BlocCollider>();

        if (pob.round > ROUND_THRESHOLD) { pob.LoadSecondPhaseRpc(); }
        else {
            pob.round++;

            if (pob.round > ROUND_THRESHOLD) { pob.LoadSecondPhaseRpc(); }

            pob.roundText.text = $"{roundTextBase}{pob.round}";

            pob.lifePoints = BASE_LIFE;
            pob.healthText.text = $"{healthTextBase}{pob.lifePoints}";

            po.transform.position = new Vector3(BASE_X_SPAWN, BASE_Y_SPAWN, BASE_Z_SPAWN);
        }
    }
}
#

Where BlocCollider is a component with a script that handles collisions, including the end platform collision (passed 3 rounds, all players should be loading a second phase which basically teleports them on a second map)

solemn zephyr
#

Looks like I've solved my problem, it doesn't work just for the host, so I'll just make it impossible for people to be host, only server or client

tame slate
tame slate
raw stormBOT
faint cedar
#

Hello. In my game, I am having an issue where the client and the host players don’t move at the same speed. My game is 2d and the player moves with rigidbody velocity. How can I fix this?

#

Im guessing the host needs to handle all the movement but im not sure how to send the clients input to the host.

tame slate
#

Are you using Mirror, Netcode for GameObjects, other?

faint cedar
#

netcode

rapid locust
#

Hey y’all! I am making a 3d multiplayer horror game, but I don’t know how to actually add the multiplayer . . . Could I have some help setting it up? DM me if you know! Thanks

PS I’m using the modular first person package

dry maple
#

You need to rewrite large amounts of your game for it to be a multiplayer game.

tame slate
#

There's a sample component you can use to allow each client to handle and sync their own movement to the server.

#

Which I also believe the documentation recommends you add a NetworkRigidbody to

faint cedar
#

Thank you. Ill check it out.

subtle bloom
#

How can I fix that classes loose their data when being networked?
I have a class that stores some information and when I add a [SyncVar] in mirror with a hook, and I listen to that on other clients that are not the host, the data is just empty?

Anyone knows why this is?
Its pretty straight forward:

public class Test
{
    public string Something { get; set; }

    public Test() { }

    public Test(string something)
    {
        Something = something;
    }
}

public class Player : NetworkBehaviour
{
    [SyncVar(hook = nameof(OnTestChanged))]
    public Test test = new();

    public void OnTestChanged(Test oldTest, Test newTest)
    {
        Debug.Log("Something: " + newTest.Something); // Returns nothing on all clients, correctly on host.
    }

    [Command]
    public void CmdSetTest(string something)
    {
        test = new Test(something);
    }
}
orchid pendant
#

hello, im trying to get a random client's gameObject so i can change a variable in their script using unity's relay system how would i go about doing that?

#

for example, in among us a random player is selected to be the imposter

ripe mesa
#
  1. search all object of players, it could be using FindObjectOfType, or you have a custom list for it.
  2. select random
subtle bloom
#

then it worked as intended apparently

sterile zenith
#

Hi there ! I am using Netcode for my coop game, i'm having an issue where my two player prefabs are spawning (The camera in my main editor and my parrallel sync activate) but after 1 or 2 seconds, they both disapear from the scene and I get "No cameras rendering". For the lobby part i followed Dapper Dino tutorial (https://youtu.be/bNCzpKX4frg) and now i'm just trying to make my players actually spawn and stay.

Any idea where the issue might be ?

PS: I know the players are indeed spawning because i also get the audio source problem (to be fixed later ik).

#

Netcode Player Prefab disapearing

silk reef
#

I'm integrating UGS Server Hosting and Matchmaking. It works up until the clients connect to the server via Netcode. It times out with Failed to connect to server. Cant figure out what I'm doing wrong, my Matchplay project is working fine, but my own project doesnt work.

sharp axle
silk reef
ripe mesa
silk reef
ripe mesa
#

instead of jumping to UGS directly

silk reef
ripe mesa
#

but make sure they have NAT open

silk reef
#

seems like theres only so many variables required to connect to a server (ip:port)

sharp axle
silk reef
#

@sharp axle @ripe mesa oh wow, really stupid typo on my part: 🤦‍♂️
var unityTransport = NetworkManager.Singleton.gameObject.AddComponent<UnityTransport>();

ripe mesa
#

the addComponent?

silk reef
#

yeah...

#

i think autocomplete screwed me there lol

#

thanks for the help, sorry about that

exotic fable
#

If I want to make a small co-op game (~4 players) using Steam for relay, what frameworks work well together for doing as much heavy lifting codewise as possible?

dry maple
exotic fable
#

I plan to publish on Steam anyway, so I'd like to take advantage of their free services for Steam games, including relaying, since I'm already buying into the Steam ecosystem.

#

I'm seeing FishNet and Mirror as options, with their own plugins for transport on Steam (FishySteamworks and FizzySteamworks respectively). I'm wondering which of these would be the best option, or if there are other free options that are better or simpler while still being "free" solutions (aside from maybe sponsoring for Github source)

dry maple
# exotic fable I'm seeing FishNet and Mirror as options, with their own plugins for transport o...

There is also Netick. It's the best performing networking solution for Unity (shown by open-source benchmarks), beating paid solutions too. It's exiting beta stage very soon.

It's pretty easy to use, and has a Facepunch transport.

Mirror, NGO, and Fishnet are all derived from the outdated UNET API. Netick uses a modern API that makes building the most complex type of networked games easy. In addition to many other features, it has a feature called sandboxing that makes working with multiplayer games extremally simple since you will never need to build your game or use two editors (or Multiplayer PlayMode), and can start the game and debug it all in the same editor. It's a game changer for quick multiplayer development.

Disclaimer: I am the developer of Netick.

exotic fable
#

Sounds interesting

#

I don't want to buy into a system where I have to pay per user/per match/per GB if free options exist, y'know? 🙂

dry maple
#

Also, the paid solutions are actually not that expensive if you do the actual math, to be fair.

exotic fable
#

Ok, thanks for the info. Some things to mull over. There will definitely be fewer hurdles just going with NGO until I have something that actually works.

dry maple
granite rose
#
public async void StartGame()
    {
        if (currentLobby != null && IsHost())
        {
            try
            {
                print("Start Game");
                // string relayCode = await TestRelay.Instance.CreateRelay(currentLobby.LobbyCode);
                Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxPlayers);
                string relayCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
                print("CODE: " + relayCode);
                RelayServerData relayServerData = new(allocation, "dtls");
                NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData);
                NetworkManager.Singleton.StartHost();
                // startingGameObject.SetActive(false);
                Lobby lobby = await Lobbies.Instance.UpdateLobbyAsync(currentLobby.Id, new UpdateLobbyOptions
                {
                    Data = new Dictionary<string, DataObject>
                    {
                        {"IsGameStarted", new DataObject(DataObject.VisibilityOptions.Member, relayCode)},
                    }
                });
                generateMap.newMapGeneration = true;

                currentLobby = lobby;

            }
            catch (LobbyServiceException e)
            {
                print("Error: " + e.Message);
            }
        }
    }

Hi everyone, could you help me understand why this code works correctly the first time, but if I try to run it again (after leaving the game) it gets stuck on this line?

RelayServerData relayServerData = new(allocation, "dtls");
sharp axle
granite rose
#

nope, nothing

granite rose
stone lagoon
#

Hey,
So im using photon,
And i had a question,
(I already went over the photon documentation, still cant figure it out)

So, players that join the server have a input field,
Where they have to enter a nickname.

Then, in the top left, a textmeshpro text field will be updated with the username that they submitted in the input field.
this works, but its for some reason only visable for the player who added it.
No one else can see this.

Scripts are links bellow,
Could someone help me please ? 🙂

(i already went over pun documentation, and cant figure it out, also after reading the articles about RPC

ornate zinc
teal cedar
#

Fishnet removed from Asset store? Interesting

stiff ridge
# stone lagoon Hey, So im using photon, And i had a question, (I already went over the photon d...

Per Player, there is a NickName field, which is automatically synced within a room / game. Your UI can use the PlayerList of the CurrentRoom to show who is who.
If I recall correctly, the PUN Basics Tutorial shows how to show the NickName per player.
https://dev-doc.photonengine.com/pun/current/demos-and-tutorials/

blissful jay
#

Fishnet removed from Asset store?

stone lagoon
#

The usernames get listed in OnSubscribed

solemn zephyr
#

I have some buttons that once clicked I want to desactivate I want them to disappear and not be visible, but when I do, it doesn't work, here is the code:

public class UIManager : MonoBehaviour {
    [SerializeField] private Button startServerButton;
    [SerializeField] private Button startClientButton;
    [SerializeField] private Button goBackButton;
    [SerializeField] private Image connectionMenuBackground;

    [SerializeField] private TextMeshProUGUI playersInGameText;

    [SerializeField] private Camera connectionMenuCamera;


    private void Awake() { Cursor.visible = true; }

    private void Start() {
        playersInGameText.enabled = false;

        startServerButton.onClick.AddListener(() => {
            if (NetworkManager.Singleton.StartServer()) {
                Debug.Log("Server started...");
            } else { Debug.Log("Server couldn't be started..."); }

            startServerButton.enabled = false;
            startClientButton.enabled = false;
            goBackButton.enabled = false;
            connectionMenuBackground.enabled = false;
            connectionMenuCamera.enabled = false;
            playersInGameText.enabled = true;
        });

        startClientButton.onClick.AddListener(() => {
            if (NetworkManager.Singleton.StartClient()) {
                Debug.Log("Client started...");
            } else { Debug.Log("Client couldn't be started..."); }

            startServerButton.enabled = false;
            startClientButton.enabled = false;
            goBackButton.enabled = false;
            connectionMenuBackground.enabled = false;
            connectionMenuCamera.enabled = false;
            playersInGameText.enabled = true;
        });
    }
}

They just stop functionning, they are not clickable but I still can see them
The background and camera are disabled and not visible, but the buttons still appear for some reason
Any idea how to fix that ? Please ping me if so

tame slate
#

Side note: This specific question technically isn't networking related, so probably best to post questions like this in another channel.

ornate zinc
#

Just for debug reasons, you know, that the notimplemented exception can break your game runtime, right?

junior sapphire
#

Anyone know of a way to refresh the DefaultNetworkPrefabs lists without having to do a Reimport all? My list randomly loses a ref to all the Network Objects, no idea why.

solemn zephyr
oak schooner
#

Hey,
I'm trying to make an UDP client/server.
I can't make the endpoints talk to each other.

The code is running properly and without exceptions as seen on the logs, but there seems to be something weird going on with the listener.
it's not receiving any bytes from the end point which is 0.0.0.0:0

I'm using .NET version 6.0
I have modified the apps firewall settings.

Server

int SERVER_PORT = 11001;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpClient listener = new UdpClient(SERVER_PORT);
Console.WriteLine($"[Server] waiting for broadcast from {ipEndPoint.Address}:{ipEndPoint.Port}");
byte[] bytes = listener.Receive(ref ipEndPoint);
listener.Close();
Console.WriteLine($"received {bytes.Length}(bytes) from {ipEndPoint.Address}");
Console.WriteLine($"MSG: {Encoding.UTF8.GetString(bytes, 0, bytes.Length)}")

Client

int CLIENT_PORT = 11000;
byte[] buffer = Encoding.UTF8.GetBytes("Hello, World!");
IPEndPoint ipEndPoint = new IPEndPoint("192.168.1.255", SERVER_PORT);
UdpClient sender = new UdpClient(CLIENT_PORT);
sender.Connect(ipEndPoint);
Console.WriteLine($"[Client] established endpoint, {ipEndPoint.Address}:{ipEndPoint.Port}");
sender.Send(buffer, buffer.Length);
Console.WriteLine($"[Client] sent {buffer.Length}(bytes) message to {ipEndPoint.Address}:{ipEndPoint.Port}");

Output:

[Server] waiting for broadcast from 0.0.0.0:0
[Client] established endpoint, 192.168.1.255:11001
[Client] sent 13(bytes) message to 192.168.1.255:11001

The server isn't receiving the packet from the client.

oak schooner
ornate zinc
oak schooner
ornate zinc
#

But you are not waiting for anything. You just open and close the listener

#
while (true)
            {
                Console.WriteLine("Waiting for broadcast");
                byte[] bytes = listener.Receive(ref groupEP);

                Console.WriteLine($"Received broadcast from {groupEP} :");
                Console.WriteLine($" {Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
            }
#

this whole part is missing to keep receiving

oak schooner
ornate zinc
#

so why would they put it in a while loop then?

#

To keep listening for the next message?

oak schooner
ornate zinc
#

And so the server ip is the same for you as in the example?

oak schooner
ornate zinc
#

You could try to use 127.0.0.1 if server and client are the same

oak schooner
ornate zinc
#

You sure you got your ports open?

oak schooner
#

I've tried now with random port numbers and still no difference in the result

oak schooner
#

Its something do with .NET

sharp axle
ornate zinc
#

🤔

sharp axle
ornate zinc
#

The docks say, it should block

oak schooner
#

The Receive method is blocking

#

The code is not falling through to the latter Console.WriteLine calls

ornate zinc
#

So you are using .net 6 in VS or something, not really using unity right now, correct?

oak schooner
#

Yeah,
I'm just messing around with UDP code to learn for later use

ornate zinc
#

Let me test this real quick

#

First thing vs tells me is, that the IP should be long, not string

oak schooner
#

IP should be type IPAddress tho

#

maybe thats an overload

ornate zinc
#

So I need to parse the string

oak schooner
#

IPAddress.Parse("127.0.0.1")

#

is what im using

#

server

int SERVER_PORT = 28000;
UdpClient server = new UdpClient(SERVER_PORT);

while(true)
{
  IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, SERVER_PORT);
  byte[] bytes = server.Receive(ref ipEndPoint);
  Console.WriteLine($"[UDP/Server] received message: {Encoding.UTF8.GetString(bytes, 0, bytes.Length)} from {ipEndPoint.Address}:{ipEndPoint.Port}");
}

This script receives when using python

Client

import socket


def client():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    destination = ("127.0.0.1", 28000)

    while True:
        msg = input("message:")
        s.sendto(bytes(msg, "utf-8"), destination)
        print(f"[UDP/Client] sent message: {msg}")

    s.close()


client()
#

Nice got it working for the code I was using previously

#

It had do with how UDP works

#

You can receive from anything specific using it

ornate zinc
#

Hm, also tried it, seems likes oemthings missing in net to make them receive it

oak schooner
#

hmm interesting

#

I wasnt running it in Unity tho

#

Just a basic Visual Studio Environment

ornate zinc
#

Thats why I was testing unity to see if there is any difference. But I guess, based on the .net, it might be a limitiation of the same client sending and receiving or what not

oak schooner
#

good to know thanks for the help

granite rose
#

hi guys, do you know if there's a way to spawn different player prefabs on the network manager? I wanted to do it randomly.
Is there any docs?

sharp axle
# granite rose hi guys, do you know if there's a way to spawn different player prefabs on the n...

You can use .SpawnAsPlayerObject() to create a player object. You can also use Connection Approval
https://docs-multiplayer.unity3d.com/netcode/1.9.1/basics/networkobject/#creating-a-playerobject

Netcode for GameObjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two Netcode components added to a GameObject:

rose pagoda
#

Hey in a current Unity 6 Project using Netcode for Enties, MPPM and the Dedicated Server Package I get this error inside Netcode for Entities: Simulator\MultiplayerPlayModePreferences.cs(122,21): error CS0234: The type or namespace name 'EditorMultiplayerManager' does not exist in the namespace 'Unity.Multiplayer.Editor'

"com.unity.dedicated-server": "1.2.0",
"com.unity.multiplayer.playmode": "1.1.0",
"com.unity.netcode": "1.2.3",

This are the package version. No newer Versions are available in the Package manager and it uses the latest Unity 6 preview build, is there any way to fix that?

gray pond
proven flint
#

Anyone know how to use the anticipated network transform, I'm messing around with NGO and can't find any official docs on this component

sharp axle
ripe mesa
#

he is a mod for unity ngo discord

proven flint
#

ok.................

sharp axle
#

Its easiest to just make the single player connect to local host.

subtle owl
strange stag
#

I want to make a multiplayer game in Unity. What should I use? I used proton PUN before, but it was too laggy for the game
is there any better way?
i thought of steamworks, but it was around $100 for a single project, correct me if i am wrong
unity multiplay was also an option, but i have not used it
could you suggest any option?

sharp axle
stable valve
#

hey everyone, im using photon pun 2 for an arena shooter, and im having some issues with a playerFiredFrom reference that the bullets should have.

#

essentially the Shoot() method sets it, but that only happens on the client that is shooting, the reference isnt updated on network

#

but im not sure how to get it to sync across the game

ripe mesa
#

some netcode may suit some do not

ripe mesa
#

A simple one. Photon quantum is best

#

But its like learning another engine but 1000% worth the investment

strange stag
#

actually i tried this same, but on different laptops

#

and, it was working rather smoothly

#

but i wrote this code like, an year ago

#

so, i am not sure,
i do want to rewrite to whole code....
but i will do that, if that makes a significant difference

#

so, i have no problem in learning any other service provider

#

can i use steamwork, for a game that i might upload on itch.io?

strange stag
ripe mesa
#

Otherwise use photon fusion or quantum

#

All works for your game

strange stag
#

ohk... so i am still with PUN

#

i think i should rewrite the code, because it is very poorly written....

stone lagoon
#

Hey!
Question,

When players connect to my server, and fill in a username,
The username will be added to a TMP_Text field,
This works and display fine for everyone,
But have a problem

Problem

  • When user 1 fills in a username, it gets added to the first field,
  • When user 2 fills in a username, it gets added to the second field, BUT, the second user, (that connected after the first user) is not able to see the text input field of the first user,

So its not displaying the username if the player that was already connected,
Does someone here know how i can make it, that it will show all the changes made to the scene (text fields in the scene) when a new user is connecting?

#

Script of thhis function:

    [PunRPC]
    public void SetNickname(string _name){
        if (chatManager.nickname1Text.text == ""){
            nickname = _name;
            chatManager.nickname1Text.text = nickname;
            chatManager.nickname1GameObject.SetActive(true);

        } else if (chatManager.nickname2Text.text == ""){
            nickname = _name;
            chatManager.nickname2Text.text = nickname;
            chatManager.nickname2GameObject.SetActive(true);
        }
    }
umbral knoll
#

How would i handle a failed connection attempt ? im using the default network manager and tried messing around with

The DisconnectTimeoutMS value of the unitytransport component
and the
OnClientDisconnectCallback of the networkmanager

Doesn't seem to work as intended, doesn't get called or anything

#

i found this but this seems to be outdated

#

that variable doesn't exist

umbral knoll
#

also, is there a way to check and avoid multiple people from hosting at the same time in the same network?

#

or rather if there is a server running on that adress

sharp axle
# umbral knoll also, is there a way to check and avoid multiple people from hosting at the same...
GitHub

Community contributions to Unity Multiplayer Networking products and services. - Unity-Technologies/multiplayer-community-contributions

tame slate
tame slate
#

This guy here had a similar problem and his solution seems okay

pseudo relic
#

I'm not entirely sure how to place cameras in my multiplayer fps game. Like, if the camera is positioned in the head of the player on the client, how would I make bullets come out of the weapon while still being accurate?

dry maple
tame slate
lean rain
#

Hey is Photon 2 PUN in maintenance or it is still working to create some multiplayers for a game ?

oak flower
pseudo relic
pseudo relic
blazing robin
#

Anyone know any good tutorial about how to open a web page throught a WebGL project? I tried this tutorial ( https://www.youtube.com/watch?v=kWxPZLNVxSU ) , but when I click on something this error appears.

In this video, you will see how you can open links in a new tab in a Unity WebGL build. Normally, Application.OpenURL won't work since it's played on the browser. You may had this issue after publishing your game to itch.io

----------| Related Links 🔗 |----------
✏️ Blog Post: https://HypedCloud.com/blog/how-to-open-links-in-unity-webgl-games...

▶ Play video
blazing robin
tame slate
#

Muzzle flash and empty shells are easy to do. Bullet tracers you can just simulate a very fast visual effect that goes from the barrel of the gun to the hitpoint of the bullet. It won’t be 1:1 with the real bullet but it doesn’t really matter because bullets travel so fast and in most games tracers are only seen for a frame or two.

wintry arch
#

Hi, big problem here, I can't build with IL2CPP, the error seem to be linked with Rpcs and NetworkBehavior

#

The error message is in french (Don't know why only the error message) but here it is in english:
"No user-defined conversion operator is available to perform this conversion, or the operator cannot be called."

#

The build work fine with Mono

proud schooner
#

weird I just got a IL support error as well after 45min compile.
Building E:\dev\Unity\MultiplayerTest\MultiPlayerTest\Builds\MultiPlayerTest_Data\Managed\Unity.Collections.LowLevel.ILSupport.dll failed with output:
Copying the file failed: Access is denied.

#

I see a lot of issues when googling it stating its a bug.

proud schooner
#

This collections has to do with Burst compiler, lots of issues with this new burst technology they implemented.

wintry arch
#

I fixed the issue, I updated the NGO Package to 1.9.1 as in 1.8.1 it fixes the bug:
Fixed a compile error when compiling for IL2CPP targets when using the new [Rpc] attribute. (#2824)

proud schooner
#

I updated collections and burst, compiling now but another 35min to go lol to see if that fixes the issue.

tame slate
crude peak
#

yo guys
i have a problem with Netcode
i want to have two different locations as... scenes for example(Main world and Dungeon or Main world and castle Interior), and let one player be inside the dungeon while another player is in the main world
and also let another player get to the same dungeon so main world is empty
and well, how can i make it so the host player "controls" the NPC's/collisions and stuff inside the dungeon while not being inside it(while being on another scene)

#

idk if it's even achievable with netcode, or maybe i'm going in a completely wrong direction rn

tame slate
#

It's possible within Netcode but your main issue is going to be with the performance implications for the Host.

#

You can additively load scenes so the Host is able to run logic whenever needed, but then you're adding performance strain for the host player that isn't present for other clients.

crude peak
#

or distribute the loading to all clients

tame slate
#

Yeah. Probably the best solution.

crude peak
#

but how do i connect the "server" to NavMesh/Colliders and stuff like that

tame slate
crude peak
#

i mean if there is some kind of server, how should it process data from clients and send them data from game

#

like "YOU CANT MOVE HERE CUZ WALL"

sharp axle
tame slate
#

The server will act the same as a Host. There's just no client connected to the same session and thus no player object.

tame slate
# crude peak like "YOU CANT MOVE HERE CUZ WALL"

you can also probably save yourself the trouble of networking stuff like this. If worlds/maps/levels are pretty static in nature, each client can just have the map for the NavMesh and tell itself it can't move any further.

sharp axle
wintry arch
#

Hi, i have this weird error after updating to NGO 1.9.1.
InvalidOperationException: Nullable object must have a value.
System.Nullable`1[T].get_Value () (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0)
Unity.Netcode.NetworkObject.HostCheckForGlobalObjectIdHashOverride () (at

sharp axle
wintry arch
#

@sharp axle How do I pinpoint where is it from?

lean rain
#

Hey im trying to make interract two prefab together, inside the Resources folder so I put them as siblings of a prefab "ball+ui", but when I do .Transform.GetChild(0) and .Transform.GetChild(1) to interract with them, it uses the two prefab that are outside my "ball+ui" it's because photon can only get what is inside the Resources folder, any one would have any idea how to make interact two prefab inside Resources together ?

sharp axle
wintry arch
wintry arch
#

It happen when a client join the game

sharp axle
proud schooner
#

Just an FYO, updated Burst and Collections in the Package manager took care of the IL.Support issue 🙂

wintry arch
#

I will try @sharp axle

#

Not working

proud schooner
#

@crude peak Im aso about to head into the issue with multiple characters in other loaded scenes. I would guess because each player has a NavMeshAgent they should communicate with the server how to path and collisions. Dont think this would really work good as running a Host though.

wintry arch
crude peak
wintry arch
#

Downgrading to 1.8.1 fixed the issue

proud schooner
#

@crude peak Googles Using Netcode for Asymmetric multiplayer with multiple scenes

sharp axle
crude peak
#

so they are not visible from main world

tame slate
#

You can put it wherever but be careful about putting it thousands of units away. You want it as close as possible without being visible.

lean rain
#

Hi again, if I Instantiate with Photon a prefab containing 2 prefabs, and I put vanilla Position coords of Unity in the 2 objects will the position of the 2 objects synchonised for 2 players ?

sharp axle
crude peak
#

so well, will probably put each dungeon somewhere between those values

#

and on -1k on Y

#

also since player amount is low, i can have 4 dungeons in total which means i can spawn on like 0 -1000 0, 1000 -1000 0, 1000 -1000 1000 and 0 -1000 1000

#

to make sure they are far away from each other

umbral knoll
#

@sharp axle wanted to mention you since you've seen this code snipped already, i guess.

I wanted to change my code around a bit so i can treat some special case scenarios when connecting. I came to a conlusion when i use the onClientConnectedCallback in Line 82 , i get the errors below when i try connecting as a client

If i leave out that callback it works fine but i need it to continue the code once connected and just have the Connection timeout coroutine as a backup

tame slate
umbral knoll
#

Im really confused, was trying to fix this yesterday too.
If i dont subscribe to that callback, and just load the scene manually after that time period in the Timeout Coroutine , it works

tame slate
#

Why have you elected to do any scene loading if the scene just gets loaded on connection anyway?

umbral knoll
#

It doesn't load on connection without the callback, that's why i need that callback instead of making the player wait even though he's already connected

Forget the callback and the method OnConnectionSuccessfull(ulong obj),

if i just start the coroutine and don't use the onClientConnectedCallback from the network manager and then do the loadscene command inside that coroutine, it works.
For Reference, this is how i had it before ( Loading done after the timeout time has ran out , which is bad because i don't want the player to wait)

private IEnumerator ConnectionTimeout(float timeout, string mode)
    {
        yield return new WaitForSeconds(timeout);

        if (NetworkManager.Singleton.IsConnectedClient)
        {
            Debug.Log($"{mode} connected successfully.");
            SceneManager.LoadScene(sceneToLoad);
            
        }
        else
        {
            
            Debug.Log($"{mode} failed to connect within {timeout} seconds.");
            networkManager.Shutdown();

           
            SceneManager.sceneLoaded -= OnSceneLoaded;
            ConnectionFailed.SetActive(true);

        }

        connectionTimeoutCoroutine = null;
    }
#

This works, but the downside is that it waits given amount of time until it actually checks if you're connected or not

tame slate
umbral knoll
#

didn't want everything cramped into one scene

tame slate
#

If you're going to do that I would make a different coroutine so it doesn't get in the way of your timeout logic.

#
private IEnumerator WaitForValidConnection()
    {
        yield return new WaitForUntil(() => NetworkManager.Singleton.IsConnectedClient);
        SceneManager.LoadScene(sceneToLoad);
    }
#

and if that gives you issues you could try:

private IEnumerator WaitForValidConnection()
    {
        yield return new WaitForUntil(() => NetworkManager.Singleton.IsConnectedClient);
        yield return new WaitForEndOfFrame();
        SceneManager.LoadScene(sceneToLoad);
    }

for some added safety

smoky pilot
#

Hello!

I need fresh ideas to fix a problem I have with the multiplayer of my game. Basically when players load a specific scene, the host generates a map procedurally, which is essentially just empty gameobjects with a specific tag across the network. Then the host calls a ClientRpc, which should tell All clients to generate a tilemap by getting all of those empty objects tagged and generating a tilemap on them. Works great on my machine, and in the editor, but in build versions it seems like spawning NetworkObjects takes longer, and on the client it seems that the clientRpc gets executed too early and the Tilemap doesn't generate, because the tagged gameObjects haven't been spawned yet.

Any idea on how to fix that? I tried with a lot of thing, and I'm still running into tricky issues with performance and the Inherent multiplayer delay.

#

Basically, I would need to detect, on the client side, that all the "spawnpoint" have been instantiated. How could I do that ?

tame slate
smoky pilot
#

But then how can I sync my map, since it is generated randomly?

tame slate
#

Just send the position + tag of each GameObject over the Network. Have each client instantiate the tiles based off that info.

smoky pilot
#

Tbh I have no clue how to implement that

#

This is driving me crazy because I have to send this project by tomorrow notlikethis

tame slate
#

Do you not already have map gen code that randomly picks the position of GameObjects?

smoky pilot
#

Everything works through those spawnpoint, a spawnpoint contains a prefab and instantiates it at runtime if the scene is single player, otherwise it spawns it across the network if it is a multiplayer scene. I first have spawnpoint that spawn room prefabs which contain more spawnPoints for objects like enemys, coins, chests and spawnpoints that do nothing on their own but are tagged and used to generate the Tilemap.

#

Tbh I didn't do the levelGeneration, I've been tasked to adapt it to make a multiplayer version of the game and the architecture is garbage but it's too late to change it

umbral knoll
#

@tame slate you're a lifesaver

tame slate
umbral knoll
#

yeah waituntil was actually a good workaround

#

can't believe i didn't think about it

tame slate
#

It's awesome for Netcode. You almost never want to pick an arbitrary amount of seconds to wait before performing an action based around networking. It's either unsafe or just too long for users.

umbral knoll
#

well now i only really have to handle disconnects, right now i have nothing to handle them, if someone leaves everything breaks, haha

tame slate
smoky pilot
#

What I simply need is to call a function ( the clientRpc which spawns the Tilemap )
when I am sure that all the objects have been properly spawned across the network, and that the clients have received them. If you can help me do that, that'd be amazing.

sharp axle
tame slate
#

I haven't worked with NGO in a while. Is there not a callback for when NetworkObjects are spawned?

smoky pilot
#

Because on the host side I call the clientRpc after spawning everything, it breaks down on the client side because he didn't receive the objects yet.

smoky pilot
#

( callbacks )

#

I could make an ugly wait for seconds on the host before calling the ClientRpc but that's a shitty fix

#

Even for my standards

smoky pilot
tame slate
#

Does the map gen code have some sort of variable that tracks how many objects are spawned?

smoky pilot
#

Not at all, it just checks if the path is correct ( if you can go from the first to the last room ) then it instantiates the rooms which make that path, then fills the rest of the map with random rooms

#

Each object spawned ( the room itself and the objects spawned by the rooms) calls, at start, the function which instantiates a random prefab in their prefab list

#

So for example a room spawnpoint instantiates a random coin, ennemy or idk

#

But a room spawnpoint instantiates a random room

tame slate
#

I mean you're making an instantiation call.. tracking it is as simple as doing objectsSpawned++;

smoky pilot
#

Yeah this is a shitty architecture

smoky pilot
sharp axle
#

Procedural generation

tame slate
#

@sharp axle ty

umbral knoll
#

Is there a way i can work around this error:
NotServerException: ConnectedClientsList should only be accessed on server.

Making a playerlist so i need this list

#

tried doing it like this and it didn't work, am i missing something?

[ServerRpc (RequireOwnership =false)] public IReadOnlyList<NetworkClient> GetConnectedClients()
    {
        if(NetworkManager.Singleton.ConnectedClientsList == null)
        {
            Debug.Log("Connected clients list is null");
            return null;
        }
      
        return NetworkManager.Singleton.ConnectedClientsList;
       
    }
tame slate
#

You’re just returning the Client List on the server

#

You’ll need to send the list back through a ClientRpc if you want clients to have it

umbral knoll
#

i tried that aswell, one second

#
[ServerRpc (RequireOwnership =false)] public void GetConnectedClients()
    {
        if(NetworkManager.Singleton.ConnectedClientsList == null)
        {
            Debug.Log("Connected clients list is null");
            return;
        }
      UpdatePlayerListClientRpc();
        //return NetworkManager.Singleton.ConnectedClientsList;
       
    }
    [ClientRpc] public void UpdatePlayerListClientRpc()
    {
        connectedPlayers = NetworkManager.Singleton.ConnectedClientsList;
    }
#

not sure if this is correct but i tried this

tame slate
#

That wouldn’t work, no

umbral knoll
#

enlighten me

tame slate
#

You’re not sending anything with the RPC, you’re sending a void message to tell all clients to access the list

#

Which is not allowed

#

Usually just easiest to make your own player list

#

You just tell a script on your player object to store itself in the list on Start()

umbral knoll
umbral knoll
tame slate
#
void MyRpcInvoker()
{
    MyRpcWithReturnValueRequestServerRpc(Random.Range(0f, 100f), Random.Range(0f, 100f));
}

[Rpc(SendTo.Server)]
void MyRpcWithReturnValueRequestServerRpc(float x, float y)
{
    MyRpcWithReturnValueResponseClientRpc(x * y);
}

[Rpc(SendTo.ClientsAndHost)]
void MyRpcWithReturnValueResponseClientRpc(float result)
{
    Debug.LogFormat("The final result was {0}!", result);
}
#

That’s usually how you “return” values with RPCs

lean rain
smoky pilot
#

Ahah

lean rain
smoky pilot
#

Nop

#

NGO

lean rain
#

Rahhh

smoky pilot
#

NGO + relay + lobby

#

Our multiplayer is basically holding by a thread it's amazing it's even working in the first place

lean rain
#

Guys is it possible to synchronize with photon Animations when we do Invoke to activate them ? PhotonAnimationView only propose parameters from the animator

smoky pilot
#

If it works like NGO, you have to call a special method to sync that kind of animation

umbral knoll
tame slate
umbral knoll
#

yes

#

since i can't use connectedClients apparently

tame slate
#

You could sync it if you wanted to yeah, but it’s not necessary

#

Each client can just populate their own list

#

You just have the player script add themselves to the list on Start(), so whenever a client joins and their player objects spawns for all connected clients

#

The objects Start() runs and the script adds itself to the list

umbral knoll
#

from a client

tame slate
#

Not sure what you mean

umbral knoll
#

well you said the client should populate the list himself

#

oh wait actually nvm

#

i dont need their networkclient

tame slate
#

I would just store the player script or the NetworkObject

#

Whatever needs to be accessed most frequently

smoky pilot
#

Guys, how can I make it so that when the host leaves, the client detects it and simply loads another scene? The callback on client disconnected doesn't seem to work like I want to

#

What I tried doing was adding a script to the NetworkManager which subscribes it to the event, and calls a function that calls networkManager.shutdown, loads another scene, then destroys the network Manager

tame slate
#

What code do you run when the host “leaves”

smoky pilot
#

Seems like the event isn't triggered

#

The NetworkManager isn't destroyed

#

The function doesn't seem to be called client side

tame slate
#

No I’m asking what code you call when you’re leaving as the Host

smoky pilot
#

Shutdown

#

Then the host destroys it's own NetworkManager

tame slate
#

And a connected Client doesn’t get OnClientDisconnectedCallback invoked?

smoky pilot
#

Doesn't seem like it no

tame slate
#

I’d try OnClientStopped then

#

OnClientDisconnectCallback may just be invoked for proper disconnections. I’d guess OnClientStopped invokes no matter what when a clients connection is terminated

smoky pilot
#
        NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback();
        NetworkManager.Singleton.OnClientStopped += OnClientStoppedCallback();
    }

    System.Action<ulong> OnClientDisconnectCallback()
    {
        NetworkManager.Singleton.Shutdown();
        Destroy(NetworkManager.Singleton.gameObject);
        return null;
    }
    System.Action<bool>OnClientStoppedCallback()
    {
        NetworkManager.Singleton.Shutdown();
        Destroy(NetworkManager.Singleton.gameObject);
        return null;
    }```

i'll try that
#

nop, doesnt work either

#

weird

tame slate
#

You can also just manually disconnect any connected clients before calling Shutdown on the Host

#

That should invoke the callback for sure

smoky pilot
#

Ah yes that would seem easier

smoky pilot
#
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.SceneManagement;

public class NetworkManagerSetup : NetworkBehaviour
{
    private void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }

    void Start(){
        NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback();
        NetworkManager.Singleton.OnClientStopped += OnClientStoppedCallback();
    }

    System.Action<ulong> OnClientDisconnectCallback()
    {
        NetworkManager.Singleton.Shutdown();
        Destroy(NetworkManager.Singleton.gameObject);
        Debug.Log("Event Triggered");
        return null;
    }
    System.Action<bool>OnClientStoppedCallback()
    {
        NetworkManager.Singleton.Shutdown();
        Destroy(NetworkManager.Singleton.gameObject);
        Debug.Log("Event Triggered");
        return null;
    }
}```
I am attaching this script to my NetworkManager, but for some reason it seems like the events never trigger, anybody has an idea why?
#

it should def. be called since i do that if(NetworkManager.Singleton != null) { foreach(var clientId in NetworkManager.Singleton.ConnectedClientsIds) { NetworkManager.Singleton.DisconnectClient(clientId); } NetworkManager.Singleton.Shutdown(); Destroy(NetworkManager.Singleton.gameObject); }

#

immediately upon pressing a button

#

ah, i am not assigning an event but calling the method

#

wtf am i doing lmao

tame slate
#

Your event listeners should be void functions

smoky pilot
#

yeah i found out

#

modified them but it still didnt work

tame slate
#

You also might want to wait a couple seconds after Shutdown() before destroying the network manager

#
private void ShutdownNetworking()
{
  StartCoroutine(ShutdownNetworkingRoutine());
}

private IEnumerator ShutdownNetworkingRoutine()
{
  NetworkManager.Singleton.Shutdown();

  yield return new WaitUntil(() => !NetworkManager.Singleton.ShutdownInProgress);

  Destroy(NetworkManager.Singleton.gameObject);
}
smoky pilot
tame slate
#

I'd think so

smoky pilot
#

wiat, the one who should call that fucntion is the one disconnecting right ?

#

i was about to implement it the other way around

tame slate
#

I mean

#

You'd want to use it for both

smoky pilot
#

hm, fair enough

tame slate
#

One is just called manually, the other is just to ensure proper cleanup when force disconnected

rose pagoda
#

What might be causing my InputEvent.IsSet to be true over multipleframes in a Predicted System, but only on the Client? On the Server in triggers once. Here is the code:

Currently trying to learn Netcode for Entities and obviously not understanding something here righ

rose pagoda
#

ya

#

character works fine, this is unrelated code that is giving me grief

proven flint
#

I'm working on a coop game about completing tasks and defending a train and wondering if I should even bother syncing the train position or find a workaround to move the world around said train, without syncing over the network, and rotating it to match the tracks, the game takes place in a 3D top down perspective so the scenery isn't too important.

Any advice here would be great as I'm really struggling on how to approach my potential solution and can't find many resources on this problem

lean rain
#

Guys im trying to synchronize my animation with Photon, PhotonAnimationView only takes parameters from the animation, but im using animation.Play for each animation, some say on Internet that it also synchronize the scenes but I cant figure it out, any ideas?

umbral knoll
#

@tame slate Same issue with the connectedClients IReadOnly collection, now i'd need a network variable to store their name , no?

[ClientRpc] public void ShowNotificationWindowClientRpc(ulong clientId)
    {
        // get the name of the user that disconnected
        string name = NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject.GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();
        Debug.Log("Client disconnected " + name);
        // get the notification object
        GameObject notification = Instantiate(notificationObject, GameObject.Find("UI").transform);
        // set the text to the name of the user that disconnected
        notification.GetComponent<NotificationUI>().SetText($"{name} has disconnected from the Server.");
    }

I just made the Host Subscribe to onClientDisconnected with this function

#

supposed to show a notification on everyone's screen saying "user has disconnected"

sharp axle
umbral knoll
sharp axle
# umbral knoll <@491598995643301888> Same issue with the connectedClients IReadOnly collection...

You can use the new connection events if you need to know when other clients disconnect
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/connection-events/

When you need to react to connection or disconnection events for yourself or other clients, you can use NetworkManager.OnConnectionEvent as a unified source of information about changes in the network. Connection events are session-mode agnostic and work in both client-server and distributed authority contexts.

umbral knoll
#

OnClientDisconnected works fine for my case , i just need a way to retrieve the network object of the disconnected player

#

So i can get his name and display a leave message on the ui

umbral knoll
#

and Disconnected doesnt

#

i wanna make a local player list like this:

public Dictionary<ulong, string> players = new Dictionary<ulong, string>();
    void Start()
    {
        // get all players in the scene
        GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
        // loop through all players
        foreach (GameObject player in players)
        {
            
            // get the player object
            PlayerObject playerObject = player.GetComponent<PlayerObject>();
            // add the player to the dictionary
            this.players.Add(playerObject.OwnerClientId, playerObject.GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString());
        }

    }
``` gets all players and saves their names and id's locally

I just need a way to handle newly joined players
#

i was figuring sending a client rpc from onClientConnected would work but since it also gets executed on the client it doesnt seem to work

sharp axle
umbral knoll
#

yeah im doing that

tame slate
umbral knoll
#
public override void OnNetworkSpawn()
    {
        if (!IsServer)
        {
            ulong clientId = OwnerClientId;
           
            string name = GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();

            SendUpdateServerRpc(clientId,name);
        }
        if (OwnerClientId == NetworkManager.ServerClientId)
        {
            
            NetworkManager.Singleton.OnClientDisconnectCallback += (clientId) =>
            {
                
                ShowNotificationWindowClientRpc(clientId);
                
            };
        }

        if (!IsOwner)
        {
            enabled = false;
            return;
        }
        // get the maincamera
        Camera mainCamera = Camera.main;
        Camera_Controller controller = mainCamera.GetComponent<Camera_Controller>();
        float zAxis = gameObject.GetComponent<PlayerMovement>().zAxis;
        controller.CustomStart(transform);



        transform.position = new Vector3(transform.position.x, transform.position.y, zAxis);


        if (!IsHost)
        {
            GetComponent<Spawn>().TeleportPlayerToSpawn(gameObject);
        }

    }
    [ServerRpc(RequireOwnership = false)]public void SendUpdateServerRpc(ulong clientId, string name)
    {
        Debug.Log("server rpc");
        UpdatePlayerListClientRpc(clientId,name);
    }
    [ClientRpc] public void UpdatePlayerListClientRpc(ulong clientId, string name)
    {
        // check if this is the new user
        if (clientId == OwnerClientId)
        {
            return;
        }
        Debug.Log("client rpc");
        
        Debug.Log("over if statement");
        // get the name of the user that connected
        
        
        


        PlayerList playerList = GameObject.Find("Core").GetComponent<PlayerList>();
        playerList.players.Add(clientId, name);
        Debug.Log("Client connected " + name);
        Debug.Log("end");

    }

So whenever a client joins i send out a server rpc and then a client rpc so that every client updates their list accordingly, i don't want the rpc to be executed on the user that just joined because the Start script of the Playerlist would already add him to the dictionary, How come it doesn't get past that if statement if (clientId == OwnerClientId)
{
return;
}

umbral knoll
#

So for some reason that statement is true, even though it shouldn't be on other client's

sharp axle
umbral knoll
#

How else could i do it?

sharp axle
umbral knoll
#

it's not the disconnect part that doesn't work, it's the connection part

#

telling all clients to locally add the new player to their player list dictionary

sharp axle
umbral knoll
#

Yes, this is the player object

#

i'll send you the full script

#
using Player;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;


public class PlayerObject : Unity.Netcode.NetworkBehaviour
{
    [SerializeField] public Sprite thumbnail;
    [SerializeField] private GameObject notificationObject;
    public override void OnNetworkSpawn()
    {
        if (!IsServer)
        {
            ulong clientId = OwnerClientId;
           
            string name = GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();

            SendUpdateServerRpc(clientId,name);
        }
        if (OwnerClientId == NetworkManager.ServerClientId)
        {
            
            NetworkManager.Singleton.OnClientDisconnectCallback += (clientId) =>
            {
                
                ShowNotificationWindowClientRpc(clientId);
                
            };
        }

        if (!IsOwner)
        {
            enabled = false;
            return;
        }
        // get the maincamera
        Camera mainCamera = Camera.main;
        Camera_Controller controller = mainCamera.GetComponent<Camera_Controller>();
        float zAxis = gameObject.GetComponent<PlayerMovement>().zAxis;
        controller.CustomStart(transform);



        transform.position = new Vector3(transform.position.x, transform.position.y, zAxis);


        if (!IsHost)
        {
            GetComponent<Spawn>().TeleportPlayerToSpawn(gameObject);
        }

    }
    [ServerRpc(RequireOwnership = false)]public void SendUpdateServerRpc(ulong clientId, string name)
    {
        Debug.Log("server rpc");
        UpdatePlayerListClientRpc(clientId,name);
    }
    [ClientRpc] public void UpdatePlayerListClientRpc(ulong clientId, string name)
    {
        // check if this is the new user
        if (clientId == OwnerClientId)
        {
            return;
        }
        Debug.Log("client rpc");
        
        Debug.Log("over if statement");
        // get the name of the user that connected
        
        
        


        PlayerList playerList = GameObject.Find("Core").GetComponent<PlayerList>();
        playerList.players.Add(clientId, name);
        Debug.Log("Client connected " + name);
        Debug.Log("end");

    }
    [ClientRpc] public void ShowNotificationWindowClientRpc(ulong clientId)
    {
        // get the name of the user that disconnected
        //string name = NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject.GetComponent<DisplayPlayerName>().PlayerName.Value.username.ToString();
        PlayerList playerList = GameObject.Find("Core").GetComponent<PlayerList>();
        string name = playerList.players[clientId];

        playerList.players.Remove(clientId);
        // client cannot access ConnectedClients, use another way to get the name

        Debug.Log("Client disconnected " + name);
        // get the notification object
        GameObject notification = Instantiate(notificationObject, GameObject.Find("UI").transform);
        // set the text to the name of the user that disconnected
        notification.GetComponent<NotificationUI>().SetText($"{name} has disconnected from the Server.");
    }

    
}

tame slate
#

I think you're over complicating the connection logic, if a player object's OnNetworkSpawn is called -> that means they joined

#

so you can just directly add the object to the list in OnNetworkSpawn

sharp axle
#

playerList.players.Add(clientId, name); is what you need in the onNetworkSpawn()

tame slate
#

NetworkObjects and NetworkVariables go a long way, it's always best to think about what synced data you already have access to before trying to add additional networking logic

umbral knoll
#

damn i feel stupid

tame slate
#

Don't lol, player objects are annoying to deal with

#

if you've got 4 players, that's 16 instances to worry about lol

#

and you're doing it all in a single script

#

it's hard to visualize sometimes

weak plinth
#

for some reason netcode will just not work on andriod for me. it works fine when i test it on my pc but when i build a apk file to test it on my phone it just wont work. my phone dose not want to connect as a host or client. anyone got a idea why this might be happning?

umbral knoll
#

My netcode seems to work fine when testing locally but just now i asked a buddy of mine to test it over radmin/hamachi

#

and it seems to behave completely different for him

#

The Stuff that i choose (Name, Player prefab etc) gets selected and properly instantiated

#

but for some reason if he chooses something it just takes all of the settings from my client on my computer

#

could this be an issue with the firewall or something?

#

So our test scenario:
I had 4 instances of my game open, my friend also did,

I can choose my player name and prefab, connect to the server and it will use all my selected stuff
( this works for all of my clients on my own computer)

But whenever my friend tries connecting, it will connect him ( had to allow an inbound rule on the firewall)
but it won't take the stuff he selected, instead ( for some reason) it will just take the name , prefab etc of the last client i connected from my computer

sharp axle
#

netcode will just not work on Android

#

player info syncing

grizzled dome
#

hey guys, while having Netcode for gameobjects v1.6.0 i added it again using add package by name. And got 1.9.1 which I wanted.
Problem is that now my Player prefab is breaking because it doesn't have NetworkObject. When I check then it is there but with a wrong icon and when I remove it and try to add it manually in the inspector by Add Component then there is not Network Obejct (but manager or transform are).
I tried to remove whole package and re-addd it but with no success.
When I leave prefab with this weird "NetworkObject" then when I get back to the prefab it breaks again that it tried to access a script that is missing etc\

tame slate
sharp axle
placid depot
#

websocket works on webgl build?

sharp axle
placid depot
#

Im booking for a solution, o got oit of memory when i tried connect tô the server