#archived-networking
1 messages · Page 18 of 1
if you'd like to see how I implemented idea 2 for clarification sake, here's a CS file where I copy/pasted all the relevant code and didn't include the "using"s or anything else other than what is necessary to understand the way it works. (General code structure critique is welcome, i'm still learning, and i'm in the middle of taking an object oriented programming class this semester to try and fix my ugly self-taught habits)
note that I'm calling furniture "item" here for some reason and I'll probably change it for clarification's sake in the future
in this example I've only implemented the lamp furniture catagory so far
still gotta figure out how tf to do images lmao
Can somone help me to fix my issue with syncing player names
https://pastebin.com/3xebUYpK
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
So, you want to sync mostly positions and some additional data.
For something 'interactable' I would go with a composition approach.
Something like this:
interface IInteractable
{
void Interact();
}
class Lapm : NetworkBehaviour, IInteractable
{
private NetworkVariable<bool> _isOn;
void Awake()
{
_isOn = new NetworkVariable<bool>();
_isOn.OnValueChanged += OnValueChanged;
}
public void Interact()
{
InteractServerRpc();
}
void InteractServerRpc()
{
_isOn.Value = !_isOnValue;
}
void OnValueChanged(bool oldValue, bool newValue)
{
//Turn on/off the lamp
}
}
You can also mix composition and inheritance if you want.
To sync transform just use a Network Transform Component.
Also note, that RPC can be called only from a NetworkBehaviour with NetworkObject attached.
mmm right
yeah thats a good point
interfaces would be useful
this doesnt really solve the root issue unfortunately
but i assume that isnt what u were trying to do lmao
ill definitely use interfaces there though
Sorry, just woke up.
It's 7 in the morning on my end.
Okay. I'll look into it again.
In an hour or so.
no sweat, take your time
so i have this question.. although i havent started implementing it i first wanna know how it could be done.. so i want to display all players on the screen but for every player their character will be in the middle
red as current client and yellow as other clients
(btw rn i havent yet made the characters so ill just be adding the nicknames of characters to these places)
So, we're talking about furniture.
And it will have different behaviors.
Like, lamp will turn on/off, note will show a text/image screen.
Inheritance is used when your objects have similar behavior or/and fields.
For example, a weapon sub-type.
abstract class Weapon()
{
protected int ammo, maxAmmo;
public abstract void Shoot();
}
class AutoWeapon()
{
public override void Shoot(){ //Auto Shoot };
}
In this example weapons share a behavior and fields
If objects have completely different behaviors and nothing in common use composition.
Also, you can mix them if you want.
Usually, when I want to create something interactable, I use composition.
So, a script for a lamp, a note, etc.
Is this a lobby thing?
Can players move in this example?
there will be animations but players wont be able to intentionally move
So, it's some kind of pre start scene.
no its not the lobby, its the game but i need the players to be there to display stuff in the middle
idek what to search in this case
First off all, why your player implement a singleton pattern, if you're making a multiplayer game. That's a multi-player game by the definition.
https://pastebin.com/Xa1gMHrA
You also may need to update nickname on client connect.
One thing that came to my mind.
Spawn players on the server
Also spawn owned player locally
Then move the owned one to the middle
And hide server one for the owner
That way every player can be at the center on their screen and on the side to others.
hmm- im not sure i got everything there, so i spawn the players. after that put the owned player in the middle locally but then what ?
i need the other players to be in the exact same place for everyone(well ofc except for the owned players)(giving it like an uno online structure)
something kinda like this with the players on the left and right of jason(ex.) being the same on his screen and my screen...
I'm trying your segustions right now , And I knew I was going to be removing the singleton pattern because I started this game as an offline game , been doing a lot of refactoring to make it networked
[ServerRpc(RequireOwnership = false)]
private void ShootServerRpc()
{
ShootClientRpc();
}
[ClientRpc]
private void ShootClientRpc()
{
if (!IsHost) return;
Bullet go = Instantiate(bullet, barrel.transform.position, transform.rotation);
go.GetComponent<NetworkObject>().Spawn();
}
im trying to get a bullet game object to spawn for all clients in the relay
but this only spawns it when ran from the hosts client
dosnt do anything on the other clients
without if (!IsHost) return; its the same thing aswell
Because only the server can spawn a network object.
[ServerRpc]
private void ShootServerRpc()
{
var bulletInstance = Instantiate(bullet, barrel.transform.position, transform.rotation);
bulletInstance.GetComponent<NetworkObject>().Spawn()
}
@sand nimbus Oops, forgot to ping.
you can’t do this with networking though?
What exactly?
the same issue happens the gameobject only spawns when the code is ran from hosts client
Does it log any errors?
it logs a warning when the host does it however it will works fine and the warning is [Netcode] Deferred messages were received for a trigger of type OnSpawn with key 4, but that trigger was not received within within 1 second(s).
there are no errors when the ServerRpc function should be ran but once the relay is started a few im just not sure what causes them
Check if you have all of your dynamically spawned prefabs in the Network Prefabs List.
yeah but the Glock prefab and P90 prefab are dynamically spawned there are in the game scene to begin with for now. they will be dynamically spawned eventually
not sure if that makes a difference
Paste your gun code here:
https://hastebin.skyra.pw/
Do you use ParrelSync for testing?
no i just create a build and use the editor
@severe briar any ideas?
Use debug mode in the editor
And search through prefabs (including scene) until you find one with a hash 897548308 and 2913467061
in debug mode where in the prefab would it show the hash code?
GlobalObjectIdHash
i dont think there is any with that id hash
oh my bad. i found them they are the 2 game scene guns
Add them to the network prefab list and test.
Seems to be working a little better still some issues im going try to fix
i think the issue was the scene prefabs I edited some values and there wernt exactly the same as the prefab that was in the network prefab list
thanks for your help
Hello guys !
There is Network for gameObject and network for entities. But If I have some characters as GO firing projectiles as entities. What I have to use to make it multiplayer ? I have to make all character as entities or make projectile as GO ?
ive fixed everything with the weapons and working right now. its just a little delayed on the clients screen is there anything i can do to fix this?
https://gyazo.com/a665d88bd2c9fed0ef4fa64831bda1ce
see in the video the bullet despawns slightly before it collides with the zombie
when on the host it despawn until it visually collides
It's because your weapon is networked.
You can spawn the model/sprite locally
[ServerRpc]
void SpawnWeaponSpriteServerRpc()
{
SpawnWeaponSpriteClientRpc();
}
[ClientRpc]
void SpawnWeaponSpriteClientRpc()
{
Instantiate(...);
}
It's because of the network delay and interpolation.
Client is always behind the server.
Since you destroy the bullet as soon as it collide on the server, it doesn't have time to travel full distance.
I think client prediction might help.
Basically, you spawn a bullet with client authoritative transform.
Move it first locally on the client, then send rpc to the server.
If the difference between client and server is 'too high' you reconcile it.
Reconcile, in this case means moving the bullet position to the server position.
But, I may be wrong on this.
Hello guys. When my friend does alt+f4 and open the game again it says that he's still in a lobby and he can't join them. How can we fix this. Should I close the lobby when I start a relay connection ?
and I see 9 connected lobbies when I start the game. When you quit the app it doesn't leave the lobby
polymorphism
Yes, why not?
In one of my prototypes I've made an Item/Inventory system.
Where the 'Pickupable' was the base class.
And it hold the ownerId.
Is netcode for gameobjects good for a casual game like halo
NGO was designed for coop games in mind.
And halo is a competitive shooter.
Of course you can create a competitive shooter using NGO, but you'll have to write client prediction, rollback systems yourself.
Also, if you want to predict physics you'll have to write/use a custom physics engine, because Unity's physics is not deterministic.
So, my opinion, for something casual you can use whatever you want.
But if you want to create a completive game, better look at Mirror as an alternative.
Especially, because Mirror team has released lag compensation and is going to release a client prediction system later this year.
@severe briar and what about Entities for gameObject for competitive ?
and if I have some characters as GO firing projectiles as entities. What I have to use to make it multiplayer ? I have to make all character as entities ?
I haven't used DOTS that much yet.
I would assume, that EGO is good for a massive multiplayer game, since Unity made a demo with 64 players themselves.
Can't help with this, sorry.
thanks @severe briar
having problems with the clientnetworktransfrom git from unity it wont work when i add it in the giturl in packmanager and all also tried the.json method, any ideas?
i even tried downloading the zip file for it and adding it into the packages in the files but the zip file is corrupt?
Just create a class called 'ClientNetworkTransform'
Inherit from NetworkTransform
Override bool 'OnIsServerAuthoritative' with false
im not really to experienced with scripting im just following a guide and it calls for this package but i can get it some reason
Just do this
public class ClientNetworkTransform : NetworkTransform
{
protected override bool OnIsServerAuthoritative() => false;
}
inside the network manager script?
No, create a new script called 'ClientNetworkTransform'
And use it
im sorry for the dumb questions, i feel like i would have to put that script somewhere. should it be a component of something?
a new component on the networkmanager object?
My advice is to get used with unity first and programming in general, because multiplayer will add new layers of complexity.
Learn some coding basics.
Create/Recreate some simple games/mechanics.
And after that try to make a multiplayer game.
i appreciate the advice, although i already have. ill figure it out, thank you
i got it!
Great, sorry for my reply, as it sounds a bit rude.
I'm just tired and don't want to answer some simple questions.
Glad that you've sorted it out.
no worries, i feel you ive been at this for around 12 hours its 6 am
getting the error Can't add script component 'OwnerNetworkAnimator' because the script class cannot be found when trying to put this script on my prefab. any ideas?
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode.Components;
using UnityEngine;
public class OwnerNetworkAnimator : NetworkAnimator
{
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
Try renaming the file and class
fixed it, just reimported all my porject files and it worked
so this one i tried trouble shooting on my own but my idea didnt work,
ive got a private void UpdateAnimationState() and it controlls the anim for left right and jump, but it also controls if running left or right to flip the prefab in the direction so the animation looks right. buttttt i cant get that to tranfer to client and sync. i tried if (!IsOwner) return; but it didnt work. any ideas?
Paste your code here:
https://hastebin.skyra.pw/
I'll look into it.
okay thank you, pasted it for ya
Paste it, click save and send me a new link back.
oh, sorry first time using that
it's okay
So, it works only on the owner side, right?
Oh, I know, you need to reference the 'OwnerNetworkAnimator' and call its methods to make them sync.
ohh would i still keep the if (!isowner) return; above it or no?
that line wasnt in the one i sent you i can really just try both
Yes, otherwise even non owners (other clients) would be able to control it.
Just change
private Animator animator;
To
private OwnerNetworkAnimator animator;
And it should work.
oh snap okay i went and just added ownernetanim and kept the other one
will try
getting a line error on 86 the name animator does not exist in the current context
maybe you forgot to rename it
'OwnerNetworkAnimator' does not contain a definition for 'SetInteger' and no accessible extension method 'SetInteger' accepting a first argument of type 'OwnerNetworkAnimator' could be found (are you missing a using directive or an assembly reference?)
I can't test it right now
Try
OwnerNetworkAnimator.animator.SetInteger(...);
Or something like that.
In your case it would be
animator.Animator.SetInteger(...);
where would this go up in class or in update
Just replace the old line with this one
okay no errors but still no flip. to google i go...
That's strange, can you send the code again?
https://hastebin.skyra.pw/
It looks fine.
Just checked one of my projects, I use it the same way and it does work.
Does it still work only on the server side?
it works for theclient and host but it doesnt sync from either, aka the client cannot see the host flip and the host cannot see the client flip
i just have bad luck
wait...
would i maybe need to to check the y rotation transform option in the network transform script..
If you want to sync it - yes.
Looks fine
but still no flip
Well, can't help you right now.
Just too tired, so I'm going to sleep, it's 8 pm already.
I'll be online around 7-9 am.
thank you anyways
Are you trying to flip a sprite?
yes across the network
That would have to be done with an RPC or Network Variable. You could also do it locally by grabbing the x velocity and flipping the sprite based on whether is + or -
yes rn i have code for the velocity > or < and if it meets those sets flip to true or false. the flip works on the owner side but it doesn’t translate between the two clients no matter what i tried
are checking the actual velocity or just the local player inputs? The sprites should still be moving on both
{
MovementState state;
if (dirX > 0f)
{
state = MovementState.Running;
sprite.flipX = false;
}
else if (dirX < 0f)
{
state = MovementState.Running;
sprite.flipX = true;
}
else
{
state = MovementState.Idle;
}
if (rb.velocity.y > .0001f)
{
state = MovementState.Jump;
}
else if (rb.velocity.y < -.0001f)
{
state = MovementState.Falling;
}
animator.Animator.SetInteger("state", (int)state);
}```
this is what ive got
where is dirX getting set? It should be getting set to rb.velocity.x
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
and here are these as well ```private float dirX = 0f;
[SerializeField]private float moveSpeed = 7f;
[SerializeField]private float jumpForce = 14f;
Yea. that's your problem. Input is only getting set locally. changer your UpdateAnimationState() to use rb.velocity.x instead of dirX
so just replace wherever there is dirX with that?
just in UpdateAnimationState() yea
still doesnt sync the flip between the two
return; ```
i added tried with and without this and it still doesnt work
i have a client network transform that work with jump run movements and jump fall and run anim and they work but just the sprite flip wont work
are you using Client Network RigidBody?
there is a network rigidbody
but i dont have any option for a client network rigidbody
oh its automatic if you use Client Network Transform
how do i get that?
if its that easy i will cry
wait i have a client network tranform already i read that wrong
yea. you'll need client network Transforma and Network Rigidbody
ive got them
ah crap. for non owners it gets set to kinematic. I think that screws with rb.velocity
lamen terms?
check if your rb.velocity is 0
how? sorry
debug,Log()
yeah but i dont know where. should i put it next to the flipX line?
im about to just give up ive been at this for over 27 hours
i'm under the impression that RPCs, networkvariables and all that don't support sending classes of any type over the network
Introduction
wait i missed the bit bellow that
can you define custom serialization for classes then
i may need to learn how to do that
im trying to read the custom serialization page but i have no idea what it is talking about
this probably stems from a greater issue of not fully understanding serialization
i know what it is but not how it works and how its being used in this case well enough
oh yeah so this isn't particularly helpful then?
it kinda implies you need to be able to convert your data into a format that Unity understands which is only useful if that data can be of any length
actually am I meant to use NetworkObjects
wait no that doesnt make any sense scratch that
using networkobjects just means ill be dealing with networkvariables which have the same limitations as rpcs
okay let me change what im asking, at the moment the only thing I don't know how to do at all is send something like an image over the network using netcode for gameobjects. does anybody know how I can do that?
NGO is not meant for sending fkoles over the network. You would use a CDN or Aws S3 bucket
As evilotaku mentioned, rigidbodies are kinematic on the clients.
But you can get its velocity from the server.
https://hastebin.skyra.pw/ragolujeqo.csharp
i really appreciate this script but it did not work i will try to build off of it and figure it out
Yeah, I didn't test it.
Use Debug.Log in 'OnVelocityChanged'.
yeah idk. its a step back for me, the code stop the animations that used to work now they dont
any tips on how to make the movement between clients more snappy. its snappy and clean on the owner screen but when for the other owner its a little delayed and like slidey if you ge twhat i mean
guys pls help i am using photon network and i am trying to sync the player positions but its so laggy i was wondering how to fix it :
(I am using photon transform view classic and the interpolation set to lerp 1 and the enterpolation disabled and the teleport is disabled)
It's because of the network delay and interpolation.
I think you'll have to write your own network transform with a custom interpolation.
yeahhhh ill just deal with the delay
Also you can implement a client prediction system.
It would move the players locally first.
Then send a server rpc with the input.
Server will move it later (because of the network delay) based on the input.
If difference between the server and the client is 'too high'.
Then reconcile, in your case it would mean - move the player to the server position.
yeah thats a little too deep for me im just trying to make a simple race to the top platform rage game for like max 4 people with a implemented push mechanic
I don't understand what 'push mechanic' stand for.
But, you'll have to dig here anyways, since it's a competitive game.
If you don't, than your game could only be played with the ping of 25 or less.
Also, it's a racing game, you'll need to sync physics.
And it's difficult if you're using a client authoritative movement and don't sync with the server.
Can you send a video?
push mechanic is like i can knock another player back a given amount to knock them back down the map. its really just a simple 2d platformer
ok
Well, I thought that you was talking about some 3d car racing game.
Like Mario cart series.
also i have a question. i cant seem to figure out how to have a camera spawn in with clients and follow.
im using cinemachine
i had it working before i put in networking but since i had to pull the player object out of the heirachy it doesnt snap to a player when they spawn in
You can place it in your prefab and disable for non-owners.
the game is really done almost i just need to implement lobby joining and hosting, fix the camera, and then finish level design
in the video its not lagging to much but when i'm not recording its lags
(i am using the left screen to move and the right one is the syncing the other player)
do i drag the main camera on or the virtual camera or something else
if this helps
I would just have the camera on the player with a cinemachine virtual camera and delete the scene one.
Does photon have some kind of 'OnTickEvent'?
Because, looks like it's either framerate or interpolation issue.
yeah i cant figure that out i can figure out how to add a camera to the prefab that has all the stuff i had on the main camera
dont know
when i move its so smooth but its syncing for the other player laggy
Wdym?
the main camera has all these components if i put a camera component on the prefab i have no way of getting the on it
Yeah, I can see that.
Does your build have framerate (fps) limitation?
i think its vsync
I still don't get it.
Just copy/paste the camera from the scene to the prefab.
You should paste it into prefab hierarchy.
what.
https://docs.unity3d.com/Manual/Hierarchy.html
Open the prefab and paste it here.
If you didn't backup, then no.
Use git next time.
how do i know if i backedup?
Because you know either you did or didn't.
Unity doesn't backup anything by itself.
..dam
holy crap i fixed it ok i will try what you said with the camera
just to be sure i dont mess it up
double click the prefab
and just paste the MainCamera with components in the hierarchy
Sounds right.
it worked thank you so much, making sure to write that down for the future!
new problem... build run the game start as host. camera works and follows me around just fine cool. on another instance i join as client to test the network, the camera then follows the client on both the host game and client game. how do i make it to where the camera only follows the owner of each "game" would i throw a if (!IsOwner) { return; }
into the camera controller script but im not sure that would work because the game is using cinemachine to follow the characters not a cameracontroller script as far as im aware?
Turn off the camera for non owners in 'OnNetworkSpawn' or in 'Start'
public override void OnNetworkSpawn()
{
camera.enabled = IsOwner;
}
that should be in camera controller script right. or the network manager one?
or the client network transofrm script?
nvm dont answer yet i will try on my own first
ok yeah i have no idea
You should reference it first.
[SerializedField] private new Camera camera;
public override void OnNetworkSpawn()
{
camera.enabled = IsOwner;
}
still same error
Make sure to use the variable not the static class.
How do you spawn the player?
while here you can also see i havent fixed the sprite flip over network : )
i do get a console error at the beginning saying the variable camera of PlayerMovement has not been assigned
I would assume, that you're using the 'Player Prefab' field in the Network Manager.
It will spawn the player with the server ownership.
You need to spawn it with the client ownership.
Remove the prefab from the Network Manager, add it to the Network Prefabs list.
Create a spawner script.
Something like this:
void OnNetworkSpawn()
{
SpawnServerRpc();
}
[ServerRpc(RequireOwnership = false)]
void SpawnServerRpc(ServerRpcParams rpcParams = default)
{
var playerInstance = Instantiate(...);
playerInstance.GetComponent<NetworkObject>().SpawnWithOwnership(rpcParams.Receive.SenderClientId);
}
Spawn players using it.
the OnNetworkSpawn() messes with code you gave me earlier
Do this in the same method.
I'm just lazy to type the whole thing.
nothing happens when i press host now
i have a feeling that i didnt name the gameOject right in the Instantiate(...) line
how do i refrence the player prefab there
Create a serialized or public field.
No,
public GameObject player;
My advice is to get used with unity first and programming in general, because multiplayer will add new layers of complexity.
Learn some coding basics.
Create/Recreate some simple games/mechanics.
And after that try to make a multiplayer game.
Unity is confusing
I think this is bug. I have host and client. When host call ThrowServerRpc (function that spawns netcode gameobject and then it does something with it) then it works fine but when client call it then there is error only server can spawn but that function is marked as ServerRpc. What?!
I believe this can happen if the network object you are calling this on has not been spawned for some reason
Well, it's netcode player object who call this func
And the script is on same object
Does anyone know if there's a way I can have multiple clients affecting a networked transform rigidbody at the same time? Currently I know how to make owner and server authorative transform but I'm not sure how to do both at the same time.
Also does anyone know if it's possible to instantiate an object on the client and then get a reference to that object and spawn it on the server that way there is no lag for the client?
Hey
Im using netcode for gameobjects and I have a pretty simple problem.
Im using client side authority for the networktransform by default, but when the player dies I would like it to switch to server authority. I have modified OnIsServerAuthoritative method to return true only when the player is dead, but it doesnt seem to work as expected. I also tried to change CanCommitToTransform on server and client but couldnt get it to work. Thanks!
[ClientRpc]
private void InvokeClientRpc()
{
foreach (var client in NetworkManager.Singleton.ConnectedClients.Values)
{
if (client.PlayerObject != null)
{
MyPlayerScript playerScript = client.PlayerObject.GetComponent<MyPlayerScript>();
if (playerScript != null)
{
playerScript.MyMethod();
}
}
}
}```
Will this work? On each client function mymethod will be called? I can later use this on stuff like red zone is moving!
I think you need a hashmap bro
or try implementing blockchain technology
Using Unity netcode for game objects and i am trying to call a server rpc when i enter a trigger. The rpc works when i call it any other way, for example with get input but when i call it inside of OnTriggerEnter, it only sends the debug.log but deosnt change my position ```// Test Teleport
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "Teleporter")
{
TeleportServerRpc();
}
}
[ServerRpc(RequireOwnership = false)]
void TeleportServerRpc()
{
Debug.Log("Teleported");
TeleportClientRpc();
}
[ClientRpc]
void TeleportClientRpc()
{
transform.position = Vector3.zero;
Debug.Log("CLIENT Test ");
}```
Hey so I am planning to make a vr multiplayer game and I’m wondering what multiplayer service would be the best? I’m looking for a service that is:
- Cheap. I don’t have lots of money maybe like $75-$100 a year so something that’s not super expensive.
- Can hold 100+ ccu and around 2,000 total active users
- Has lots of tutorials. I’m a very visual learner so video tutorials help a lot.
- Is easy to learn. I know that multiplayer is super hard but I’m looking for something on the medium/easy side of multiplayer services.
- Can be scaleable.
I don’t even know if something like this exists but just thought I’d ask and see if you know anything like this or could fit a few of these requirements. Thanks!
I assume that the object you're trying to teleport is networked, aka has a network object component and a network transform component.
If this is the case, then only the server can change its position.
right, thats a lot of extra work but i guess this is the only real scalable way of going about it, thanks for the pointers
Anyone knows where to find manual with all callbacks? Like Onclientconnectedcallback
Netcode for gameobjects
Just read through the source code or get an IDE with the auto complete, I would suggest Rider, since it have a built-in Unity support.
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/develop/com.unity.netcode.gameobjects/Runtime/Core/NetworkManager.cs
So read network manager and network behaviour?
Yeah, and search for 'event Action'.
I am using WebSocketSharp to create websockets and building my game for webGL and encountring this error
Is there any solution for how can I fix this?
or any other way to implement websockets for webgl in unity
using NGO, is there a way to change the owner to the client id on spawn? doesn't look like mines being set right as i have a client rpc that should fire on all players but isn't
You shouldnt need a client rpc for changing ownership, only the server needs to change its ownership to whoever it wants then itll be fine
i know this, and that's what I want to do, make the server change the ownership on join
fully aware that for authortitative/sec reasons the server needs to do this, and what I'm asking for is a pointer on how
Is this for the player prefab?
yes
literally just need a way for the owner id to become the client id when the player connects, thats all, server side
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkobject/#creating-a-playerobject
You can spawn as player object with the ID you want
thanks
I wonder if users cant interact or see directly each other in any way and instead they interact with the map so only map state has to be synced + it has very distinct small sections to be together in (galaxy made out of star systems you can get into) do I even need networking like fishnet for this I already know im gonna use firestore database to store the map since I already used it before. It has realtime listeners to a value change + basic rules to see if user tries to write something what should be possible to him at the moment, thats it basically and I would be covered. On the other hand if I would go with fishnet I could make host itself mini db and only periodically write to the actual db saving tons of writes and host would keep clients synced in same star systems himself through all that rpc stuff + perhaps better control over whether the action of client is legit, thing is im somehow still a noob at networking so idek if fishnet choice wont cause problems midway project whats the move here is my hypothesis correct and learning fishnet is worth it? 
If it's completely asynchronous then you can use whatever serverless framework firebase uses. Unity has Cloud Close that you can use as well
I am trying to build a multiplayer RPG (basically an MMORPG without the first M) with a dedicated game server. And I am having trouble understanding what exactly is Netcode for GameObjects and if it iis able to manage that. Or do I just build a custom server from scratch and connect the unity client to the server with websockets or something. So far all the tutorials and stuff i seen makes it seem like NGO is just for low scale p2p or local servers. I want to have a game server that handles all the game logic, what kind of networking solution do i use?
So a Massively Online Role Playing Game
Instead of a massively multy---
??
massively multiplayer online without the first m is multiplayer online? i want to make a game of that genre it just wont be massive bc im not a millionaire
Can we use websockets in Unity webGL build to send and receive data?
if yes I need assistance
If not then how can I transform data from my node server to Unity
This is part one of the Porting from client-hosted to dedicated server-hosted series.
Hey guys i want to make a networked RTS game, does anyone know of a good asset or solution for this so i don't have to build the rts from scratch with networking in mind?
I planned on using an RTS asset and adapting it for either ngo or fishnet, but an rts asset already set up for networking would be great
why is this not working
in english ""PlayFabClientAPI" does not contain a definition for "PlayFabId""
how can i fix that
You should check the Fishnet discord, maybe someone there got a fish ready rts template for you
Thank u sir
For NGO, how do I handle leaving a game concerning relay/lobby? I am using the Unity Relay and Lobby to connect two players then after the game, they return to the main menu but I don't have anything actually "disconnecting" them, so there is weird stuff happening when trying to connect to a new game.
Hello, how can I disconnect the host and client connections?
The NetworkManager is a required Netcode for GameObjects (Netcode) component that has all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project.
Thank you
Anyone have any suggestions on how I can securely authenticate a client and approve the connection using some sort of access token? I saw in the Unity docs that it's not recommended to send tokens for connection approval using the Unity transport because it's not encrypted
Btw, to add to what I mentioned in the other channel, games would often use the transport layer of their platform. If your game is on Steam, you'd usually use the steam transport layer. These platform specific layers probably provide secure connection as is, though you might want to confirm that in their documentation.@covert gull
You would use Unity Authentication for this
how can i activly update text? when i added ngo it didnt seem to work anymore.
Isn’t Unity authentication specifically for authenticating clients so that they can talk to Unity’s other services like leaderboards and stuff? Or am I mistaken?
Does adding encryption to the Unity transport via certificates cause any performance issues? What would be better, adding transport encryption, or sticking everything in a vnet? My app/game is for a specific customer so we can require them to operate on a vpn if needed
i just have an erro that when the bulle hit the player , the player should be killed in 2 hits BUT the player is dying in 20 hits how can i fix it (i am using photon)
Bullet Script
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class Bullet : MonoBehaviour
{
public float bulletSpeed = 20f;
public int bulletDamage = 50;
public PhotonView photonView;
void Start()
{
Destroy(gameObject, 5f);
}
void OnTriggerEnter2D(Collider2D collision)
{
PlayerHealth health = collision.GetComponent<PlayerHealth>();
if(health != null)
{
health.TakeDamage(bulletDamage);
}
Destroy(gameObject);
}
void Update()
{
if(!photonView.IsMine)
return;
transform.Translate(Vector3.right * bulletSpeed * Time.deltaTime);
}
}
Player Health Script :
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class PlayerHealth : MonoBehaviourPunCallbacks, IPunObservable
{
[Header("Player Health")]
public int maxHealth = 100;
public int currentHealth;
[Header("PhotonView")]
public PhotonView PV;
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(int amount)
{
if (!PV.IsMine)
return;
currentHealth -= amount;
currentHealth = Mathf.Max(currentHealth, 0);
if (currentHealth <= 0)
{
Die();
}
}
void Die()
{
if (PV.IsMine)
{
PhotonNetwork.Destroy(gameObject);
}
}
void OnChangeHealth(int newHealth)
{
currentHealth = newHealth;
}
public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
{
if (stream.IsWriting)
{
stream.SendNext(currentHealth);
}
else
{
currentHealth = (int)stream.ReceiveNext();
}
}
}
anyone got advice for working with scriptabel objects in mirror? Ive got a card game selecting random cards to draw on the serer side (scriptable object variants) but the client side always receives the same card no matter how many you draw, any tips?
You may want to name the error and include the callstack for this.
Not a lot of community members will try to help without any context.
Hello I'm having a problem with photon
It sayis that PhotonTargets doesn't exist
Why?
How do modify this car controller thats multiplayer?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
.
any simple network lib to use in C#? I don't want to use anything like mirror, I'll just need send/receive packet
How does the unity transport encrypt traffic with certificates (when configured to use certificates)? Does it use ECC with ECDSA for every message sent/received? I need to implement encryption for a different transport and I’m wondering if ECDSA will be too slow
there's no such an error, its just the thing that I have sent
I don't see the cause for this. I would add Debug.Log lines logging the parameters and values in the related methods.
Could be that PV is not correct for some cases. As in it has a reference to another object's PV?
The MonoBehaviourPun has a photonView field. Use that where possible.
Mirror (et al) is the simple solution, if you want to send raw data, use a basic socket
Yeah its simple turn based no need more, I ll use riptide
Idk what you think the ‘more’ is that mirror does. You’re just gonna reinvent most of it if you use a ‘lightweight’ solution.
Something like riptide is fine if your sync is exceedingly trivial or infrequent.
But it provides zero convenience and guidance
I already did my project using this but I'm trying to find a untied to unity lib, I found out yesterday riptide was ok for this so I can do a complete project without unity for the server part
mirror is perfect for real time games tho, turn based is fine with simple packet system
what networking solution would you guys recommend for a multiplayer RTS with thousands of units? is there something with not too much overhead?
Netcode for entities
I use mirror now but i have a question about it I get the wrong textures when im connecting with my client
do i need to say something lik ethis you need to sync but how?
Make sure to select the texture on the server and send it to the clients.
is it scalable for 1000's of units moving around at the same time, in a dedicated-server model? do you know much about how it works?
It's a ECS based network solution.
It has a bunch of stuff to optimize the use of network bandwidth.
Personally, I didn't use it that much, because the scale of my games are much much smaller, so I don't get any benefit from using it.
I would suggest learning DOTs first before jumping into its Netcode
Hello. For example, I have a class "Player". He has some data. How will you replicate it? There are two options:
- Lots of network variables
- Make the player class INetworkSerializable.
The second option seems preferable to me because it guarantees that all data will be serialized together, and there will not be a situation where one variable has already been replicated and the other has not yet. But then the question arises: how performant is this for send over the network and what limit would you choose (in bytes), after which the INetworkSerializable class needs to be divided.
Personally, I would use a struct.
About separation, I would do it by meaning or responsibility.
Let's say I have some player data, it contains a score, nickname, ready state, etc.
In this case, it would be more like a lobby data.
Later, I need to save their positions and rotations, that data has a different meaning from the lobby one, so I'll move it to a separate struct, and so on.
I hope you've got the idea.
About the data size.
Your data should be less than (MTU - some overhead), the average MTU is about 1200 bytes.
Hey ,
i have created a unity application witch hits the API using UnityWebRequest now in that request i need to send a token X-CSRF-TOKEN which i get as a response Header of my previous hit
Can anyone help
Okay, im done. I am suffering about this already 3 days. Please help. When host call throw then everything works but when client call it's own throw (each player has own throw) then it says on host logger object to throw is null. Why? I already reference it in throw then I call server rpc throw. ```public void Throw(GameObject objectToThrow)
{
if (!IsOwner)
{
Debug.Log("Throw called by a non-owner client.");
return;
}
if (objectToThrow == null)
{
Debug.Log("objectToThrow is null in Throw method; it may not have been assigned correctly.");
return;
}
Debug.Log("Throw called.");
readyToThrow = false;
this.objectToThrow = objectToThrow;
ThrowServerRpc();
}
[ServerRpc (RequireOwnership = false)]
public void ThrowServerRpc()
{
readyToThrow = false;
//if(!IsOwner) return;
Debug.Log("ThrowServerRpc called on client.");
if (objectToThrow == null)
{
Debug.Log("objectToThrow is null; it may not have been synchronized yet.");
return;
}
GameObject projectile = Instantiate(objectToThrow, attackPoint.position, Quaternion.identity);
NetworkObject networkObject = projectile.GetComponent<NetworkObject>();
if (networkObject != null)
{
networkObject.Spawn(true);
}
Rigidbody projectileRb = projectile.GetComponent<Rigidbody>();
projectileRb.useGravity = true;
Vector3 direction = CalculateThrowDirection();
Vector3 initialVelocity = CalculateInitialVelocity(direction);
projectileRb.velocity = initialVelocity;
StartCoroutine(WaitAndResetThrow());
}```
hey can anyone tell how to access <Set-Cookie> header in WebGl Build ?
can anyone show me how to fix laggy movement in multiplayer I am using Photon Transform View Classic And Here's the options :
Here's the code : https://www.toptal.com/developers/hastebin
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I tried using the default's photon transform view and it turned out good but when player moves he get back then he get synced at the position he moves in
You may need to pass a reference of 'objectToThrow'
[ServerRpc]
public void ThrowServerRpc(NetworkObjectReference objectToThrow)
{
if(objectToThrow.TryGet(out NetworkObject networkObject))
{
//The rest of your code
}
}
Note, the syntax maybe wrong, wrote it from my head.
This must be unity glitch. I cannot solve it. I call function throw where I set Object to throw = object (parameter) then I call ThrowServerRpc that spawns object to throw
Object to throw is game object
It's not in sync with the server.
Send it via NetworkObjectReference, as I stated above.
Oh, thanks! I will try it then
But object to throw is initialised at the beginning, public gameobject object to throw
Then throw set it and then server rpc spawns it
Not for the server, only locally
So that is reason why it doesn't work on client?
On host it works fine
I've already told you the reason.
The server doesn't know about the object to throw, because clients don't tell it about it.
Okay, sorry for interrupting
And this is how calling should look like? ```NetworkObjectReference objectToThrowRef = new NetworkObjectReference(objectToThrow.GetComponent<NetworkObject>());
ThrowServerRpc(objectToThrowRef);```
You don't have to make a new reference but yes. You can just objectToThrow and it will get implicitly converted to a reference. In the serverRPC you can convert it back to an network object. You'll just need to make sure that object to throw has been Spawned before you send it
What?
I need server throw rpc to spawn it
In that case it is impossible to pass?
NetworkObjectReference needs to be of a spawned object. If you are trying to tell the server which object to spawn then you send the index of the network prefab list instead
I understand, ty
NetworkManager.Singleton.NetworkConfig.NetworkPrefabs[prefabIndex];
Does Network for GameObjects have client-side prediction/reconciliation? Can it handle something akin to starcraft's gameplay? Aka low player counts but quite a few AI controlled goobers on the map? Looking for a casual setup here.
@stiff charm
Assets\Scripts\ThrowableScripts\GranadeProjectile.cs(125,73): error CS1061: 'NetworkConfig' does not contain a definition for 'NetworkPrefabs' and no accessible extension method 'NetworkPrefabs' accepting a first argument of type 'NetworkConfig' could be found (are you missing a using directive or an assembly reference?)
don't ping people into your questions. i redirected you here so that someone who might actually be more familiar with whatever networking library you are using can help you. not so that I can help you in here
Oh, okay
guys is anyone here good with photon?
Show the code.
for (int i = 0; i < NetworkManager.Singleton.NetworkConfig.NetworkPrefabs.Count; i++)
{
if (objToCompare == NetworkManager.Singleton.NetworkConfig.NetworkPrefabs[i])
{
return i;
}
}
return -1;
}```
I think it should be
NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs.Count
NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs[i]
From where do you know it? Pls I need sources
I just read the source code + Rider helps a lot.
Oh
In my source code I saw network prefabs though
¯_(ツ)_/¯
NetworkConfig.Prefabs.Prefabs[] is the list
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.6/api/Unity.Netcode.NetworkConfig.html#Unity_Netcode_NetworkConfig_Prefabs
does anyone know how to upload my screenshot image to my server? i have checked my screenshot filepath and it is correct but my image file does not seem to send to my server. ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Text;
using UnityEngine.Networking;
using Cysharp.Threading.Tasks;
namespace ImageStorage
{
public class ImageStorageClient : MonoBehaviour{
UnityWebRequest uwr;
private static readonly string imageStorageUrl = "http://localhost:3000/upload";
IEnumerator PostRequest(string url, string filePath){
byte[] dataToPost = System.IO.File.ReadAllBytes(filePath);
UploadHandlerRaw uhr = new UploadHandlerRaw(dataToPost);
uwr = new UnityWebRequest(url, "POST", new DownloadHandlerBuffer(), uhr);
yield return uwr.SendWebRequest();
}
IEnumerator UploadProgressCoroutine()
{
while (!uwr.isDone)
{
HandleProgress(uwr.uploadProgress);
yield return null;
}
}
void HandleProgress(float currentProgress)
{
print("Upload : " + currentProgress);
}
public void UploadDataFromStringUnityWebrequest(string path)
{
string Url = imageStorageUrl;
uwr = null;
StartCoroutine(PostRequest(Url, path));
StartCoroutine(UploadProgressCoroutine());
}
}
}```
I made a simple netcode project. 2 clients. there is a common object that is spinning at a constant (framerate) speed. however that object is not synced on the two clients? is this to be expected? I figured if I started the rotation once both clients "readied" then it would be in sync. If I use network variables instead it is in-sync, but I was hoping for a more light weight solution
idk for a networking game with cpu enemies it is more common for the server to manage state (position, rotation, and whether shoot) or the client to each manage their own? is the latter even possible without serious desync issues?
There's always will be a delay.
So, to sync it, you need to use NetworkTransform.
Usually, enemies AI is run on the server.
thanks! yeah after experimenting some more that seems like the way to go.
Guys i'm using netcode for entities networked
I have a big 2d array of structs that holds my map data, it's kinda big like 16KB
I want to set it up so that i only send updates to the client when there's a change, rather than constantly sending the whole thing when 1 part of it changes
I can't quite get my head around how to do it with netcode for entities
Do i have to break up the whole array into all the data that makes it up, so it will happen automatically the way i want?
I believe if you make the struct a buffer element only what changes get sent. But you really need to do something to get the total size down. Breaking the map into chunks might help
I'm creating the layout for creating and joining lobbies for my multiplayer game. I assigned the CreateLobby() function to a button, and it works. The only problem is the lobbyCreated callResult won't initiate the OnCreatedLobby() function. I've been stuck on this for hours and don't know what I'm doing wrong.
My code: https://gdl.space/balezugigi.cs
using steamworls.net c# wrapper ^
Quick question: Do scenarios exist where OnNetworkSpawn and OnNetworkDespawn can happen multiple times for the same NetworkBehaviour instance?
It would be nice to know this in advance so I can write my stuff accordingly.
I believe it gets called twice on the host. Once on the host client and once on the host server
🤔
hmm thanks
Hello @everyone
I have a question
I have 256 clients which I have to update in every frame
What is the data size in byte that I can update per client?
Here frame rate is 100 fps, so 1 frame is 10 ms long.
I have 256 clients, so 10ms/256 = 0.04 ms per client
How much data can I transfer to client in 0.04ms?
Am I calculating correctly?
Please help me with the calculation.
Thank you.
Is it related with the VPS 's max network traffic? (I am gonna make a DGS for my game and set it up on a VPS)
Upload speed or Download speed?
Or is it related with max packet size of NetworkManager of NGO?
How should I approach vehicles in my game, which players can enter? What should I do with their NetworkTransforms? Parenting? It has always kind of baffled me.
I need help with photon
My Host Cant see the client
idk what is wrong i just started a series
https://www.youtube.com/watch?v=6YeDL6bmlTE
i had the problem here
Welton shows us how to separate the controls in our multiplayer game so the local player doesn't have control over other clients brohh...
(JOIN OUR DISCORD FOR A DOPE COMMUNITY, INFO, AND HELP: https://discord.gg/vrErfxa)
(CATCH UP ON OUR GITHUB: https://github.com/Kawaiisun/SimpleHostile)
Over the course of the next couple weeks, Welton will b...
Check the inspector for both the host and the client (that's if u are using a clone editor for client) see if there are 2 player objects
no there is only one
Are u using a clone editor?
How are u lauching the game for ur client is what I'm asking
here is the launcher script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
namespace Fps.Game
{
public class Launcher : MonoBehaviourPunCallbacks
{
public void Awake()
{
PhotonNetwork.AutomaticallySyncScene = true;
Connect();
}
public override void OnConnectedToMaster()
{
Join();
base.OnConnectedToMaster();
}
public override void OnJoinedRoom()
{
StartGame();
base.OnJoinedRoom();
}
public override void OnJoinRandomFailed(short returnCode, string message)
{
Creat();
base.OnJoinRandomFailed(returnCode, message);
}
public void Connect()
{
PhotonNetwork.GameVersion = "0.0.0" ;
PhotonNetwork.ConnectUsingSettings();
}
public void Join()
{
PhotonNetwork.JoinRandomRoom();
}
public void Creat()
{
PhotonNetwork.CreateRoom("");
}
public void StartGame()
{
if (PhotonNetwork.CurrentRoom.PlayerCount == 1)
{
PhotonNetwork.LoadLevel(1);
}
}
}
}
Oh ok that's not how I'm working on mine forget it then. I'm using the normal multiplayer services
Hopefully someone helps u
You might have better luck asking on the photon discord server
@burnt talon !code and some debugging tips are pinned in #💻┃code-beginner
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Also don't spam the channel, noone new will see that and you are just annoying the people who already did
sry
I would like to ask one more time!
It's up to you how you want it to handle. There's no one fits all template here. Try different approaches and see what will work for you.
Damn, how to do this? client receives id of client who damaged him. now how can client get transform of that client who damaged him?
okay, I figured it out but this is bad code if there are 100 players. ``` private void RegisterServer(ulong clientId)
{
NetworkFPSController[] networkFPSControllers = FindObjectsOfType<NetworkFPSController>();
foreach (NetworkFPSController fpsController in networkFPSControllers)
{
NetworkObject playerObject = fpsController.gameObject.GetComponent<NetworkObject>();
if (playerObject.OwnerClientId == clientId)
{
Transform positionOfAttacker = fpsController.transform;
if (positionOfAttacker != null)
{
finalattackerposition = positionOfAttacker;
Register(finalattackerposition);
return; // No need to continue searching if found
}
}
}
Debug.LogError("Client with ID " + clientId + " not found.");
}```
Anything better?
So I have been facing this weird issue here. I am not able to connect the build and local Unity Version of the game together as Host/Client. For example, when I connect as Host on the editor and Client on the build, player does spawn in the client but nothing happens in the build window. These error messages are displayed. Funny, cz when I delete Library and obj folders to refresh the project, It works for the first time, after that the same problem comes again.
I am using NetCode btw
I will help you
in unity netcode on the transport one can set Debug Simulator > Packet Delay Ms. I made a test for ping (where client records its local time, does serverrpc, server does clientrpc, and then client compares cur local time with message local time). This value is always 4x the packet delay (even for extreme values of lag like 1 second). Why is this? I would expect it to be 2x packet delay...
If you're using ParrelSync, then the client/clone will have a delay too.
Server - 100 ping
Client - 100 ping
Client -> (100+100 ping) -> Server -> (100+100 ping) -> Client
But I may be wrong here.
thank you! yeah I am using ParrelSync..
So parrelSync has ping 400ms? Client --> server --> client
I think it's more that the simulator is double dipping
Is NGO worth it or is Photon better? what do you guys think
Im biased towards NGO. Photon Fusion seems very good but also very expensive
Can NGO handle 100 shooting players?
i believe there is no hard limit currently, meaning you can have any number of players you want BUT you'll likely run into bandwidth issues right away unless you do some really good custom solution. Even just trying to sync 100 players transforms to all 100 people, 100 * 100 = 10,000 transforms to update per network tick
That's insane. 10000 transforms per network tick?! So my codes must be very optimised and powerful servers?
well if you do it a naive way, all 100 players receiving 100 network transform updates then yea. person 1 gets 100, person 2 gets 100..., person 100 gets 100
100 * 100
🤷♂️ i dont know too much about trying to sync large amounts but you definitely need a custom solution to not sync as much at once. Then again, you really dont see 100 player shooting games often for a good reason
Yeah, like in apex you only see like 5 players max even though there is 64 transform in total
You can definitely optimize by only syncing what's needed (like not updating transform if the players are too far or out of vision), but still there are flaws and this wouldnt be an easy task.
Also if people could easily lag/freeze the whole game by just having a lot of people in one area then it wouldnt be a good experience
NGO seems to be still aiming for smaller player numbers, no matter the genre.
There is the "BR 200" sample for Fusion, which is a Third Person Shooter for up to 200 players. Don't know if I should link to the Asset Store here.
A simpler shooter sample is also coming for Fusion.
But I don't think that I will have 100 players online per fleet. That would be too good
Unity said they will improve it so it can handle fast paced shooters but 🤷
Netcode for Entities is what you would use currently for this
Unity Transport can handle hundreds of connections but you will get cpu bound or bandwidth capped before you reach any theoretical player limit
Damn, another month of converting
Simple, solution just change to Mirror networking
networking techniques such as rollback require a synced timestep between all players. how does one achieve a synced timestep in netcode for game objects? how does everyone start counting ticks at the same time? if the server sends a message telling everyone to start counting ticks, then wouldnt it reach all players at different times due to latency?
The server is authoritative with a set tick rate. The client would be considered ahead of the server which is why it's called client prediction. The clients would then Rollback in time to reconcile any discrepancies.
what is alternative of WebSockets?
I want to create a webGL base game with in game chat option
My idea is working perfectly fine with WebSockets but I cannot use this in webGL.
So, what is alternative of websockets or how can I implement this?
WebSockets specifically are the historically best solution for low overhead data on the browser, but the catch is that you have to do that through the browser to interface with the WebSocket API since browsers don't allow you to freely use system APIs.
You can see an example implementation of a Unity websocket interfacing with a browser here https://github.com/James-Frowen/SimpleWebTransport/tree/master/source/Runtime/Client/Webgl, and you can find something similar in all networking solutions that work with Unity WebGL.
General interaction with browser scripting manual https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
But to answer your question, your alternatives are HTTP and WebRTC.
It depends on your camera orientation. It could be up or down. This a question for #💻┃code-beginner
i got the channel wrong sry
and i got it thx
This is a whole can of worms, what I'm doing to get websocket in webgl is just going through a very simple JavaScript plugin with send and receive functions through websocket.
But you should know unitys .net implemented is straight up missing the websocket library also so making a server with it in unity will also be a pain.
(Actually worse than missing, it's there but the functions don't do anything)
I have this code
using UnityEngine;
using Unity.Netcode;
using UnityEngine.Networking;
public class RandomNumberGenerator : NetworkBehaviour
{
private System.Random randomGenerator = new System.Random();
[SyncVar]
private int randomValue;
// Server initialization
public override void OnStartServer()
{
base.OnStartServer();
GenerateRandomNumber();
}
}
[syncvar] is not working. In visual studio "using UnityEngine.Networking; " is greyed out, even though they use it for syncvar in the docs.
Okk so you are using JavaScript base websockets
That's a great approach I'll try it
This looks like very old Unet code. If you are trying to use Netcode for GameObjects, check he docs here
https://docs-multiplayer.unity3d.com/netcode/current/installation/upgrade_from_UNet/
Use this step-by-step guide to migrate your projects from Unity UNet to Netcode for GameObjects (Netcode). If you need help, contact us in the Unity Multiplayer Networking Discord.
thats also what i assumed. thanks!
hello everybody i have a probleme with websocket how can help me?
There is already one outstanding 'SendAsync' call for this WebSocket instance. ReceiveAsync and SendAsync can be called simultaneously, but at most one outstanding operation for each of them is allowed at the same time
i want to click button and a want sendmessage (active tracking)
and in updatefixe => sendmessage (my postion)
when i put a button to active (tracking camera) => i have got this message (how i can do?)
Hello
i really need help, i am stuck with this error for 2 days
code from Game Manager script
`public override void OnNetworkSpawn(){
base.OnNetworkSpawn();
if(IsServer){
UnityEngine.Debug.Log("isServer true");
NetworkManager.Singleton.SceneManager.OnLoadEventCompleted += AllPlayersJoinedLoaded;
NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnect;
}
}
private void AllPlayersJoinedLoaded(string sceneName, UnityEngine.SceneManagement.LoadSceneMode loadSceneMode, List<ulong> clientsCompleted, List<ulong> clientsTimedOut){
if(!IsServer) return;
SpawnPlayersServerRpc();
gameState.Value = GameState.OnCountDownToStart;
}
[ServerRpc(RequireOwnership = false)]
private void SpawnPlayersServerRpc(){
if(!IsServer) return;
foreach (PlayerData playerData in MultiplayerManager.Instance.networkPlayerDataList) {
UnityEngine.Debug.Log("Spawning player for client with id: " + playerData.clientId);
Transform playerTransform = Instantiate(playerPrefab);
playerTransform.GetComponent<NetworkObject>().SpawnAsPlayerObject(playerData.clientId, true);
}
}`
i dont know why but it is SPAWNING PLAYERS 2 TIMES
You are spawning all players every time another joins. With a 3rd client you'll have 3 sets of player objects
How can i prevent that ?
I did debug.log and found out event is called as many times as many players are there
If 2 players
Event is fired two times
you are calling SpawnPlayersServerRpc(); every time a client loads the scene
So I have a small prototype where host and client player objects try to move a singular ball which is synced in both the host and the client. The Ball is spawned on the host and any/all of the forces that the Host Player object applies are reflected in both host/client. But no forces are being applied by the client on the ball. The function that is responsible for applying the forces is getting called but the logic that applies the force just doesn't work. There is no error, just the ball remains at the same place even when the client player object tries to move it. What am i missing here! The Code for application of force is this :
private void ApplyForce(Vector2 dashDirection)
{
Debug.Log("Force on ball applied");
if (dashDirection == Vector2.left)
{
dashDirection = new Vector2(-1.0f, 1.0f).normalized;
}
else if (dashDirection == Vector2.right)
{
dashDirection = new Vector2(1.0f, 1.0f).normalized;
}
Vector3 bounceForce = dashDirection * forceValue;
_rb.AddForce(bounceForce, ForceMode2D.Force);
}
I want to know why do i get this error message after trying to connect to a server
https://media.discordapp.net/attachments/87465474098483200/1155910621230026833/image.png?width=800&height=427
Only the host can move the ball in that case. So the client would have to send the forces to the host so it can apply them
Im having a problem where consistently in scene placed network objects when switching scenes dont load for clients does anyone know why?
in NGO I have a NetworkVariable<bool> and if it starts false, and the server sets it true, then a client connects, the value is correct but I get no OnValueChanged. Should I be checking in OnNetworkSpawn to make sure my game updates based on the current value?
Hi, I'm looking for some general guidance on what I can google next. I have two devices which communicate with the new Netcode networking. And I currently need to enter the IP address of the server into the client.
How can I automate this? Is Bonjour, for example, something that will work on both Android/MacOs/Windows , or are there other automatic detection techniques that I would be better off investigating?
This is all happening offline, just on a local LAN network.
Ok, I found what looks like a solution for this , if it is relevant to anyone reading this later on search or something, this seems like what I need : https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery
is it possible to use netcode between two different unity projects?
my situation is: I have a main VR application which runs on several headsets and I want an app running on a tablet (in this case uwp) that acts as the server/management station for the VR apps.
having both in the same repo/project seems kinda iffy on a design level, ideas?
should work--VR oculus is essentially an android build when it compiles over
Unity NGO's are still a peer to peer based solution. They architected it that way instead of going for the dedicated server/multi client solution. You can still create a dedicated server build (and code base I think) separate from the clients code base/build, but I'm guessing you'd still have to do silly things like name your methods "ServerRpc" on a server only code base
offering $50 to whoever can help me with a small issue where the direction of my bullet based on mouse position is only being set on the host side and not the client, despite having if(isowner) set when setting the mouse position.
if offering a job is not allowed let me know!
is this netcode? I assume you are doing something to pass the direction of the bullet to the client (netvar, sync transform)?
Yes netcode for gameobjects !
hey i have a strange issue
this is my movement code for my 2d game
private void Movement()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(horizontal, vertical) * speed;
_rigidbody.velocity = movement;
}
the host player can move fine but any other players cannot move however i did some logging and this function is actually running
The network transform component is server authoritative by default.
You can either make it client authoritative by overriding a bool 'IsServerAuthoritative' with false. But that will allow players to cheat.
Or send a server rpc with the input and make the server responsible for moving the player, but it will introduce a delay.
The best approach is to use both.
Create a client authoritative transform component.
Move the player locally.
Send player input to the server and save it in a queue.
Move the player on the server.
If the difference between the server and the client is too 'big', then move the player to the server position.
Actually, it's a bit more complex, than I've written, but hopefully it will give you an idea about how it works.
Upd:
Oh, you're using a rigidbody component...
The unity's physics is not deterministic, so you'll have to write your own physics framework.
It sounds like a lot of work, but it really depends on the complexity of the physics in your game.
Or you can try to sync physics across clients, I've seen that some dude did that using 'Physics.Simulate()'.
I have a question about collision detection
So im making a 2d 1v1 game and im adding grenades that basically work by using Physics2D.OverlapCircleAll and loop over all the results and check if one is a player
How should I do this with client and server Rpc
Where should the collision detection happen?
The grenade should be spawned on the server.
Then the server detects a collision and makes its things ( damage, spawning particles, etc. )
im running into abit of an issue with it im running
ExplosionServerRpc();
[ServerRpc(RequireOwnership = false)]
private void ExplosionServerRpc()
{
Explosion go = Instantiate(explosion, transform.position, Quaternion.identity);
go.GetComponent<NetworkObject>().Spawn();
}
to spawn the explosion on the server
but i cant seem to get the explosion class to run anything
on awake im running
LoggingClientRpc(1);
[ClientRpc]
private void LoggingClientRpc(int num)
{
Debug.Log(num);
}
as a test to see if anything will log but nothing not too sure why
thanks 🙂
here is my whole explosion script. bit of a mess right now
You didn't send the code ^
Does your script inherit 'NetworkBehaviour'?
Should Unity Transport encryption work with certificates created from an intermediate CA?
My bad. https://hastebin.com/share/ofaborihud.csharp
yeah it does habe NetworkBehaviour
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Rpcs would only work inside the 'OnNetworkSpawn' or 'Start' functions.
OnNetworkSpawn is invoked on each NetworkBehaviour associated with a NetworkObject spawned. This is where all netcode related initialization should occur. You can still use Awake and Start to do things like finding components and assigning them to local properties, but if NetworkBehaviour.IsSpawned is false don't expect netcode distinguishing properties (like IsClient, IsServer, IsHost, etc) to be accurate while within the those two methods (Awake and Start). For reference purposes, below is a table of when NetworkBehaviour.OnNetworkSpawn is invoked relative to the NetworkObject type:
https://docs-multiplayer.unity3d.com/netcode/current/basics/networkbehavior/
I may be misunderstanding but move the colliding detection to a override OnNetworkSpawn?
public override void OnNetworkSpawn()
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, radius);
foreach (Collider2D collider in colliders)
{
Character character = collider.GetComponent<Character>();
if (character)
{
float proximity = (transform.position - character.transform.position).magnitude;
float effect = 1 - (proximity / radius);
character.Damage(damage * effect);
}
}
base.OnNetworkSpawn();
}
No, just move all the rpc functions and those that call rpcs to a 'OnNetworkSpawn' function.
I might be being silly, but I cant quite figure it out
Ive tried something like this but no results
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/serverrpc/#serverrpc-ownership-and-serverrpcparams
Introduction
Can anyone help regarding Unity NGO. This don't work when clients are in different devices but connected with same Local Network
I checked Remote connections in Unity transport but still it don't work
Checked Firewalls, it's not blocking it
Make sure that you're using the local ip address.
Yes I am using local ip. But ip changes in different devices
Even tho they connected to same network
I don't get what you mean by saying 'the ip changes'
Like, of course they will have different addresses.
You can display the local ip address.
https://github.com/R1nge/BomberMan/blob/main/Assets/Scripts/LocalIpUI.cs
And set it using an input field.
https://github.com/R1nge/BomberMan/blob/main/Assets/Scripts/ConnectMenu.cs
Yes I tried this also. But it don't work
public void StartHost()
{
NetworkManager.Singleton.StartHost();
ipText.text = "Join IP: " + GetLocalIPAddress();
}
public void StartServer()
{
NetworkManager.Singleton.StartServer();
ipText.text = "Join IP: " + GetLocalIPAddress();
}
public void StartClient()
{
NetworkManager.Singleton.GetComponent<UnityTransport>().ConnectionData.Address = ipTextField.text;
NetworkManager.Singleton.StartClient();
ipText.text = "Join IP: " + ipTextField.text;
}
public string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new System.Exception("No network adapters with an IPv4 address in the system!");
}
I also tried puttin 0.0.0.0 in Address
nothing works
You should host the server using its local ip.
And then clients should enter this ip address to the input field to connect.
Yes. That 192.168.1.4 is my local ip of my pc. I tried entering on my mobilke device but didnt worked
In client it says
[Netcode] StartClient
[Netcode] Initialize
but its not actually connected because player is not spawned
The Host and Client works fine in my pc with different game instances
Check the manifest file it may not have a network access allowed.
I'm trying to learn to develop multiplayer games in Unity, using the project from Binary Lunar's excellent tutorial:
https://www.youtube.com/watch?v=HWPKlpeZUjM
If I simultaneously run a local build on my machine (which happens to be a Linux box) and run the game within the Unity editor, I can create a host in one and a client in the other. They play together happily.
I also made a MacOS build and downloaded it on a separate machine. I can run the game there and create a host.
Strangely, if I then try to create a client from the other machine (either the local Linux build or within the editor), I get this message:
[Netcode] Cannot start Host while an instance is already running
UnityEngine.Debug:LogWarning (object)
Unity.Netcode.NetworkLog:LogWarning (string) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Runtime/Logging/NetworkLog.cs:28)
Unity.Netcode.NetworkManager:CanStart (Unity.Netcode.NetworkManager/StartType) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Runtime/Core/NetworkManager.cs:697)
Unity.Netcode.NetworkManager:StartHost () (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Runtime/Core/NetworkManager.cs:830)
NetworkUI/<>c:<Awake>b__4_0 () (at Assets/Scripts/NetworkUI.cs:20)
UnityEngine.EventSystems.EventSystem:Update () (at ./Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:530)
This only happens if there is an instance running on the Mac!
Of course, the only time you would want to create a client is if there is another instance (a host) running. It's as if the game running on the Mac and the one running in the Unity editor think they're the same program, and therefore refuse to make a "second" network connection.
What can I do about this?
In this comprehensive tutorial, you will learn the basics of Netcode for Gameobjects to start building your multiplayer game.
Download Project Files (Patrons only): https://www.patreon.com/BinaryLunar
Netcode for Game Object Documentaions https://docs-multiplayer.unity3d.com/netcode/current/about/index.html
(This video is Sponsored by Unity)
00...
sorry im still a little confused
this is what i current have https://hastebin.com/share/usinisopey.csharp
hey so i'm currently learning how to make a multiplayer game, which includes the basics like making lobbies and joining them etc. My question is, how could I make it so there could be an online market system where players can list items to buy and sell? my current knowledge only allows me to make it so players are able to create and join lobbies with synced movements and animations etc.
It's okay.
So, I wrote that RPCs (ServerRpc, ClientRpc) should be called inside a OnNetworkSpawn function.
Let's say you have a spawn function
[ServerRpc]
void SpawnServerRpc()
{
//Spawn on the server
}
void Spawn()
{
SpawnServerRpc();
}
In order for it to work, it should be called inside a OnNetworkSpawn function.
public override void OnNetworkSpawn()
{
Spawn();
}
Or you can call SpawnServerRpc directly
public override void OnNetworkSpawn()
{
SpawnServerRpc();
}
Thanks I found the main issue it was todo with the way it was being spawn on the server
One new issue is with adding a force to a rigidbody on the server
Here is the method that addsforce
public void Throw(Vector2 position)
{
Vector2 direction = position - (Vector2)transform.position;
direction = direction.normalized;
_rigidbody.AddForce(direction * force, ForceMode2D.Impulse);
}
and im calling it here
[ServerRpc]
private void GrenadeServerRpc(Vector2 position)
{
Grenade go = Instantiate(grenade, transform.position, transform.rotation);
go.GetComponent<NetworkObject>().Spawn();
go.Throw(position);
}
but basically the grenade prefabs spawns in but dosnt move at all just stays
I tried making the Throw method client/server rpc but didnt work. It has a Client Network Transform to sync its transform so dont think it needs that. not sure tho
Since the grenade has a network rigidbody component it will be kinematic on the clients.
Use NetTransform instead.
i have a problem with networking a physics object that is already in the scene with photon fusion i have the netwotk object and network rigidbody but do i have to instantiate it or something?
Got it all working thanks for the help 🙂
Hey guys
I have a question
I want to host servers in such way
that the players can host a server
and the clients join the server
but I dont want to use any existing multiplayer services
I want to host the servers on my laptop
I have good internet
and atleast 1TB of SSD storage
just need guide on how to set it up
Without using a relay service you are going to have to give the world your public IP address then set up port forwarding. This is not something you want your players to have to do.
so I have a very weird problem with netcode for gameobjects
basically I imported it and it does work
but it doesn't appear in the In Project packages in the package manager
tho if I search for it in Unity Registry it does appear with the check, imported (tho for some weird reason I can't remove it because it's installed as a dependency)
fixed it, basically I needed to reimport the package from the git URL I got it from and it just added it
Hey! Not sure if this is too hard to set up but I'm trying to make a game where players connect via their phones and then the drinks on screen are filled depending on the tilt of the device.
Any advice on how to get this set up is appreciated or if it even is possible or feasible!
Im willing to make 3d models for games if anyone needs it
so my assumption, if I understand you correctly, is that you basically have a game with a tavern for exmample where there are drinks and you want them filled locally, by the tilt of the phone?
This should be pretty easy to make, you just make your game, get the tilt of your phone and map it between 0 to 1, 0 not filled, 1 full, that it is it, if you want it synced, just make it a network var
Hey all, I’m pretty new at this still and I’m trying to follow different tutorials and the like to make my own multiplayer game using Netcode for GameObjects.
I’m wondering if anyone else has had trouble trying to understand how to implement item inventories like individual inventory, shared chests, and shop inventories.
Just at a basic level, should the inventories only be created/instantiated on the server side or should I be using things like IsOwner and instantiate the players personal inventory on the client and others on the server.
But then I have questions about sending the item data via rpcs and there’s a whole bunch of issues with serializing the stats of the item.
Has anyone seen someone’s project or tutorial that can really help me understand what I should be doing?
Again, super new so really appreciate and guidance and patience over my probably misunderstood ideas.
So here is how I did it, firstoff my game is just a casual survival game and I don't mind people cheating, if that is what they want to do, so I was lazy in the desigb
I just made the inventory local and I have writte a custom struct with serialization to send that info to the host, which then puts it into a database. For chests I will do a similar thing, have everything on the server and send copies of that to the local players via the struct. This way it is easy to implement with db management and I can access the chests in the local inventories
One thing about this is, it makes it easy to cheat, but I don't care about that. If the player says he now has 500 apples via cheat engine, the game says ok and writes it into the db on the host
So depending on your project you should only make this server sided
The design of the netcode is easy once you asked the question "how much can I trust my clients/players"
Depending on how much data is actually in the item, it could also become handy to have an item manager, so you only have itemname/id and count in your actual inventory, which makes it easy to syncronize and you just request the rest from you item manager. Like when you drop an item and want to now what prefab to spawn
I was originally thinking to just have it local and when trying to send info to like a shop or drop items in the world, so long as I kept my item very simple it can work.
I’m using scriptable objects for the items and database btw.
I was registering the item to a database and then passing the itemID though the rpc and reconstructing the item using the database on the server side to spawn.
But then when adding things like buffs or stats, the item becomes unique and I’m having a ridiculous time trying to pass the info.
And I can’t really register it to the database since if I were to recreate it on the server side it would not have the same stats.
I mean, I suppose I can just really break down the item into basic values and reconstruct the whole thing on the other side, but that seems wrong. But what do I know :p
Or maybe I setup a separate database for unique items that can register a UUID. But then I think I’m still gonna have to send the data to the server somehow to register the UUID on the server side db.
Just do it on the server side then. If everything is allready there it makes it easier. You need to sync some information either way tho, since the client needs to know of some things to actually fisplay stuff
Fair point, I need to really just keep plugging away and see which ways really support what I’m doing.
I have a basic understanding so if I can at least start to be able to break everything down and send the data to be reconstructed on the other side, I can worry about fixing it later 😂
yea just write a quick prototype, there is time for refinement later
I did the scriptable object item manager thing. I haven't done temp buffs yet but enchant upgrades will also use SOs. In a database, item ID 43 will have upgrade IDs 86,30, and 49.
Ooooo, now that’s a thought.
A db of buffs/enchantments instead of generating them. Neat idea!
The main thing I'm a little confused about is how to make the desktop app and the mobile app use the same connection if that makes sense?
If its like a Jackbox game, I believe they use a web server for the shared connection
Is there an easy way to set that up via packages or anything or is it a convoluted sorta thing?
I used this asset called Happy Fun Times a number of years ago but it looks like it's been deprecated. But it should give you a starting point at least
https://github.com/greggman/hft-unity3d/
Where should I start more multiplayer matchmaking? i followed Code Monkeys video on Game server hosting(multiplay) and Matchmaker but i don't know how to set up the code
The videos talk about how to set it up in the Unity dashboard and go over the code but I'm wounding how to make a button that will start a match
And i didn't really understand the code that he was talking about
There is not a whole lot of code to go through. basically the client create a matchmaking ticket. When a match is found it will spin up a server which can grab the match results and set up the match accordingly
https://docs.unity.com/ugs/en-us/manual/matchmaker/manual/get-started
Hi I'm currently trying to figure out multiplay and matchmaker, I need clarifications if my understanding is correct. Basically matchmaker is the one that enables and disables the fleets that you have already created right? in that case, what will happen if I only have 5 fleets and all players already occupied them then a new player comes in and finds a match? will it create a new fleet or will it cause error?
It will spin up a new server in your fleet. Not create a new fleet.
thank you for your response, I misunderstood server and fleet.
please help what i need put to LobbyMember?
I don't know, but maybe this is helpfull anyway, hover over .Members and your intillisense will tell you what type it is, if you have set it up correctly, alternatively open the docs, which should also specifices the array/list type
Well I can actually afford this
no worries if my IP is leaked
I don't know where you live, but the 100$ for steam, which includes their networking, will be cheaper in the longrun, than constantly having a server running in your home, so players can play 24/7
Self hosting is not a valid idea for these types of games anymore, you will always be better of with using a battle tested solution.
And what evolotaku was reffering to is that if players have to self host, portforward and expose their IP that is a nogo for most of them and you can't do that anymore
If you don't want a realy service have a dedicated server build, for linux, that everyone can download for free and host on a vps, this is the way minecraft servers work for example
Even then, you would need to host your own server, for people starting in the game, they won't just invest an additional 5$ in an vps and you will once again be better off with using steam, epic, unitys gaming services, ..., in the long run
i want android and iOS
Not to mention the work of patching servers, maintaining them, keeping them secure and so on
I don't develop for these platforms, but I'm guessing the same can be said for them. For cross platform solutions you will have to use the relays of your transport provider (unity, fishnet, photon)
These will be paid monthly tho afaik
hmmmmmmm
I guess .Net core provides local host feature
but is it the same as a full fledged online server hosted on a local ip address and router?
You can't do that. No one is portforwarding on their phones, won't happen
In the mobile market users expect even more to just download and run the game instead of going through a tedious setup
hmmmmmmmm
so what's the best solution?
cuz I have only 300$ atm
to spend on the servers and stuff
and I want a good solution
Also a question
many games have their own servers
how do they achieve that if not using Unity Multiplayer services and so on
That depend son the scale of your game, your expdcted ccu users that are simultaneously playing your game) and your budget
If you have a 50player game, you are in the free tier of unitys gaming services (which is free up to an average of 50ccu over the month)
If you are way above and your game doesn't need a lot of processing power, having a dedicated server is the way to go
Also a question
I heard about the dedicated server but dunno how it exactly works
Also there is aws, azure and so on, there are a lot of options for hosting, which one to choose will depend on your platform, your expectations, your roi (return of investment), playerbase, ...
A dedicated server build is a build that does not have the game in it only the server stuff. It is meant to run on a server
A virtual private server (vps) is a server that happens through virtualization like proxmox, it is basically a vm
A dedicated server, also called bare metal server, is a server os running on actual (server) hardware
understood
so it just does is calls the functions of the game written on a machine which actually does the processing over the actual server right?
Also I heard that for the Unity Multiplayer
the first fee is usually 600$
or maybe 800$
I can't tell you how it works in unity specifically, because I use steams lobby system, so I have a host as a server (host= a client which additionally hosts the server)
But usually with dedicated servers they contain the logic that needs to run there
Lets use webdev as an example, because it is more intuitive:
Let us supose the user wants to edit a form that allready exists (adress and so on), multiple steps need to happen for that:
-request to the server for the existing data
-the server processes that request and gets the data from the database and optimally just sends it to the page, notice how the server does not know about any off the actual stuff happening on the website
-the website recieves that data and processes it to put in the existing form
You can imagine the same thing for gamedev, the server obviously needs to know how the current scene layout is, for physics processing and so on, what it doesn't need to do is render the whole scene and display it somewhere, because that would be useless information to the server
So it is more like you think about where what part of the logic should happen and deal with requests and so on (or your transport does it)
understood
so
for now
What I want to host is a server that actually stores just the data which the players/user of the application wants to
and the other users/players can actually see the data stored on the server
and can download the data from the server as well
much like Firebase Realtime Database
I wanted an efficient solution
I have a good laptop with 1TB of SSD storage and more as well
and 2GB of GPU and 16 GB of ram as well
I wanted to know if not the multiplayer but only the files can be stored on it someway by making it a server
i dont care if my IP address is leaked or what so ever
I live in an area where these things dont matter much
If the electricity bill is not an issue for you, sure
I have run my calculations, for my country and it would be so not worth it, a server by a provider is always cheaper in my case
in my country
the server by the provider kindda seems much of a cost issue
due to low value of the currency
but due to the currency value sooo low
the resources are not much a deal as they are easily a get to go with
So yes you can, I would just strongly adivce against that for a released game, in the western world, where self hosting is much more expensive
Like i have a really good pc build
any guides and tutorials
and what should I actually do
?
or where to take a start
I'm not a mobile dev, so it might be better to ask these things in a network related discord. Can't tell you
I only know how the internet is build up from an academically perspective and how I develop my game with a higher level solution from a dev perspective
But some steps should be always the same:
-get your server to run linux (much less frustrating for that kindoff stuff, if you don't bave a dedicated server use a linux vm)
-hardcode your static ip or domain with ports in the server build
-somehow get the server build
-configure your server with the right ports etc
-execute that server build
-profit/let players play
How to get the server build I can't help you
I would advice to checkout the network discords in the pins
ok thanks for the info
So I am working on my own steamworks.NET package and I have some quick questions, The usecase for this is small co-op games (1-5 players) to play with friends:
-
Where should you sync variables / player locations? Should you do it in update, fixedupdate or run a coroutine that runs x times per second, like ticks in for example Minecraft. I can see some problems with all of them so if anyone could give some input it would be nice.
-
Is it better to send data from the player to the host and then the host broadcasts to all players or just let one player broadcast to all. I dont really care about cheating since this is for friends, not anything competitive.
-
For performance is it better to send player position and rotation or just keyboard and mouse input and then let the other clients do the calculations?
It might be worth to checkout the facepunch package, it is open source and under mit licence, so checking how they do it should be straight forward
Can't help you anymore, that is too deep in the topic for me
alright thanks!
update: the scene reloading is not related to the excess player spawns. I commented out the two lines in the foreach loop so no players would be created and it still gets stuck in a loop reloading the scene
got it working
We are using certificates for Unity transport encryption like recommended here:
https://docs-multiplayer.unity3d.com/transport/current/secure-connection/index.html
However our customer requires to use a intermediate certificate workflow with IntermediateCA certificates create from the comapnies RootCA.
A test using customer created certificats didnt work so now we are wondering if the workflow with intermediate certificates is supported by unity transport.
I am no expert in handling certificates, so any help or suggestions would be appreciated 🙂
You can configure the Unity Transport package to encrypt the connection between the server and clients while ensuring the authenticity of both.
Hello, I want to ask. I am pretty new in making multiplayer game. What if I want to make my main menu online. Do i need to connect to server from the start of the game? I am using mirror networking. Want to implement data syncing and globat chat in main menu.
is this a global server or a lobby system?
for example you could have a game main menu and when you join a lobby a lobby menu where everyone can pick their skin and so on
or for a global server, usernames, chats, friends and so on
Eitherway that shouldn't matter too much and you should be able to just use the networking, if you are allready connected, simple with a global dedicated server, more complicated in a lobby based situation
Well for main menu it is global. For gameplay actually it is 1vs1 match
So it is oneserver, which handles all of that main menu logic with one given IP? (or in a more complicated setup one domain with your servers and dns to allow for load balencing)
I see.. so it is okay to just connect to server as the game start. I am actually scared that the server cant handle global server connection
One server only
I am not planning to seperate server by region
this is actually pretty easy then, just hardcode a connect to that server in your network manager
depends how well your server build works and how much ccu you have, I would be more afraid of latency
Well if i need to handle multiple server maybe i need to get server list reference to player to choose then
you can always expand later, just get your game running in the first place ^^
Yeah, actually I am not thinking of any advanced matter
of course that requires you to write scalable code and not spagheti code, but that shouldn't be something that needs to be mentioned
My gameplay is simple and turn based. So maybe it will not take load for server to handle
Yeah, quality code matter
Thank you for answering. Rather than coding logic, I am in need of multiplayer architechture now because I dont know how most of multiplayer game implemented
By letting client connect at start it make it easy for server to match making basically solved my problem to
chatgpt is always a great place for these kind of concepts, it messes up big time with actual code, but the basic concepts of a specific feature in multiplayer games are very well explained by it
Next to that I would recommend watching tutorials and writing your own small application, a text based card game should be fine, this will need you to handle rpcs, network vars, differentiate between client and server logic and give you an overview of how networking works in games
if you have any specific problems, you can come here or the mirror discord is pinned as well
Ah, I never really try chatgpt.. maybe I will consider that for resource searching
and when I mean chatgpt is a great place I mean to challenge your understanding, so I have problem x and I thought about using concept y because of reasons z, can you give me an opinion to my thoughts. This works great and it helps you learn by having a conversation, just doing the "write code that does x for me" thing won't work, most of the time that code won't even compile or run
[SerializeField] private GameObject _player;
[SerializeField] private NetworkObject playerObject;
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
playerObject = NetworkManager.Singleton.LocalClient.PlayerObject;
_player = playerObject.gameObject;
localPlayerAttack = _player.GetComponent<PlayerAttack>();
joinNetworkUI.SetActive(false);
}```
Im trying to reference player, but doesnt seem to be working, i cant figure out the right way to do this. Anyone have any more knowledge on it?
if i set a ienumerator to wait 3 seconds before calling, it works, but whats the right method?
update, this works !
{
NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnected;
ability1UI.color = abilityBaseColor;
}
private void OnClientConnected(ulong clientId)
{
clientId = OwnerClientId;
playerObject = NetworkManager.Singleton.LocalClient.PlayerObject;
_player = playerObject.gameObject;
localPlayerAttack = _player.GetComponent<PlayerAttack>();
}```
[RELATED TO NETCODE FOR GAMEOBJECTS]
Hey all, I'm kind of stumped here... I made a grabbing system using fixed joints between objects, but can't get it to sync properly. I've tried using clientRPCs and serverRPCs for creating and destroying joints, this seems to work just fine for the host but you can't say the same for the clients. The clients cannot grab anything at all, only the host can.
Here's the grabbing code: https://paste.ofcode.org/NNMZNv9MMsm66EUfBuiLBN
And here's a video for better demonstration (don't worry about the errors that pop up on the build version of the game, that isn't related to this problem):
Also quick note: I tried to do this without RPCs at all, but for some reason only the host could pick up the cube, everything else worked fine.
I made a game with Netcode. And when I try to run It it gives this error message: [Netcode] Runtime Network Prefabs was not empty at initialization time. Network Prefab registrations made before initialization will be replaced by NetworkPrefabsList.
UnityEngine.Debug:LogWarning (object)
basically I have some prefabs placed in the scene but still some are instatniating after the game started
the game itself works but when somebody tries to join it wont work for them
anyone know this problem?
Update to this:
Hi, I got the grabbing to somewhat work for the clients, but it's REALLY laggy, but for the host it works flawlessly. I have a 5g wired LAN connection, so latency shouldn't be an issue. I messed with the tick rate but it didn't help.
Here's the grabbing code: https://paste.ofcode.org/3b2Gt4S4StyfA6ELXMtsgk4
If you have questions please ask!
Here's a video:
does someone in here use photon pun?
im having problems with it
it doesn't connect to servers
it was working yesterday morning
but it stopped working in the evening
What does it doesn't connect to servers mean exactly?
What happens when you try?
Are you encountering some kind of error?
like
i run the game right?
its supposed to connect on awake
and join room also
cuz i have both options on
but i doesn't work
BUT
it used to work
it just stopped working suddenly
Anyone got a Good Source where to learn how to Async Load with the Netcode for GameObjects?
this doesnt really look like lag to me, you could add debugs to see when stuff happens. it looks like the joints arent in the correct place or something
i think i just found out the reason, if a client grabs something, it just starts creating a TON of joints for some reason
this does not happen with the host
it should only create like 1 joint
here's the code if you wanna see it https://paste.ofcode.org/nV8nZNuknPHbEuch77mFKs
it's probably these if statements that are failing but i don't know why
look at where you are adding components (ServerRpc) but the client is checking for the component
i tried to put the null check inside the createJointServerRpc but i got the same results
the issue is not a null check
think of it like this: theres a client and server. Server is creating a joint between your player and the box. Client does not create it, meaning the client doesnt see it. There is no joint on your clients side. Everytime you check if theres a joint, its the same result because your client never made it.
adding/removing components are not synced like this, so one possible fix is send the input to the server that the client is pressing the hold button. Have the server do this hold logic and check if it can grab anything. The client wont really be able to send these RPC's in a correct way
even if you add a joint client side, you have to check with the server that it makes sense because things may have moved away by then possibly due to lag.
If i Spawn my Player Object, as the Child of a Scroll View, i cant Save it from beeing Destroyed Right? (Netcode)
If i swap Scene now the PlayerObjects gets Destroyed and i got No Reference for the Player or just anything to keep the Player... what would be the Correct way to do that?
A) Respawn a PlayerCharacter after Screen Swap for each still connected Player?
B) Keep that Player from Beeing Destroyed?
i think this is the right channel
im following a tutorial on Networking for Game Objects, the unity multiplayer pkg and i have gottern it as far as a host / server and a client connecting, and having the players synced up. my problem is that i still am albe to control the other player from the other client, adn sometimes it even completely locks up the camera script. its probably an oversight, or ive used it wrong but none the less heres my Movement.cs and MouseLook.cs
Movement
https://pastebin.com/0LR18RpT
MouseLook
https://pastebin.com/hTjG5K4c
you can see if i have put in the respective IsOwner checks
ive also attached screenshots showing what my player prefab looksl ike (from prefab view not in game)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
does someone in here use photon pun 2?
im having problems with it
it doesn't connect to servers
it was working yesterday morning
but it stopped working in the evening
i run the game right?
its supposed to connect on awake
and join room also
cuz i have both options on
but i doesn't work
BUT
it used to work
it just stopped working suddenly
@mortal widget Maybe check if your games are correctly shutting down using the Pun webtool.
I remember when I was using Pun I was reconnecting to the same game which was bugged.
Also creating a build and testing it there can sometimes help.
if i Spawn my Prefab with
GameObject playerLobbyPrefab = Instantiate(lobbyPrefab, Vector3.zero, Quaternion.identity);
playerLobbyPrefab.GetComponent<NetworkObject>().SpawnWithOwnership(obj, true);
(obj in this context is the ulong from the OnClientConnectedCallback)
why is my isLocalPlayer false? shouldnt he have authority over that Object?
You are just spawning with ownership. IsOwner will be true. You want to SpawnAsPlayerObject()
If you have a camera as part of the player then you will need to to disable the camera on the remote players
ahhh... Thanks
But then i got another question, whats the Difference Between Authority and Ownership? isnt that... the same?
To illustrate the difference: The police has the authority to put you in jail if you shoot the gun you own in public.
so you say it might work on builds but not on unity?
I have that be the case yes. But your problem description is very vague so can't really tell you more.
its cuz it just stopped working
😭
out of nowhere
Compare your code with the latest working version.
Or rollback to it.
Anyone here used Mirror as well as Netcode? i need some Pro/Cons after working With Netcode if its worth to take a look at Mirror before Commiting to Netcode
im completely green to this what do I need if I want to run one instance of my game on someones servers I need recommendation I hoped to stick with google so I dont add another dependency but they only got web hosting it seems
Compute servers on Google Cloud should work fine. You are probably looking at some web hosting specific site of Google.
Hey! I'm trying to make a game and the gist of what I want to do.
1: Player walks around environment.
2: Player closes game.
3: Final player position is sent to a network and saved.
4: Whenever somebody opens the game objects are instantiated at all those saved positions.
Is there any free way to implement this?
Does Photon Fusion works like Unity Relay system?
or is it different?
Photon Fusion is a netcode framework not a relay service, but it can used with a relay service.
do you have a budget?
You mean just saving the player position? Is this suppossed to be a host/client or server/client architecture?
Either way you will have to have a database running on the server/host side
(For hosts I recommend sqlite3 and for a dedicated server solution mariadb/mysql)
It is just having a db connector on the server, processing and sending that data on the server to the client and handling that data on the client. That is all there is to it
DB<-->server is all you have to worry about, the rest is the same sync as every other data in your game
is there a way to use quickjoin in combination with relay? i thought there would be like a "QuickjoinAllocationAsync()" similar to how you would normally join a relay lobby with a lobbyCode. any ideas on how to do this?
There is no list of Relays to search. You can only search or quick join Lobbies
but how would i quickjoin a lobby with relay then
after you create a Relay then add the relay join code to the Lobby Data
that sounds like a simple solution. thanks
Suggestion on Networking.. ??
You're going to have to narrow it down a bit
Hey anyone know how i can join in started game?
im using unity netcode and steam facepunch
Hey I was sent here to ask my question. Copy paste:
Hey, what should I use to make a multiplayer game which has a hosted server by me?
A server I can purchase somewhere, I think it's called dedicated server?
So people have to connect to my server instead of playing through IP/hosting their own.
Ideally I'd like a tutorial on how to do that.
This is meant to be for a battle arena style of game with more than 10 people playing at the same time.
I understand this won't be easy, but I need something to get me started.
Someone mentioned https://aws.amazon.com/gamelift/
But ideally I'd get some sort of tutorial on how to set this up.
Also looking for all other options.
Check the pinned message here. You'll need to pick a network framework first then read through the docs. And then you can start looking up tutorials
Thanks
i'm working on a multiplayer character customization menu and need some help with logic and program flow. i'm using a client/host setup not a dedicated server.
how i want this to work is:
- in singleplayer (self-host) mode, let the one player adjust all characters freely
- in a three player lobby, let each player only adjust themselves and hide the controls for the other two players
- in a two player lobby let each player adjust both themselves and the third character but not each other. hide the controls for the other player (ie player 1 can adjust 1 and 3 but 2 is hidden)
i have not set up anything to do with object ownership yet so right now the host controls everyone's appearance. how do I set up ownership of these objects?
the apperance is already controlled by NetworkVariables so they will sync correctly across clients
That kinda depends on the network variable permissions. If it's server write then the clients would need to send a serverRPC to change things. If it's owner write then you'd need to call ChangeOwnership() before the new owner can change things
I want to build a strategy game something like a 3d turn based real time strategy - will involve moving characters and each one will have their turn
Have no experience in Networking at all - had used some Photon before
The game is for mobile devices, what would be the best way to implement it? Any packages or modules for Unity that anyone recommends?
I'm using matchmaker, when I make a new match I receive this error. I have 6/7 available servers from the fleet.
MultiplayAllocationError: request error: maximum capacity reached (1)
Hey everyone. We are having an issue where, we have a Database on a server and we Query it with Unity WebGl through HTTP requests (not HTTPS) to get the table associated with our computer name. This used to work in unity 2020 but since we updated to unity 2022 it stopped working. I noticed there is a new setting in player settings called allow HTTP requests and we have this set to always allow. Any idea what might be causing this? Anyone can help? Thanks 🙂
It’s very plausible that non-encrypted network setups will stop working eventually for all sorts of reasons. Ideally you’d aim to always use a secure stack, especially if you want to keep using webGL
A certificat with scriptbot is literally free as well. There is no reason to use http and you shouldn't ever use http outside of the local network for testing. So not shure if that is the reason it stoped working, but that is something to work on either waY
Hello everyone!!! We met a lot of you developers at this year's tradeshows (GameRebellion hi friends! 👋)
MIGS 2023 is next, another important tradeshow in Montreal, QC. We're giving away 2 Free Indie Tickets to studios with less than 9 employees!
If anyone is interested in entering our contest feel free to respond / DM me 😄
for more info on GameRebellion:
gamerebellion.com
Hey so I’m planning on make a vr multiplayer game and I am thinking of using normcore to add multiplayer. I just want to get your guy’s opinion if normcore is a good choice. Thanks
Hey is there a tutorial how to use new "Unity Player Accounts" for Unity Authentification ?
Never heard of it. How far does the documentation go? How much support is there for this solution? What is your budget? And what exactly is your pject requirement?
These are the questions you need to ask, for every solution and evaluate them. I would go with a well documented solution
I'm stuck on some behavior I don't understand. I have a set of NetworkVariables to control character appearance declared like this:
private NetworkVariable<int> skinColor = new NetworkVariable<int>(3, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
I'm testing the case where there's two players right now. Player 0 is the host and Player 1 is the client. I want both players to be able to control the appearance of Player 2, who would be ai controlled in game since there is no third human connected in this scenario.
I tried setting the ownership of the Player 2 prefab to Player 1, figuring that Player 0 would have access anyway because it is the server. But trying to modify the appearance of Player 2 with Player 0 gives an error Client is not allowed to write to this NetworkVariable.
How do I make it so that both host and client can modify the object?
If you set it to owner, only the owner can write to it no one else. To server only the server can write no one else
The server does not have permission when you set it to owner, afaik
And the how you achieve it:
Custom functions that handle the syncing on the server
Set the network var to server write permissions and use a serverrpc to change the network var
This is probably the easiest way
The reason behind that is very likely the question "what happens if both set it simultaneously? Who is right?"
And data races can be nasty bugs you don't want to debug, they can be unpredictable, so it is good that they are not allowed
ok that makes a lot of sense. so i need to restructure slightly so that the NetworkVariables are server owned and the interface buttons no longer directly modify the value but instead call a ServerRpc to set them that way. They probably don't even need to be NetworkVariables then, actually? Since the server owns them anyway? And then I control access by simply controlling access to the interfaces for each character?
It depends on what you are doing if they still need to be network vars, a server rpc is just execute following code on the server. So if you want to change color from ui for example and that color should be available for late joiners as well (rpcs are one time events, network vars sync)
This would be your process:
Client: color input
Submit -> server rpc to colorChange
Server, ColorChange: chnage the value of the network var
The network var internally then syncs to the clients
With an onchange event you can catch that on other clients and execute your own logic
If your action is one time only, so late joiners don't have ti be taken into account:
Client: colorChangeServerRpc with value
Server: just calls colorChangeClientRpc with value
ColorChangeClientRpc than actually changes the color
This is a one time event, which syncs, the network vars sync even with late joiners
So it really depends what you want to achieve
The best option, for non realtime stuff (so movement for example is out, the delay is too high), is to have a server network var and modifying it in a server rpc
For player skins this way seems to be the most reasonable. The delay is irrelevant, since it doesn't change every single frame, it syncs with late joiners and you can call the server rpc anywhere (make sure to have it set so non owners can call it)
[ServerRpc(RequireOwnership=false)]
awesome that's incredibly helpful, thank you! i think I can figure it out from here with that info
No problem
One thing tho, if the delay does become too high and you want to change it, you can call both the server rpc and the function to change it localy
This way you are basically saying, server please change that and I'm trusting this will happen very soon anyway, so Imma do it now
This is a neat little trick to compensate for delays. With changing stuff like player movement this does become more complicated and you will need to write actual prediction and not just, I'm taking a leap of faith I will apply it now and trust that I will recieve that signal in 200ms anyway
oh yeah i've only been doing local testing so far. i imagine it would feel bad to click a button and get a delayed response so i should consider that. would i need basically two copies of every variable, the network one and the local one? and the local one is what actually determines stuff but when the network variable changes it updates the local one too? and to do this i simply change the local one immediately when calling the rpc and let it get overridden automatically to the same value when the update response comes back?
The thing to understand here is what your code actually does. The variable itself should hold not much meaning, it should only hold the value, that's the job
The logic to change it should be decoupled from that, I will make that more obvious with a simpler example
//in your code this would be a network var
int number = 0;
//The logic we want to execute
void printNum(int n) {print(n);}
//The onchange function
//I will call that directly and we assume a delay here, in thus simpler example
void numberOnChange(int prev, int cur) {
printNum(cur);
}
void main(){
...
printNum(x+1);
numberOnChange(x,x+1);
}
This is a very simple example, obviosuly this will print twice, for a simple skin changer that is not important, you can add one simple local bool to take that into account, so that is not much of an issue
And that is a very simple way to decouple your code, the actual changer function does not know of the existence of your network var, you just pass the value in
In a real world case the onchange would be called by ngo and you would only write the rpc and change the network var
And obviously overload the onchange function with your existing one
netVar.onChange += yourFunction;
yeah i'm already doing something similiar
public class PlayerPreview : NetworkBehaviour
{
private NetworkVariable<int> skinColor = new NetworkVariable<int>(3, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner);
private NetworkVariable (etc...)
[SerializeField] private Image skinImage;
[SerializeField] private Image (etc...)
public override void OnNetworkSpawn()
{
skinColor.OnValueChanged += SetSkin;
eyeColor.OnValueChanged += SetEyes;
hairColor.OnValueChanged += SetHairColor;
hairStyle.OnValueChanged += SetHairStyle;
outfit.OnValueChanged += SetOutfit;
Material mat = Instantiate<Material>(skinImage.material);
skinImage.material = mat;
mat = Instantiate<Material>(eyeImage.material);
eyeImage.material = mat;
mat = Instantiate<Material>(hairImage.material);
hairImage.material = mat;
}
public void NextSkin()
{
skinColor.Value = (skinColor.Value == 16) ? 0 : (skinColor.Value + 1);
}
public void PrevSkin()
{
skinColor.Value = (skinColor.Value == 0) ? 16 : (skinColor.Value - 1);
}
public void SetSkin(int previous, int current)
{
Material mat = skinImage.material;
mat.SetFloat("_Current_Palette", (float)current);
}```
Good just calling SetSkin(0, the new Value) locally after calling the serverrpc should do the job then
In a simple case (so not changing every frame with prediction) changing it locally in addition to calling a serverrpc should only be one line more
With more experience a lot of syncronisation becomes almost trivial if and only if the code is structured properly
That is atleast my experience in my game, your experiences may differ xD
so just to make sure i'm understanding correctly all the functions on my interface buttons should be modified like:
public void NextSkin()
{
int value = (skinColor.Value == 16) ? 0 : (skinColor.Value + 1);
ChangeSkinServerRpc(value);
SetSkin(0, value);
}
and then I just need something like this to change it on the server
[ServerRpc(RequireOwnership=false)]
ChangeSkinServerRpc(int value)
{
skinColor.Value = value;
}
Yes exactly
If you want to know later down the line that this change is only local, you could pass in -1 for previous, since this is a value your network var will never hold
awesome thank you so much i'm confident this will work
No problem
I have this function that checks for (IsHost), and if it is, it changes a networked boolean to start the game. This all works, except ALL the users think they are the host and so the boolean is changed multiple times. This also causes a few functions to be called multiple times.
Here's where it goes wrong:
private void Start()
{
if (IsServer)
{
Invoke("StartGame", 10f);
}
}
This function is in a script with network behaviour, and attached to a player prefab which gets spawned for every player that has joined the lobby. What is going wrong?
Move that to onNetworkSpawn and see if the behaviour changes
It still is getting called multiple times. I noticed though they're only getting called twice on the host itself, and not on the other "client" devices. So my guess is there is something wrong with the player prefab
OnNetworkSpawn() gets called twice on the host. Once for the Host Client and once for the Host Server
But shouldn't it only Invoke "StartGame" on the host server? Since I check it with IsServer. Even with the if statement, in OnNetworkSpawn, it gets called multiple times
Host is both server and client so those checks will always be true
Damn. How to do this? I have network variable count. Each item (med kit, bandages) should be spawned with different count. For example bandages are packed in five
Do it through event on server started.
You mean OnServerInitialized()?
No, wait a second
Which version of unity you use?
2022.3 i think. Cant check right now
Hi I am struggling with some network principles that I want to discuss.
Imagine you have a scene with your level, a large building consisting of 10 different prefabs like walls and roof objects lets say around a 1000.
I have multiple player objects that can walk around in this building.
Now a wall is removed on the server. The wall is destroyed on the server but the wall is not a network object so the other clients wont see that.
What is the best way to communicate to the other clients that this wall has been destroyed on the server?
I tried adding a client rpc on the wall script that is called on the server that it should be destroyed, but the wall is not a network Object so it can't send out rpc calls.
Then I thought okay I will add an networkedObject to my wall prefab but that would mean 1000 networked objects (seems bad but not sure how much impact that would have) and I would have to instantiate the wall on the server which I don't really like.
Another thought was to create a separate empty networked object with a script that passes objectId's via ClientRpc's but I read that objectID's are not a reliable way to do this as they can differ each runtime.
How would you approach this issue?
Hm, maybe it is initialised. Because in older (2021) it is OnServerStarted
The easiest solution would be, if the building layout itself is static, to have a network object parent and just syncing the child id you want to deactivate/destroy
This is the easiest solution I can think off
You could also have a wall manager where every wall has to register itself and gets a unique but predictable identifier
What happens in the game start invoke?
Can you attach a debug statement in the isServer if statement
For example what could happen is if you load a different scene, your player instance gets destroyed and a new one created in the new scene, this would make the game run the whole initialization process twice
So when the server start instantiate this parent object parent it to the prefabs and let it control it's children via rpc calls.
Yes, yoz would structure your scene like this:
emtpyParent with NetworkObject
-wall1
-wall2
-...
Again this is the simplest solution, but if it works, it works
Yeah I agree I wanted to check if I was missing something. Thanks
@nocturne vapor I implemented the solution and it works.
But I forgot one thing RPC's are not great for synching data that is persistent.
So when a player joins late it misses the RPC calls and the changes to the building are not represented.
Yea. A network Variable/List would be better in that case. If the building isnt changing all that often then a Json of the current state of all the walls might be enough
I do indeed switch from scene, but I put the players in a DontDestroyOnLoad(), so they're not getting spawned in again
I see now I'm using 2021.3. But there is not autocomplete for OnServerStarted. It always gives me OnServerInitialized. And it doesn't do anything. When I run it, the method does not get called
i attached a debug.log to the if-statement. It does indeed print multiple times when in OnNetworkSpawn(), or in Start()
hi can anyone tell me why this is not running the generateSpawnPositions() or Invokerepeating methods. When I press server or host they dont run.
Coming back to this. I managed to find "OnServerStarted". I just wasn't calling it correctly. Now I have
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
if (!IsServer)
{
CanGameStart.OnValueChanged += OnStateChanged;
}
NetworkManager.Singleton.OnServerStarted += StartCoroutine;
}
and it works! It only gets called once now. Thanks @sharp axle and @teal cedar
Start() is called before the network is connected
@sharp axle ahh where should I do that check then?
OnNetworkSpawn()
@sharp axle awsome ty
Hey guys, I'm currently facing with two netcode issue
First is that when my client side, it sometimes stucked and only having lots of warning log like this
I can recognize that OnSpawn is an event I defined in my network prefabs which will be called on networkspawn()
But here's no more info for me to know what had I get wrong with
Second is that when I try to use spawnasplayerObject(clientID), it throws out an exception : Type System.Int32[] is not supported by NetworkVariable`1
The clientID seems doing well when I check it through debug.log
Can anyone help me with this?
it seems I was using illegal networkvariable<int[]>, but anyone knows how to use the networkList, not finding any docs releated with this part
seems like you just use NetworkList<int> and add / remove from it like a normal list, no?
I just searched "NetworkList" on this page https://docs-multiplayer.unity3d.com/netcode/current/basics/networkvariable/
Not having any NetworkList yet
you asked how to use a NetworkList
I meant that, I think you just declare a field of type NetworkList<int>
instead of NetworkVariable<int[]>
Sorry for this, got what you mean
Just went through the doc, and I'm just wondering whether this could help me with my situation
I'm having multiple factions in game like team red, tema blue etc.
And every team has it's Coins, Coins in total these kind of similar variables.
Before I use Networkvariable<int[]> Coins to declare it
And as I have a Enum type Faction, I just refer to Coins[(int)Faction.Red] to find RedCoins
Which is convenient to go through all factions with one loop and guaranteed the possibility to extend more factions in game
Sure, you would just have something like
public NetworkList<int> Coins = new NetworkList<int>();
public NetworkList<int> TotalCoins = new NetworkList<int>();
// when the server initializes this object
for (var i = 0; i < Enum.GetValues(typeof(Faction)).Length; i++) {
Coins.Add(default);
TotalCoins.Add(default);
}
// some useful methods
public int GetCoins(Faction faction) => Coins[(int)faction];
public int GetTotalCoins(Faction faction) => TotalCoins[(int)faction];
Cool this is so simple! When i refer to the doc, I thought I need to construct a struct like this
I'm kind of a newbie to C#, this example code really helps me a lot to understand how this networkList work.
yeah they are just going overboard because they are showing how to make a custom serializable type
Really really thanks for this
I just thought I needed to revert back to that kind of nasty code structure
I mean, let me know if that actually works haha
I have never used Unity's NetCode
So smooth
Everything works fine now, appreciate to this answer, this saves my day
Oh okay cool, perfect
Got another issue with smoothSync. Maybe network transform will also works but I experienced same issue before.
My network prefab got lots of child objects and for now it seems the whole unit is pretty laggy on it's child objects
My previous solution is switch to smoothsync and as it said in doc, you just add it to parent object and everything will be fine
Hard to describe this issue, but it seems my prefab just be tear apart and the client will just die after this problem
The child object just explodes😂
Anyone know why i get 2 copies of my ui when I run my game? Its like it creates a ghost copy...
I fixed it, there was no camera in the scene lol.
how to set parent of network object?
I spawn network object and then I want to set it to be child of another network object (manager)
Hello, I have a question regarding Unity Netcode
I have two classes with some properties inside them and one of my classes has a property of the other class type, here's the code:
public class Chat: INetworkSerializable
{
public string message;
public string type;
public string placeID;
public User receiver;
public User sender;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref message);
serializer.SerializeValue(ref type);
serializer.SerializeValue(ref placeID);
serializer.SerializeValue(ref receiver);
serializer.SerializeValue(ref sender);
}
}
public class User: INetworkSerializable
{
public string name;
public string uuid;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref name);
serializer.SerializeValue(ref uuid);
}
}
The error that I'm getting is this:
NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.FastBufferWriter.WriteValueSafe (System.String s, System.Boolean oneByteChars) (at Library/PackageCache/com.unity.netcode.gameobjects@1.1.0/Runtime/Serialization/FastBufferWriter.cs:498)
Unity.Netcode.BufferSerializerWriter.SerializeValue (System.String& s, System.Boolean oneByteChars) (at Library/PackageCache/com.unity.netcode.gameobjects@1.1.0/Runtime/Serialization/BufferSerializerWriter.cs:29)
Unity.Netcode.BufferSerializer`1[TReaderWriter].SerializeValue (System.String& s, System.Boolean oneByteChars) (at Library/PackageCache/com.unity.netcode.gameobjects@1.1.0/Runtime/Serialization/BufferSerializer.cs:71)
I'm sure that the classes are properly initialized before sending them, I'd be grateful if someone could lend a hand :3
Ok the problem is solved, seems like the problem was serializing string types, I changed the types to FixedString32 and it worked just fine, also I used serializer.SerializeNetworkSerializable for serializing my User class inside my Chat class.
I would make those structs instead of classes
Thanks for the advice, I'll change them to structs
Hi! Is there anyway of destroying just one cell from a tilemap on network?
Currently my projectile basically destroy the entire tileset on collision
I'm not too familiar with Tilemaps but it will probably have to be done with RPCs. You would have to send the exact tile coordinates in the RPC
for RPC i am using this ```[ServerRpc(RequireOwnership = false)]
public void DestroyBrickTileServerRpc(){
Tilemap toDestroy = destructableTilemap;
toDestroy.GetComponent<NetworkObject>().Despawn();
Destroy(toDestroy);
}``` but yeah, basically I am destroying the entire tilemap
as a non RPC i am using this one that works wonders```Vector3 hitPosition = Vector3.zero;
ContactPoint2D hit = collision.contacts[0];
hitPosition.x = hit.point.x - 0.01f * hit.normal.x;
hitPosition.y = hit.point.y - 0.01f * hit.normal.y;
destructableTilemap.SetTile(destructableTilemap.WorldToCell(hitPosition), null);```
but I am struggling atm sending the coordinates in the RPC
yea. just send a Vector2 instead of the Tilemap then do the SetTile() thing in the RPC.
It will need to be a ClientRPC to let all the other clients know
how do i find the object ? how does this even happen ?
also found an interesting "workaround" - instead of painting tiles, I am paiting gameobjects and these are already set and working for me
i'm trying to use a ClientRpc to teleport my players (who have client network transforms on them so they are client authoritative movement) but it's not working. the relevant code is:
immediately after my manager spawns the players:
player[0].TeleportClientRpc(new Vector3(-1.5f, 0.18f, 0f));
player[1].TeleportClientRpc(new Vector3(0f, 0.18f, 0f));
player[2].TeleportClientRpc(new Vector3(1.5f, 0.18f, 0f));```
in the player class:
```cs
[ClientRpc]
public void TeleportClientRpc(Vector3 newPosition)
{
if (!IsOwner) return;
transform.position = newPosition;
}```
the players are spawned like this:
foreach (ulong clientId in NetworkManager.Singleton.ConnectedClientsIds)
{
player[count] = Instantiate(playerPrefab).GetComponent<Player>();
player[count].GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
count++;
}
if (count < 3)
{
for (int i = count; i < 3; i++)
{
player[i] = Instantiate(playerPrefab).GetComponent<Player>();
player[i].isAi = true;
player[i].GetComponent<NetworkObject>().Spawn();
}
}```
for now I removed the teleport calls and just adjusted the position with Instantiate(object, position, rotation) instead of Instantiate(object) but I'm still curious why it failed
How would you guys properly shut down a host's server? I'm making a practice multiplayer game with NGO, and it's pretty much done except for shutting down a host's server. I want to shut down a server, taking all clients and the host back to the main menu scene. Any ideas?
All I know is I use the Shutdown() method but that's it:
NetworkManager.Singleton.Shutdown();
Thanks!
That's it. When the host shuts down, it will end the network and everyone gets disconnected. You can then just load your main menu with Load Scene
ty
Hi guys if anyone is going to be there at Unity Unite Event in Amsterdam from Nov 15 - 16, please PM me gladly if you would be interested to join me !
P.s : Unfortunately tickets are sold out. @mods Please let me know if this is not right channel and also should post somewhere else !
i cant find the vivox package in the package manager for some reason
hey guys, I have a list of images and data that I want to save and call from code in run time, but I'm building for Android, I tried saving it as a binary file and loading it, It worked on PC but not in Android, is it possible to do it in another way or I have to use a server to send the images!??
You have to add it by name com.unity.services.vivox
thank you
How would you guys properly destroy a Network player object? I got a Left 4 Dead inspired game with players vs ai, but I'm pretty unsure to how I can correctly remove/destroy a player from a scene, but can spectate players through a camera.
Hey guys. Quick question. I'm using Netcode, and I'm trying to trigger a script when a player connects to my game. What do I call?
OnNetworkSpawn isn't working, since it's only fired when the server itself is created (correct me if I'm wrong?)
Or maybe somebody else can tell me what's wrong with my code. My game has 8 players, and each player is supposed to have a unique tag. The game is spawning all players with the Player1 tag. How do I fix this?
OnNetworkSpawn is called on the NetworkObject that was spawned. I don't really see how playerNumber can ever become more than 1 if I'm picturing this setup correctly.
So, is there a different event handler I should be using?
Not very familiar with Netcode for GOs, but I would imagine you would hook into or override NetworkManager or one of its it's sub-systems.
The server has to be the one that instanties and spawns the players. You could use the Onclientconnected callback or you could use Connection Approval
Making playerNumber static or storing it in a shared place could work
But I would consider setting these sort of things based on some explicit data provided by the server if I wanted to keep these tags consistent between clients
Personally I would just use the client id instead of a playerNumber variable
Thank you for the feedback. I'll go back to the drawing board.
Can someone help me with Unity Lobby and Relay.
I am stuck on a problem. The player cannot connect to same lobby after disconnection. It says the player is already a member of lobby.
How can the host remove the player from lobby if the player got disconnected by any means like internet crash, quit, etc?
I am using Unity Lobby + Relay + NGO
I even set the lobby config disconnection time to 10. The Netcode gives callback when client Disconnects but Lobby don't remove player even after the 10 seconds timeout. I waited for minutes but still the player didn't got removed from Lobby
Is this Unity relay or lobby SDK bug?
Are you using the Relay Lobby integration?
Yes
I can only speak for steamworks, the client needs to disconnect from the server/host AND the lobby api (in my case steamworks in yours probably relay)
Lobby, Relay and NGO all
You have a bug somewhere. Relay is supposed to remove the lobby player when it disconnected
There is no source which explains player removal from lobby after disconnection from NGO or Relay
I could he wrong here I never used it, just posted it in case this is transferable
Ohh. The NGO disconnection and connection callbacks occur perfectly but Lobby don't catch it
The player remains in lobby untill the lobby gets abandoned
So you have the allocation id set in the Lobby Player Data? That's how the integration works
What's that. How to set allocation id?
I think the relay and lobby is not connected in my case
But I am getting relay code from lobby data
And joining it
I would really appreciate your help into this
Utils.DebugLog("Creating relay allocation..");
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxPlayers);
string relayJoinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
Utils.DebugLog("Starting Host..");
//Making relay work with NGO
RelayServerData relayServerData = new RelayServerData(allocation, "dtls");
NetworkManager.Singleton.GetComponent<UnityTransport>().SetRelayServerData(relayServerData);
NetworkManager.Singleton.StartHost();
try
{
//Lobby
var options = new CreateLobbyOptions
{
Data = new Dictionary<string, DataObject> { { JOIN_CODE_KEY, new DataObject(DataObject.VisibilityOptions.Member, relayJoinCode) } },
IsPrivate = isPrivate,
};
Utils.DebugLog("Creating lobby");
var lobby = await Lobbies.Instance.CreateLobbyAsync(lobbyName, maxPlayers, options);
hostLobby = lobby;
StartCoroutine(HeartbeatLobbyCoroutine(lobby.Id, 15));
Utils.DebugLog("Created lobby " + lobby.Id + " Lobby join code " + lobby.LobbyCode);
// Create a new instance of LobbyEventCallbacks
LobbyEventCallbacks callbacks = new LobbyEventCallbacks();
// Subscribe to the PlayerJoined event
callbacks.PlayerJoined += OnPlayerJoined;
callbacks.PlayerLeft += OnPlayerLeft;
// Subscribe to lobby events
await Lobbies.Instance.SubscribeToLobbyEventsAsync(lobby.Id, callbacks);
}
catch (LobbyServiceException e)
{
Utils.DebugLog(e);
}
This is my code i first create Relay allocation and add relay code to lobby options data
I am not setting any allocation ids
am i missing something here?
I have to create a class of PlayerData and allocate id to it and when client gets disconnected from ngo i remove the player of that allocation id from lobby?
i have seen the sample but the thing i want it hard to find
var options = new CreateLobbyOptions
{
Data = new Dictionary<string, DataObject> {
{
JOIN_CODE_KEY, new DataObject(DataObject.VisibilityOptions.Member, relayJoinCode)
},
{
ALLOCATION_ID, new DataObject(DataObject.VisibilityOptions.Member, allocation.AllocationId.ToString())
}
},
IsPrivate = isPrivate,
};
will it look like this
I have to do it with both Join and Create lobby options
Player Data is part of the lobby service. When a player joins the relay, you just have to update their lobby player data with the allocation id they got from JoinAllocationAsync
Yes I set allocation id with this for player.
But how I remove that player with allocation id?
Thats creating a new lobby. You need to update each player after they join
Yes I'll do it for both Join and Create
I just want to implement this
Idk how
So the allocation id is now sending in creation and after joining
In Creation
var options = new CreateLobbyOptions
{
Data = new Dictionary<string, DataObject> {
{
JOIN_CODE_KEY, new DataObject(DataObject.VisibilityOptions.Member, relayJoinCode)
}
},
Player = new Player
{
Data = new Dictionary<string, PlayerDataObject>
{
{
ALLOCATION_ID,new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member,allocation.AllocationId.ToString())
}
}
},
IsPrivate = isPrivate,
};
In Joining
var options = new UpdatePlayerOptions
{
Data = new Dictionary<string, PlayerDataObject>
{
{
ALLOCATION_ID,new PlayerDataObject(PlayerDataObject.VisibilityOptions.Member,joinAllocation.AllocationId.ToString())
}
}
};
// Update the player data in the lobby
await LobbyService.Instance.UpdatePlayerAsync(lobbyID, AuthenticationService.Instance.PlayerId, options);
How can the relay will now remove the player from lobby after disconnection using this allocation id?
The relay service will do this automatically
But how the relay server will know allocation id because its custom data right
The lobby service will tell it
Ohh. The allocation id in Player Data is getter so i am unable to set it. I did that through custom Key data
For me the client gets disconnected from relay but not from lobby even after doing this
can you look if i am missing something in code
I solved my problem by using ServerRpc but it doesnt call the ServerRpc methods on the client
can someone help? :(
ServerRpc will only execute on server. There is this constructor you can use [ServerRpc(RequireOwnership = false)] so any client can send this
.
how do I send code
I already used this
i didnt got it
you sended this code field here
"""
this symbol `
[ServerRpc(RequireOwnership = false)]
private void EnterCarServerRpc(ServerRpcParams serverparams = default)
{
Debug.Log("Entering");
NetworkObject.ChangeOwnership(serverparams.Receive.SenderClientId);
CarController.enabled = true;
DriveUI.gameObject.SetActive(false);
driving = true;
Player.transform.SetParent(Car);
Player.localPosition = new Vector3(-0.16f,-0.6f,0.125f);
PlayerOn(false);
PlayerCam.SetActive(false);
CarCam.SetActive(true);
}
[ServerRpc]
private void ExitCarServerRpc()
{
Debug.Log("Exiting");
NetworkObject.RemoveOwnership();
Car.gameObject.GetComponent<CarController>().brakeInput = 1f;
CarController.enabled = false;
driving = false;
Player.localPosition = new Vector3(-2.25f,0,0.125f);
Player.transform.SetParent(null);
PlayerOn(true);
PlayerCam.gameObject.SetActive(true);
Player.localRotation = Quaternion.Euler(0, -Player.localRotation.y, 0);
CarCam.SetActive(false);
}
yes
and The console doesnt send the Debug.Log(); on the client
I am kind of new to NGO as well 😦
ok...
This is my code to add knockback from 1 client to other client. The flow is 1 client send the target client id to server and server send it to the target client
Sending from 1 client
NetworkTransform otherNetworkObject = other.GetComponent<NetworkTransform>();
other.GetComponent<AttackHandler>().AddKnockoutForceServerRpc(otherNetworkObject.NetworkObjectId, knockbackDirection);
To server and server will send to target client
[ServerRpc(RequireOwnership = false)]
public void AddKnockoutForceServerRpc(ulong networkObjectID, Vector3 knockDirection)
{
if (NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(networkObjectID, out NetworkObject networkObject))
{
ulong targetClientID = networkObject.OwnerClientId;
Debug.Log("[Server] Applying force to client " + targetClientID);
networkObject.transform.GetChild(0).GetComponent<AttackHandler>().ApplyForceToClientRpc(knockDirection, new ClientRpcParams
{
Send = new ClientRpcSendParams
{
TargetClientIds = new ulong[] { targetClientID }
}
});
}
}
[ClientRpc]
private void ApplyForceToClientRpc(Vector3 knockDirection, ClientRpcParams clientRpcParams = default)
{
Debug.Log("Received knockback in direction " + knockDirection);
StartCoroutine(pushTowardsKnockDirection(knockDirection));
}
This is a test chat script this can also help you
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;
public class TestRPC : NetworkBehaviour
{
[SerializeField] private TMP_InputField rpcField;
[SerializeField] private Text receveiddataText;
public void SendData()
{
SendMsgServerRpc(rpcField.text);
}
[ServerRpc(RequireOwnership = false)]
public void SendMsgServerRpc(string msg)
{
DataOfFieldClientRpc(msg);
}
[ClientRpc]
public void DataOfFieldClientRpc(string someText)
{
receveiddataText.text = receveiddataText.text + "\n" + someText;
Debug.Log(someText);
}
}
Someone pls help regarding this
Yes in this code I did exactly that. But how I connect that allocation key of player data with relay
I already did that in above code
Do the string in the allocation key should exactly be same as "AllocationId"?
No you should set it in options.AllocationId
In playerdataobject.allocationid?
nope. in options.AllocationId after you create UpdatePlayerOptions
Like this?
So i have to Update it for both Creater and Joiner the same like this?
for the host its the allocation id you get from CreateAllocationAsync but yes
Yes
I tested it and it finally left the lobby 🙂
Thanks a lot @sharp axle for your time and help!
Does anyone have a good resource on developing a game using NetCode and also having it function with Steam ?
I want to have a multiplayer game that works properly with Steam accounts, invites, etc.
Netcode and steam are entirely orthogonal problems
They don't work well with each other?
They are unrelated
Ah, so is having both doable / reasonable?
Whether it’s reasonable depends on your team’s skill, budget, project scope and deadline
I'm diving into my first networking project, and want to publish it to steam later down the road, so I'm a noob. How does the process usually go?
- Code the entire game using Netcode?
- Then implment steam functionality?
Or should they be done at the same time
No team , it's all me 😄
Start small without any ambition of launching on steam in your first try
So you would suggest just developing using Netcode and then link it with steam?
try to finish anything that’s remotely fun and is multiplayer, then think about what you can do in your next project based on that experience
whether you integrate steam or any other platform is really not important
there is certainly stuff to learn regarding launching a game to a store and maintaining it, but those aren’t the hard part.
I'm getting this error for this script. Could someone explain what the error message means to me? I already added a Circle Collider 2D to the game object.
Argument needs to be Collider2D other
Argument?
Sorry, I'm new to Unity
Once you get the game closer to being finished, you can begin to implement Steamworks.net.
hey guys, what networking solution would u guys recommend? We are using Photon Quantum but we aren't sure it is the best option.
the deterministic system has some limitations
we are thinking about fishnet
Whatever is the best depends on the specifics of the project. No framework or even custom system can do it all.
Is Fishnet capable of developing a main scene like an MMO, with several rooms which players can join to play minigames?
That’s all custom code you can build on top of most frameworks
Quantum and Fusion give you a relatively turnkey solution for a very specific type of game. Other frameworks that are more open can serve a wider range of projects but also require more custom work. There is no framework that allows you to easily make an MMO. Most frameworks aim to be used in short lived matches (servers) of 2-16 players and provide no builtin support for complex data persistence.
thanks
Depends how fast you need which steam feature. If you only want to use them as a server host with steam lobbies, don't bother for a long time if you don't want to
If you want to make playtesting easy, this can allready be a point to buy it 50ish hours in the project
If you want to use different features as well (achievements, workshop,..) it will depend how fast you wsnt to implement these features
Even just playtesting makes it worth ir early on, if you are conmited to your project
Just the networking part is not too complicated tho
If you are commited to your project it just depends on how fast you can spare the 100 bucks steam wants
There is no right or wrong on when to implement it, that is project and goal specific
I'm glad I did it early on (implementing with appid 480: 50ish hours into the project, finally buying the appid: 100ish hours)
One pain point tho: you will need 2 machines to test your networking. You can't do it on one, that is something to keep in mind
Im having a problem where consistently using loadscene.single and than running SceneEventType.LoadEventCompleted I have players that often don't load in (note it doesn't happen for a while than once it happens for the first time it snowballs and happens more often could it be I missed a single networkObject in my list or is it something else idk pls help)
How do I make an image that is visible to the player as one image, but a different image to everyone else in the room? (Netcode)
I'm trying to make a multiplayer poker game, and I want the player to be able to look at their own cards, while the cards appear face-down to everyone else.