#archived-networking

1 messages · Page 18 of 1

rotund pilot
#

thankfully I believe this is gonna be the hugest headaches of things I don't know how to do for this project at this stage

rotund pilot
#

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

empty night
severe briar
#

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.

rotund pilot
#

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

severe briar
rotund pilot
#

lmao no worries, it's afternoon here

#

what you gave me was still helpful

severe briar
#

Okay. I'll look into it again.
In an hour or so.

rotund pilot
#

no sweat, take your time

river summit
#

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)

severe briar
#

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.

#archived-networking message

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.

severe briar
river summit
#

there will be animations but players wont be able to intentionally move

severe briar
#

So, it's some kind of pre start scene.

river summit
#

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

severe briar
severe briar
river summit
#

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...

empty night
river summit
#

dang

#

im lost

sand nimbus
#
    [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

severe briar
#

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.

rotund pilot
severe briar
sand nimbus
sand nimbus
# severe briar 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

severe briar
sand nimbus
#

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

severe briar
sand nimbus
#

no i just create a build and use the editor

sand nimbus
#

@severe briar any ideas?

severe briar
sand nimbus
severe briar
sand nimbus
sand nimbus
severe briar
sand nimbus
orchid helm
#

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 ?

sand nimbus
severe briar
severe briar
# sand nimbus ive fixed everything with the weapons and working right now. its just a little d...

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.

austere palm
#

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 ?

austere palm
#

and I see 9 connected lobbies when I start the game. When you quit the app it doesn't leave the lobby

rotund pilot
severe briar
# rotund pilot 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.

normal peak
#

Is netcode for gameobjects good for a casual game like halo

severe briar
# normal peak 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.

orchid helm
#

@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 ?

severe briar
orchid helm
#

thanks @severe briar

forest chasm
#

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?

severe briar
forest chasm
severe briar
forest chasm
#

inside the network manager script?

severe briar
#

No, create a new script called 'ClientNetworkTransform'
And use it

forest chasm
#

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?

severe briar
forest chasm
severe briar
# forest chasm 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.

forest chasm
forest chasm
#

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;
    }
}
severe briar
forest chasm
#

fixed it, just reimported all my porject files and it worked

forest chasm
# severe briar Try renaming the file and class

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?

forest chasm
severe briar
forest chasm
#

oh, sorry first time using that

severe briar
#

it's okay

forest chasm
severe briar
forest chasm
#

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

severe briar
severe briar
forest chasm
#

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

forest chasm
#

'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?)

severe briar
severe briar
forest chasm
#

where would this go up in class or in update

severe briar
forest chasm
#

okay no errors but still no flip. to google i go...

severe briar
forest chasm
severe briar
forest chasm
#

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

forest chasm
#

wait...

#

would i maybe need to to check the y rotation transform option in the network transform script..

severe briar
#

If you want to sync it - yes.

forest chasm
#

i didnt work 😦

severe briar
forest chasm
#

but still no flip

severe briar
sharp axle
forest chasm
sharp axle
# forest chasm 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 -

forest chasm
sharp axle
forest chasm
#
{
    

    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);

    
}```
sharp axle
forest chasm
forest chasm
sharp axle
forest chasm
sharp axle
forest chasm
#
     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

sharp axle
forest chasm
#

there is a network rigidbody

#

but i dont have any option for a client network rigidbody

sharp axle
#

oh its automatic if you use Client Network Transform

forest chasm
#

how do i get that?

#

if its that easy i will cry

#

wait i have a client network tranform already i read that wrong

sharp axle
#

yea. you'll need client network Transforma and Network Rigidbody

forest chasm
#

ive got them

sharp axle
#

ah crap. for non owners it gets set to kinematic. I think that screws with rb.velocity

sharp axle
#

check if your rb.velocity is 0

forest chasm
#

how? sorry

sharp axle
#

debug,Log()

forest chasm
#

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

rotund pilot
#

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?

sharp axle
severe briar
forest chasm
severe briar
forest chasm
#

yeah idk. its a step back for me, the code stop the animations that used to work now they dont

forest chasm
#

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

weak plinth
#

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)

severe briar
forest chasm
severe briar
# forest chasm 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.

forest chasm
severe briar
forest chasm
#

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

weak plinth
severe briar
forest chasm
#

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

severe briar
forest chasm
#

the game is really done almost i just need to implement lobby joining and hosting, fix the camera, and then finish level design

weak plinth
#

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)

forest chasm
#

if this helps

severe briar
severe briar
forest chasm
weak plinth
forest chasm
#

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

severe briar
weak plinth
#

i think its vsync

severe briar
forest chasm
#

how... i dont see a paste option on the prefab

severe briar
forest chasm
severe briar
forest chasm
#

is there a way to open a back up of the game?

#

i might of destroyed the prefab ..

severe briar
forest chasm
#

how do i know if i backedup?

severe briar
forest chasm
#

..dam

forest chasm
#

just to be sure i dont mess it up
double click the prefab

#

and just paste the MainCamera with components in the hierarchy

forest chasm
forest chasm
# severe briar Sounds right.

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?

severe briar
forest chasm
#

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

severe briar
# forest chasm

You should reference it first.

[SerializedField] private new Camera camera;

public override void OnNetworkSpawn()
{
    camera.enabled = IsOwner;
}
forest chasm
#

still same error

severe briar
forest chasm
#

wow im an idiot thank you

#

camera still swaps to most recent client

severe briar
forest chasm
#

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

severe briar
# forest chasm while here you can also see i havent fixed the sprite flip over network : )

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.

forest chasm
#

the OnNetworkSpawn() messes with code you gave me earlier

severe briar
forest chasm
#

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

severe briar
forest chasm
#

public gameObject Player;

#

Correct?

#

didnt work

severe briar
# forest chasm Correct?

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.

forest chasm
#

yeah i meant G

#

okay

teal cedar
#

Unity is confusing

teal cedar
#

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?!

sharp axle
teal cedar
#

And the script is on same object

wheat bramble
#

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?

broken bramble
#

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!

teal cedar
#
    [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!
green hollow
#

or try implementing blockchain technology

latent valve
#

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 ");

}```
regal oar
#

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:

  1. Cheap. I don’t have lots of money maybe like $75-$100 a year so something that’s not super expensive.
  2. Can hold 100+ ccu and around 2,000 total active users
  3. Has lots of tutorials. I’m a very visual learner so video tutorials help a lot.
  4. 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.
  5. 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!

severe briar
rotund pilot
teal cedar
#

Anyone knows where to find manual with all callbacks? Like Onclientconnectedcallback
Netcode for gameobjects

severe briar
teal cedar
severe briar
white ledge
#

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

alpine pulsar
#

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

shrewd junco
alpine pulsar
#

fully aware that for authortitative/sec reasons the server needs to do this, and what I'm asking for is a pointer on how

shrewd junco
alpine pulsar
#

yes

#

literally just need a way for the owner id to become the client id when the player connects, thats all, server side

alpine pulsar
#

thanks

fallow adder
#

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? kekW

sharp axle
terse drift
#

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?

fading quartz
#

Instead of a massively multy---

terse drift
white ledge
#

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

weak plinth
#

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

wide igloo
#

why is this not working

#

in english ""PlayFabClientAPI" does not contain a definition for "PlayFabId""
how can i fix that

slender plume
#

I need help with my lobby serivec to work

#

anyone could help me ?

scenic fulcrum
slender plume
#

help me to rebind controls in game pls

#

??

azure solstice
#

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.

slender plume
#

hello

#

need hlep with my hame

#

game

faint cedar
#

Hello, how can I disconnect the host and client connections?

sharp axle
faint cedar
#

Thank you

covert gull
#

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

wide girder
#

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

sharp axle
true palm
#

how can i activly update text? when i added ngo it didnt seem to work anymore.

covert gull
#

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

weak plinth
#

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();
        }
    }
}
daring halo
#

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?

stiff ridge
nimble nest
#

Hello I'm having a problem with photon

#

It sayis that PhotonTargets doesn't exist

#

Why?

humble ore
deft magnet
#

any simple network lib to use in C#? I don't want to use anything like mirror, I'll just need send/receive packet

covert gull
#

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

weak plinth
stiff ridge
#

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.

austere yacht
deft magnet
austere yacht
#

Something like riptide is fine if your sync is exceedingly trivial or infrequent.

#

But it provides zero convenience and guidance

deft magnet
#

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

weak plinth
#

what networking solution would you guys recommend for a multiplayer RTS with thousands of units? is there something with not too much overhead?

elder moss
#

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?

severe briar
weak plinth
severe briar
sharp axle
modest mantle
#

Hello. For example, I have a class "Player". He has some data. How will you replicate it? There are two options:

  1. Lots of network variables
  2. 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.
severe briar
# modest mantle Hello. For example, I have a class "Player". He has some data. How will you repl...

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.

severe briar
viscid sphinx
#

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

teal cedar
#

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());
}```
viscid sphinx
#

hey can anyone tell how to access <Set-Cookie> header in WebGl Build ?

weak plinth
#

can anyone show me how to fix laggy movement in multiplayer I am using Photon Transform View Classic And Here's the options :

#

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

severe briar
teal cedar
#

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

teal cedar
severe briar
teal cedar
#

Then throw set it and then server rpc spawns it

severe briar
teal cedar
#

On host it works fine

severe briar
#

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.

teal cedar
#

Okay, sorry for interrupting

teal cedar
sharp axle
teal cedar
#

I need server throw rpc to spawn it

#

In that case it is impossible to pass?

sharp axle
teal cedar
tardy crag
#

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.

teal cedar
#

@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?)

stiff charm
# teal cedar <@175082927862841344>

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

zinc sentinel
#

guys is anyone here good with photon?

teal cedar
# severe briar 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; 
}```
severe briar
teal cedar
severe briar
#

I just read the source code + Rider helps a lot.

teal cedar
#

In my source code I saw network prefabs though

teal cedar
#

¯_(ツ)_/¯

naive yoke
#

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());
}
}

}```

formal comet
#

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?

severe briar
formal comet
weak plinth
#

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?

sharp axle
cold estuary
#

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

cold estuary
dapper burrow
#

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.

sharp axle
light orbit
#

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.

light orbit
#

Or is it related with max packet size of NetworkManager of NGO?

azure crown
#

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.

burnt talon
#

I need help with photon

My Host Cant see the client

#

idk what is wrong i just started a series

#

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...

▶ Play video
fathom epoch
fathom epoch
#

Are u using a clone editor?

burnt talon
#

??

#

i am spawning a prefab

#

(the player prefab)

fathom epoch
#

How are u lauching the game for ur client is what I'm asking

burnt talon
#

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);
        }
    }

}

}

fathom epoch
#

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

burnt talon
#

thx

#

so am just gonna wait for someone to come and help me

#

...

burnt talon
#

...

#

..

#

.

sharp axle
oak flower
raw stormBOT
#
Posting code

📃 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.

oak flower
#

Also don't spam the channel, noone new will see that and you are just annoying the people who already did

azure crown
oak flower
teal cedar
#

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?

teal cedar
#

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?

cedar star
#

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

formal comet
#

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...

severe briar
formal comet
teal cedar
sharp axle
timid compass
#

Is NGO worth it or is Photon better? what do you guys think

sharp axle
teal cedar
shrewd junco
# teal cedar 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

teal cedar
shrewd junco
#

🤷‍♂️ 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

teal cedar
#

Yeah, like in apex you only see like 5 players max even though there is 64 transform in total

shrewd junco
stiff ridge
#

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.

teal cedar
teal cedar
sharp axle
#

Unity Transport can handle hundreds of connections but you will get cpu bound or bandwidth capped before you reach any theoretical player limit

teal cedar
exotic summit
#

Simple, solution just change to Mirror networking

formal comet
#

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?

sharp axle
white ledge
#

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?

spring crane
#

But to answer your question, your alternatives are HTTP and WebRTC.

burnt talon
#

hey

#

i just want to ask

#

Does X = = 1 is it right or left?

sharp axle
tough thorn
#

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)

bronze tendon
#

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.

white ledge
#

Okk so you are using JavaScript base websockets
That's a great approach I'll try it

sharp axle
# bronze tendon I have this code ```using System; using UnityEngine; using Unity.Netcode; using ...

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.

bronze tendon
#

thats also what i assumed. thanks!

marble brook
#

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?)

fringe flame
#

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

sharp axle
fringe flame
#

If 2 players
Event is fired two times

sharp axle
bronze grove
#

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);
    }
burnt talon
sharp axle
gleaming zenith
#

Im having a problem where consistently in scene placed network objects when switching scenes dont load for clients does anyone know why?

silk reef
#

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?

willow totem
#

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.

willow totem
#

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

GitHub

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

remote crown
#

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?

regal delta
#

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

fringe imp
#

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!

formal comet
sand nimbus
#

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

severe briar
# sand nimbus hey i have a strange issue this is my movement code for my 2d game ```csharp ...

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()'.

sand nimbus
#

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?

severe briar
sand nimbus
# severe briar The grenade should be spawned on the server. Then the server detects a collision...

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

sand nimbus
#

oh and this is what the explosion prefab looks like

severe briar
# sand nimbus

You didn't send the code ^

Does your script inherit 'NetworkBehaviour'?

jolly helm
#

Should Unity Transport encryption work with certificates created from an intermediate CA?

sand nimbus
severe briar
# sand nimbus My bad. https://hastebin.com/share/ofaborihud.csharp yeah it does habe NetworkBe...

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/

sand nimbus
# severe briar Rpcs would only work inside the 'OnNetworkSpawn' or 'Start' functions. > OnNetw...

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();
    }
severe briar
waxen quest
#

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

severe briar
waxen quest
#

Even tho they connected to same network

severe briar
waxen quest
#

Yes I tried this also. But it don't work

waxen quest
# severe briar I don't get what you mean by saying 'the ip changes' Like, of course they will h...
    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

severe briar
#

You should host the server using its local ip.
And then clients should enter this ip address to the input field to connect.

waxen quest
#

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

severe briar
crimson saffron
#

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...

▶ Play video
sand nimbus
willow radish
#

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.

severe briar
# sand nimbus sorry im still a little confused this is what i current have <https://hastebin....

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();
}
sand nimbus
# severe briar It's okay. So, I wrote that RPCs (ServerRpc, ClientRpc) should be called inside...

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

severe briar
vivid scarab
#

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?

sand nimbus
short umbra
#

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

sharp axle
supple sentinel
#

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)

fallow zenith
#

It's not filtered, is it?

#

although, there's only one filter available to me...

supple sentinel
frank dragon
#

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!

stuck totem
#

Im willing to make 3d models for games if anyone needs it

nocturne vapor
# frank dragon Hey! Not sure if this is too hard to set up but I'm trying to make a game where ...

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

robust falcon
#

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.

nocturne vapor
# robust falcon Hey all, I’m pretty new at this still and I’m trying to follow different tutoria...

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

robust falcon
#

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.

nocturne vapor
#

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

robust falcon
#

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 😂

nocturne vapor
#

yea just write a quick prototype, there is time for refinement later

sharp axle
robust falcon
frank dragon
sharp axle
frank dragon
sharp axle
wise fern
#

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

sharp axle
mortal blaze
#

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?

sharp axle
mortal blaze
tropic shoal
#

please help what i need put to LobbyMember?

nocturne vapor
short umbra
#

no worries if my IP is leaked

nocturne vapor
# short umbra Well I can actually afford this

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

short umbra
#

i want android and iOS

nocturne vapor
#

Not to mention the work of patching servers, maintaining them, keeping them secure and so on

nocturne vapor
# short umbra i want android and iOS

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

short umbra
#

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?

nocturne vapor
#

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

short umbra
#

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

nocturne vapor
#

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

short umbra
nocturne vapor
#

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, ...

nocturne vapor
short umbra
#

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$

nocturne vapor
# short umbra so it just does is calls the functions of the game written on a machine which ac...

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)

short umbra
#

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

nocturne vapor
#

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

short umbra
#

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

nocturne vapor
#

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

short umbra
#

Like i have a really good pc build

short umbra
#

and what should I actually do

#

?

#

or where to take a start

nocturne vapor
#

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

short umbra
#

ok thanks for the info

delicate parcel
#

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:

  1. 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.

  2. 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.

  3. 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?

nocturne vapor
delicate parcel
#

alright thanks!

desert lion
#

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

desert lion
#

got it working

jolly helm
#

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.

glass stirrup
#

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.

nocturne vapor
# glass stirrup Hello, I want to ask. I am pretty new in making multiplayer game. What if I want...

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

glass stirrup
#

Well for main menu it is global. For gameplay actually it is 1vs1 match

nocturne vapor
#

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)

glass stirrup
#

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

nocturne vapor
#

this is actually pretty easy then, just hardcode a connect to that server in your network manager

nocturne vapor
glass stirrup
#

Well if i need to handle multiple server maybe i need to get server list reference to player to choose then

nocturne vapor
#

you can always expand later, just get your game running in the first place ^^

glass stirrup
#

Yeah, actually I am not thinking of any advanced matter

nocturne vapor
#

of course that requires you to write scalable code and not spagheti code, but that shouldn't be something that needs to be mentioned

glass stirrup
#

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

nocturne vapor
#

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

glass stirrup
#

Ah, I never really try chatgpt.. maybe I will consider that for resource searching

nocturne vapor
#

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

fringe imp
#
    [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?
fringe imp
#

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>();
    }```
unkempt rapids
#

[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.

subtle sandal
#

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?

unkempt rapids
# unkempt rapids [RELATED TO NETCODE FOR GAMEOBJECTS] Hey all, I'm kind of stumped here... I made...

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:

mortal widget
#

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

hearty dock
#

What does it doesn't connect to servers mean exactly?
What happens when you try?
Are you encountering some kind of error?

mortal widget
#

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
#

and im sad

#

cuz i can't test my game

brave egret
#

Anyone got a Good Source where to learn how to Async Load with the Netcode for GameObjects?

shrewd junco
unkempt rapids
#

this does not happen with the host

#

it should only create like 1 joint

#

it's probably these if statements that are failing but i don't know why

shrewd junco
unkempt rapids
#

i tried to put the null check inside the createJointServerRpc but i got the same results

shrewd junco
#

the issue is not a null check

shrewd junco
# unkempt rapids i tried to put the null check inside the createJointServerRpc but i got the same...

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.

brave egret
#

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?

vapid roost
#

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)

mortal widget
#

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

neon yoke
#

@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.

brave egret
#

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?

sharp axle
sharp axle
brave egret
#

ahhh... Thanks

brave egret
#

But then i got another question, whats the Difference Between Authority and Ownership? isnt that... the same?

austere yacht
mortal widget
neon yoke
mortal widget
#

😭

#

out of nowhere

severe briar
brave egret
#

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

fallow adder
#

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

spring crane
frank dragon
#

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?

white ledge
#

Does Photon Fusion works like Unity Relay system?
or is it different?

austere yacht
#

Photon Fusion is a netcode framework not a relay service, but it can used with a relay service.

amber trench
#

do you have a budget?

nocturne vapor
#

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

bronze tendon
#

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?

sharp axle
bronze tendon
#

but how would i quickjoin a lobby with relay then

sharp axle
bronze tendon
#

that sounds like a simple solution. thanks

tiny galleon
#

Suggestion on Networking.. ??

sharp axle
tropic shoal
#

Hey anyone know how i can join in started game?

#

im using unity netcode and steam facepunch

fresh meteor
#

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.

sharp axle
desert lion
#

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

sharp axle
autumn whale
#

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?

mortal blaze
#

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)

midnight jolt
#

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 🙂

austere yacht
nocturne vapor
#

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

cinder mirage
#

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

regal oar
#

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

warped pilot
#

Hey is there a tutorial how to use new "Unity Player Accounts" for Unity Authentification ?

nocturne vapor
desert lion
#

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?

nocturne vapor
#

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

desert lion
#

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?

nocturne vapor
#

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)]

desert lion
nocturne vapor
#

No problem

nocturne vapor
#

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

desert lion
#

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?

nocturne vapor
# desert lion oh yeah i've only been doing local testing so far. i imagine it would feel bad t...

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;

desert lion
#

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);
    }```
nocturne vapor
#

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

desert lion
#

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;
}
nocturne vapor
#

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

desert lion
nocturne vapor
#

No problem

bronze tendon
#

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?

nocturne vapor
bronze tendon
sharp axle
bronze tendon
sharp axle
teal cedar
#

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

teal cedar
bronze tendon
teal cedar
#

Which version of unity you use?

bronze tendon
neon yoke
#

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?

teal cedar
nocturne vapor
nocturne vapor
# bronze tendon 2022.3 i think. Cant check right now

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

neon yoke
nocturne vapor
#

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

neon yoke
#

Yeah I agree I wanted to check if I was missing something. Thanks

neon yoke
#

@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.

sharp axle
bronze tendon
bronze tendon
#

i attached a debug.log to the if-statement. It does indeed print multiple times when in OnNetworkSpawn(), or in Start()

knotty timber
#

hi can anyone tell me why this is not running the generateSpawnPositions() or Invokerepeating methods. When I press server or host they dont run.

bronze tendon
sharp axle
knotty timber
#

@sharp axle ahh where should I do that check then?

sharp axle
knotty timber
#

@sharp axle awsome ty

clear jolt
#

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?

clear jolt
#

it seems I was using illegal networkvariable<int[]>, but anyone knows how to use the networkList, not finding any docs releated with this part

abstract copper
#

seems like you just use NetworkList<int> and add / remove from it like a normal list, no?

abstract copper
#

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[]>

clear jolt
#

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

abstract copper
#

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];
clear jolt
#

Cool this is so simple! When i refer to the doc, I thought I need to construct a struct like this

clear jolt
abstract copper
#

yeah they are just going overboard because they are showing how to make a custom serializable type

clear jolt
#

Really really thanks for this

#

I just thought I needed to revert back to that kind of nasty code structure

abstract copper
#

I mean, let me know if that actually works haha

#

I have never used Unity's NetCode

clear jolt
#

Everything works fine now, appreciate to this answer, this saves my day

abstract copper
#

Oh okay cool, perfect

clear jolt
#

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

clear jolt
#

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😂

knotty timber
#

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.

teal cedar
#

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)

tender storm
#

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

tender storm
sharp axle
tender storm
wooden vine
#

Hi! Is there anyway of destroying just one cell from a tilemap on network?

#

Currently my projectile basically destroy the entire tileset on collision

sharp axle
wooden vine
#

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

sharp axle
#

It will need to be a ClientRPC to let all the other clients know

nova linden
#

how do i find the object ? how does this even happen ?

wooden vine
desert lion
#

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();
    }
}```
desert lion
desert lion
#

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

karmic siren
#

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!

sharp axle
gleaming elm
#

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 !

nova linden
#

i cant find the vivox package in the package manager for some reason

pastel holly
#

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!??

sharp axle
nova linden
#

thank you

karmic siren
#

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.

rustic quail
#

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?

spring crane
rustic quail
spring crane
#

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.

sharp axle
spring crane
#

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

sharp axle
#

Personally I would just use the client id instead of a playerNumber variable

rustic quail
#

Thank you for the feedback. I'll go back to the drawing board.

waxen quest
#

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

waxen quest
waxen quest
sharp axle
waxen quest
nocturne vapor
#

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)

waxen quest
#

Lobby, Relay and NGO all

sharp axle
#

You have a bug somewhere. Relay is supposed to remove the lobby player when it disconnected

waxen quest
nocturne vapor
#

I could he wrong here I never used it, just posted it in case this is transferable

waxen quest
#

The player remains in lobby untill the lobby gets abandoned

sharp axle
#

So you have the allocation id set in the Lobby Player Data? That's how the integration works

waxen quest
#

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

waxen quest
waxen quest
#

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

sharp axle
waxen quest
#

But how I remove that player with allocation id?

sharp axle
#

Thats creating a new lobby. You need to update each player after they join

waxen quest
#

Yes I'll do it for both Join and Create

waxen quest
#

Idk how

subtle sandal
#

Nvm

#

I got another problem

waxen quest
# sharp axle Thats creating a new lobby. You need to update each player after they join

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?

sharp axle
waxen quest
sharp axle
waxen quest
#

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

waxen quest
subtle sandal
#

I solved my problem by using ServerRpc but it doesnt call the ServerRpc methods on the client

#

can someone help? :(

waxen quest
#

ServerRpc will only execute on server. There is this constructor you can use [ServerRpc(RequireOwnership = false)] so any client can send this

subtle sandal
#

how do I send code

waxen quest
subtle sandal
#

you sended this code field here

waxen quest
subtle sandal
#

"""

waxen quest
#

this symbol `

subtle sandal
#
 [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);
    }
waxen quest
#

yes

subtle sandal
#

and The console doesnt send the Debug.Log(); on the client

waxen quest
#

I am kind of new to NGO as well 😦

subtle sandal
#

ok...

waxen quest
#

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);
    }
}
waxen quest
waxen quest
waxen quest
#

Do the string in the allocation key should exactly be same as "AllocationId"?

sharp axle
#

No you should set it in options.AllocationId

waxen quest
sharp axle
#

nope. in options.AllocationId after you create UpdatePlayerOptions

waxen quest
#

So i have to Update it for both Creater and Joiner the same like this?

sharp axle
waxen quest
#

I tested it and it finally left the lobby 🙂

#

Thanks a lot @sharp axle for your time and help!

patent iris
#

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.

austere yacht
patent iris
austere yacht
#

They are unrelated

patent iris
#

Ah, so is having both doable / reasonable?

austere yacht
#

Whether it’s reasonable depends on your team’s skill, budget, project scope and deadline

patent iris
#

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?

  1. Code the entire game using Netcode?
  2. Then implment steam functionality?

Or should they be done at the same time

#

No team , it's all me 😄

austere yacht
patent iris
#

So you would suggest just developing using Netcode and then link it with steam?

austere yacht
#

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.

rustic quail
#

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.

austere yacht
rustic quail
#

Sorry, I'm new to Unity

austere yacht
sharp axle
rain lily
#

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

austere yacht
rain lily
#

Is Fishnet capable of developing a main scene like an MMO, with several rooms which players can join to play minigames?

austere yacht
#

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.

nocturne vapor
# patent iris I'm diving into my first networking project, and want to publish it to steam lat...

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

gleaming zenith
#

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)

rustic quail
#

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.