#archived-networking

1 messages · Page 22 of 1

austere yacht
#

Whatever are those two options?

crystal marlin
crystal marlin
# austere yacht Whatever are those two options?

In Unity, you typically create a new game object using the Instantiate function. Creating a game object with Instantiate will only create that object on the local machine. Spawning in Netcode for GameObjects (Netcode) means to instantiate and/or spawn the object that is synchronized between all clients by the server.

austere yacht
#

that said I could imagine situations where you need to break away from simple ‘everyone sees everyone’ model that’s the default in simple arena-style games or when you may need to worry about exploits.

crystal marlin
light holly
#

anyone? thanks in advance

summer otter
#

How can I prior set variables in NGO at server side to ensure they are accessible in OnNetworkSpawn at Client side?

tribal stream
#

Cool, what other free versions and resources are there?

#

Not that one ready for multiplayer support yet, I’m mostly curious

#

In particular at some point a game of mine will have online and I’ll need the help of my friends to debug online issues. Any advice for how to do that?

#

FYI I know absolutely nothing about this kinda thing

#

Any advice should be “networking for dummies levele”😂

sharp axle
# tribal stream Cool, what other free versions and resources are there?

Check the pinned message here for resources. All the solutions will have their own discord servers as well. You will need to decide on multiplayer from the very beginning or you are going to be rewriting all your code. You'll be using a Relay service to connect over the internet. Unity, Steam, Epic, and Photon all have their own services you can use for varying cost.

tribal stream
#

Glad I asked this now rather than waiting till the end like I had planned. Idk why but I thought that would be the hardest thing to implement. That would a set me back majorly.

#

Is there anything else like that that I need to be careful of?

#

I know it’s probably hard to answer considering you don’t know what I’m making . But Do randomly generated levels mess with online functions? Would I need to make keys and seeds as identifiers or something for each character?

#

My brain thinks that if it’s all random other player might load into the void or in the wrong place😅

#

Also I’m reading through it all. Does the “multiplayer play mode” not exist anymore? The page is missing

long marlin
#

How can I set the Tag of each player to "Enemy" unless its the local player? Using Pun 2/ Photon

sharp axle
tribal stream
tribal stream
#

Are seeds the only way to make identifiers fire greater worlds. Or is that the best used method?

#

It seems like it would be the simplest and best option, but I’m not sure what others exist and how or when they’d be chosen

#

If the game is Minecraft it’s probably the best use. But what about other games like animal crossing, spelunky and so on.

sharp axle
sharp axle
tribal stream
#

Like checking to make sure the player loading into the world is your friend and not some random who accidentally joined

#

If in testing among friends I meet I make sure I have a way to identify them and make sure no one else can get in.

#

Idk how games and networks do this other than with spending of number or password/key to identify “friends vs !friends”

#

I think that means I have to make some kind of friends list option or room codes like among us and animal crossing dodo codes

#

Unless I’m overthinking things again

long marlin
tribal stream
#

Ag I think I found a page 📄relevant.

#

Man in the middle attacks and security is my concern when testing with friends

#

How do I keep us all safe and ensure only a select specific few can test with me?

sharp axle
tribal stream
#

I haven’t found the friends system page about it but that’s good to know this

#

I’ll do some research and experiment with multiplayer first and make sure I get it safe before I start doing adding features.

“I’ll be back”😎

#

At some point eventually

tough loom
#

hey, i have a place in my multiplayer game where when you go there another scene loads additively normally when there are more than 1 player and someone goes there the new scene only loads for the player that entered that area.
but if the host enters the area before the others join. when they join the scene loads for everyone that joins after the host entered the area.
how do i fix that ?

austere yacht
tough loom
austere yacht
#

It’s certainly easier to not load scenes asnyc and do what you said.

tough loom
austere yacht
cold vine
#

I'm currently looking at https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.Get.html

this is the code:

public class Example : MonoBehaviour
{
    void Start()
    {
        // A correct website page.
        StartCoroutine(GetRequest("https://www.example.com"));

        // A non-existing page.
        StartCoroutine(GetRequest("https://error.html"));
    }

    IEnumerator GetRequest(string uri)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            string[] pages = uri.Split('/');
            int page = pages.Length - 1;

            switch (webRequest.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                case UnityWebRequest.Result.DataProcessingError:
                    Debug.LogError(pages[page] + ": Error: " + webRequest.error);
                    break;
                case UnityWebRequest.Result.ProtocolError:
                    Debug.LogError(pages[page] + ": HTTP Error: " + webRequest.error);
                    break;
                case UnityWebRequest.Result.Success:
                    Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
                    break;
            }
        }
    }
}

I would like to add a interface function to the IEnumerate:

public string GetRequest(string uri)
    {
        string response = StartCoroutine(GetRequest(uri));
        return response;
    }

But I can't figure out how to get a return value from IEnumerate, any advice?

fluid walrus
cold vine
#

aha okey ill check it out

crystal marlin
#

I have the following scenario, which I don't know how to handle:

Context:

  • I am using Kinematic Character Controller from the asset store to move my client authoritative players around, as well as plaltforms.
  • In order to move the platforms, and the players be able to be moved by them, I need to do the platform movement on the client side as well.

Let's say I have a platform that I need to move around the map, that needs to be able to move all players around (host + clients).

What I've tried:

  1. If I only move the platform on the server, and add a network transform to the platform, the client players will not get moved by it, since the physics mover also has to be ran on the client side.
  2. Have a network variable on the platform which the server updates. Lerp towards that from the current position on each client. Problem with this is that since the client has quite the delay like this, For the server it will appear that the client stands on thin air because the client thinks the platform is further back in time. And the client sees the server standing in thin air as well but ahead in time.

How do I fix this? Any ideas are much appreciated. Thanks!

tribal stream
#

like the home menu scene or some cutscenes?

empty night
#

I have a question for the pros , I have a trivia game I wanna add networking , I was close to completeing my task once with netcode for gameobjects but I also know that NGO is "overpowered" for a trivia game. my question is what is a more simple solution for making a trivia game multiplayer?

fluid walrus
sharp axle
tribal stream
#

kinda like that conversation example where someone tells someone to come here, but they dont know where here is

robust silo
#

Im trying to build a Unity Netcode app through XCode to my phone, but when I try to deploy with XCode, I get a few errors like:

/Users/sanderschulhoff/Unity/builds/Il2CppOutputProject/Source/il2cppOutput/Assembly-CSharp.cpp:4688:9 no matching function for call to 'NetworkBehaviour___beginSendRpc_mD9AE8C915F9ECD278DAF43F4A0FA318DEE1851D1'

I have tried 3 different unity versions and 2 different XCode versions, but can't figure it out. The app works fine if being deployed to desktop, and I havent found this error on the Internet. Any ideas?

robust silo
#

I have found that removing all [Rpc(SendTo.Server)] fixes it, but I need these Rpc calls.

sharp axle
# robust silo I have found that removing all [Rpc(SendTo.Server)] fixes it, but I need these R...

There is a github issue on this. Changing back to ServerRPC seems to be a workaround
https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/2817

GitHub

Description When building a project using [Rpc(SendTo.***)] with NGO 1.8.0, the build in Xcode fails with this error for every Rpc in the Project: buildPath/Il2CppOutputProject/Source/il2cppOutput/...

robust silo
#

Im not sure I can do ServerRPC unless I downgrade netcode

#

reading issue now

sharp axle
robust silo
#

I have spent days looking at these errors and scratching my head

#

Thanks again for pointing me here

tawdry night
#

does some1 know how to make a seprate ui for each player? i am using netcode

robust silo
tawdry night
#

no

tawdry night
robust silo
tawdry night
robust silo
tawdry night
#

u mean like work like normal?

robust silo
#

Yes

tawdry night
#

oh oke

robust silo
#

I said it like that bc it should just work as you expect it to

tawdry night
#

and player is a prefab soo anything for that

robust silo
tawdry night
#

u need to make the player a prefab to put in manager

#

so u cant asign ui to it that easy right?

tawdry night
robust silo
#

Hmm, I dont quite understand (also I have minimal Unity experience)

sharp axle
tawdry night
#

not on the single player way tho

tawdry night
sharp axle
crude ridge
#

I'm getting this error on the host whenever a client joins

terse idol
# crude ridge

I'm still learning but it might have to do with the networkTransform

crude ridge
#

but im not sure which one

#

or why its even causng it

#

cuz i didnt modify anything at all in the network transform, and yet its saying Object reference is null?

terse idol
#

Does it have a network object

crude ridge
#

yes

#
    [Rpc(SendTo.SpecifiedInParams)]
    private void ApplyGlassRpc(RpcParams rpcParams)
    {
        Debug.Log(IsServer);
        foreach (NetworkObject obj in chosen)
        {
            obj.gameObject.AddComponent<GlassPart>().glassBreak = glassBreak;
        }
    }```
why does isServer = true here, but then when i add the component and in the script in start function itry to print isServer, it's false
```cs
    void Start()
    {
        GetComponent<Collider>().isTrigger = true;
        
        Debug.Log(IsServer);
    }```
sharp axle
crude ridge
#

Even tho this isnt run on start

#

It's when its triggered

sharp axle
# crude ridge But the same issue happens in here: ```cs private void OnTriggerEnter(Collid...

Trigger events should happen on both server and clients.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/physics/

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

crude ridge
#

I'm trying to only detect it on the server tho

#

But the IsServer varaible is false there as well...

sharp axle
crude ridge
crude ridge
sharp axle
crude ridge
#

interesting

#

alr ig ill try that

tawdry lichen
#

Is it a bad idea to just set maxPlayers for a new allocation for Relay to 100 so that I don't have to update the limit if needed?
And updating would be stopping the Relay and then creating a new one with the updated number I guess right?

weak plinth
#

Can someone explain to me how it's possible in Unity Netcode (or in mirror) to have the server host multiple game instances (e.g. matches)?

austere yacht
#

You probably need to configure your servers via command line args or a config file to inject that port

#

Alternatively you can use a hypervisor to run virtual hosts or run each server inside a
(docker) container

weak plinth
austere yacht
#

It’s also how everyone from indie to AAA do it.l, meaning it scales excellently.

#

Only MMOs with large persistent shared worlds really need anything else

weak plinth
#

I see it working for indies, and most genres, but e.g. for an FPS where you have ~ players / 10 matches i can see issues with scaling
since my primary objective is to learn, i'll write my own netcode

sharp axle
wooden sky
#

i just use third party server providers since im lazy and kinda stupid

weak plinth
wooden sky
#

i use playfab and photon, which both have a 100k player limit before you have to pay

weak plinth
#

and you especially don't have to worry about optimization because it's already implemented, "bug free" for you

#

but tbh i'm convinced, i'm not going to write my own netcode in Go xD I mean if I had 2000 concurrent players, that's 200 processes, I'd argue that my game is already a blazing success, but in a much more realistic scenario I'd call myself lucky if i have monthly 200 players

sharp axle
#

Also just putting it out there that if you have less than 50 concurrent players 24/7 then the Relay service is completely free. Steam and Epics relay services are also free

bitter bough
#

How i can instantiate from client to client?

I have are server and two clients connect to him.

bitter bough
#

I don't understand how to make it possible for a client to create an object on a second client. If they are connected to the same server

sharp axle
bitter bough
sharp axle
# bitter bough I didn't understand the second part of the message, i.e. I can't create it in so...

Parenting a network object is kind of complicated
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/networkobject-parenting/

ServerRPCs will only get run on the server so you shouldn't be seeing that error. Make sure that this in on a Network Behavior.

A NetworkObject parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of NetworkObject components.

bitter bough
sharp axle
# bitter bough even if me remove the second parameter, the error remains the same

post the full code here. something is very wrong if clients are trying run a serverRPC. Do you have the [ServerRPC] attribute?
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/serverrpc/

ClientRpc and ServerRpc are legacy features of Netcode for GameObjects and have been replaced with the universal RPC attribute. This documentation is for legacy use. For current projects, use Rpc instead.

bitter bough
#

!code

raw stormBOT
sharp axle
sharp axle
sharp axle
#

is it already in the scene? or was it instantiated after the game started?

bitter bough
sharp axle
bitter bough
sharp axle
# bitter bough

Dunno. that message usually means the chat network behavior is not on a spawned object

crude ridge
#

so lets say i have a gameobject that i disable across the host/clients and then enable it 15 sec later via a coroutine. how do i sync this to new players joining? because if they join after i send the rpc to disable the gameobject, it will still be visually enabled on their screen

sharp axle
crude ridge
sharp axle
crude ridge
#

This is what my current script for the object looks like

#
    void Start()
    {
        GetComponent<Collider>().isTrigger = true;
    }

    private void OnTriggerEnter(Collider other)
    {
        if (IsServer && other.gameObject.GetComponent<Player>() && GetComponent<MeshRenderer>().enabled)
        {
            DestroyGlassRpc();
        }
    }

    [Rpc(SendTo.ClientsAndHost)]
    private void DestroyGlassRpc()
    {
        GetComponent<MeshRenderer>().enabled = false;
        GetComponent<AudioSource>().Play();

        StartCoroutine(RespawnGlass());
    }

    private IEnumerator RespawnGlass()
    {
        yield return new WaitForSeconds(15);

        GetComponent<MeshRenderer>().enabled = true;
    }```
sharp axle
crude ridge
#

Ah

#

Alright

bitter bough
#

When I send a message, a strange error pops up, I don't understand why I want to change the msg variable

sly scroll
#

does anyone have a simple rigidbody2d prediction script that I can add to my game (i'm using NGO). I'm trying to make a quick demo and don't really have the time to research my own. I know it would just be a component extending the networkrigidbody2d component.

sharp axle
#

If you just need it client authoritative, then you can add a client network transform to it

signal bone
#

Is it a guarantee that network variables will eventually be synced?

#

in my game a network variable int for health sometimes stays at 1 even though on the server the value is less than zero

#

so the death action on the client doesn't trigger

#

and even after a while the value never updates to the server value

#

like this

sharp axle
signal bone
#

and even when i wait 10 + seconds the value of health stays at 1 despite the value on the server definately being less than 1

#

wait

#

nvm

#

I'm pretty sure the value does change to 0

crude ridge
#

If I have a gameobject that is disabled in a scene by default is there an easy way to enable it across all clients/server when needed?

sharp axle
sharp axle
signal bone
#
public void OnHealthChanged(int previous, int current)
{
    HealthBarText.text = current.ToString() + " / " + MaxHealth.ToString();

    if (current <= 0)
    {
        Dead = true;

        transform.position = GameManager.Singleton.GetGraveyardLocation();

        if (!IsServer)
        {
            return;
        }

        Invoke(nameof(Respawn), 7);

        return;
    }

    if(previous <= 0 && current > 0)
    {
        Dead = false;

        transform.position = GameManager.Singleton.GetSpawnLocation(Team);
    }
}
crude ridge
signal bone
#

this is the onrep for the health network variable

austere yacht
crude ridge
sharp axle
crude ridge
#

Hmm. I think I migth just make it a prefab and spawn it into the scene whenever I need it

sharp axle
#

Yea. In scene objects are not meant to be despawned dynamically anyways.

austere yacht
crude ridge
#

I don't, I just thought it would be easier, but a prefab system for this might be cleaner anyway

#

Wait if I want to spawn a prefab do I have to add it to some kind of list? Or can I just do it with the instantiateandspawn function?

#

I think that was added in the latest version

#

Oh shoot

#

How am I supposed to have another script thats meant to handle networking things on my networkmanager gameobject?

sharp axle
crude ridge
#

Looks like one of these was already created

sharp axle
#

If you are adding a prefab at runtime then that's a bit more complicated

crude ridge
#

Wdym adding at runtime?

sharp axle
crude ridge
#

Oh

#

Anyway why can't add I add variables to my custom network manager that appear in the inspector?

sharp axle
crude ridge
#

Whatever, I just made a game manager network object and now that's fine

#

But I try to spawn my prefab and I get this error

#

Spawning NetworkObjects with nested NetworkObjects is only supported for scene objects. Child NetworkObjects will not be spawned over the network!

#

And

#

ArgumentException: NetworkObjectReference can only be created from spawned NetworkObjects.

#

Can I just loop through all of the network objects and spawn them?

sharp axle
crude ridge
#

Crap

#

Idk how I can make there only be a root object for the network object

#

I have like a million network objects

#

So I have the root which has a network object and script, but then I have a bunch of the same parts as children with a network object and script

#

The root script requires network object references for the children with the script

#

And the script on the children also requires network object

#

Looks like the scripts on the children themseleves don't need objects

#

A NetworkBehaviour requires a NetworkObject component on the same relative GameObject or on a parent of the GameObject with the NetworkBehaviour component assigned to it.

#

But how am I supposed to pass references to the children? Rn I use networkobject reference

sharp axle
crude ridge
#

So like I used to have networkobjects on the child

#

and in an RPC I would pass the networkobject reference as a parameter because I wanted server/clients to be able to modify the same gameobject

#

now If I remove the network object from the child

#

The networkobject refernece doesn't work

#

and I can't use gameobject as a paramter in rpc

sharp axle
crude ridge
#

Like when they were in the scene when building

crude ridge
sharp axle
crude ridge
#

Is there a reason why u wouldnt want the biggest one?

sharp axle
crude ridge
#

Ah

#

So FixedString4096 has a max length of 4096 charatcterS?

sharp axle
crude ridge
#

Got it

#

Also, do you know of any other way that I can send references to gameobjects via rpc or network variable/list without like an index?

#

That's the main thing I'm struggling with right now

#

I saw that unity has some kind of instance id for gameobjects, but idk if those are the same across all clients

#

And how I could find gameobjecgs based on it

mint anvil
#

quick (stupid) question, when dealing damage to another player i always call a serverrpc, is that correct? it feels kind of wrong calling the server every time to deal damage to any player

sharp axle
crude ridge
#

So those are regular gameobject lists?

sharp axle
sharp axle
crude ridge
#

I see

#

Btw, is there a list or something of all players with prefabs?

#

Because rn to get the player with their associated gameobject prefab based on their client ID, i have a dictionary of clientid and gameobjects that i add to when a player prefab is created and delete from when a player leaves

#
public Dictionary<ulong, Player> players = new Dictionary<ulong, Player>();```
#

im wondering if theres a better way to do this

sharp axle
crude ridge
#

Ah okay thats fine

#

I only need it on server anyway

#

One more thing, I've noticed that even tho my network manager is a singleton, it doesn't have a feature built in that will make it delete other network managers if i go back to a scene where it was created. is this on purpose or a bug?

#

since if i dont have an if statement to check if the singleton variable was already assinged, there would be 2 network managers

#

i have to manually delete if the singleton variable was already assigned

mint anvil
sharp axle
mint anvil
#

another quick question: i want to send a server rpc to spawn an object, but i want to set the "spawned" object to the spawned object variable on the client and not the server (same with the isSpawned bool) how can i do that?

[ServerRpc(RequireOwnership = false)]
void SpawnServerRpc(int PrefabId)
{       
        GameObject prefab = NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs[PrefabId].Prefab;
        spawned = Instantiate(prefab , spawn.position, spawn.rotation);
        spawned.GetComponent<NetworkObject>().Spawn();
        spawned.GetComponent<Health>().Team.Value = Team.Value;
        isSpawned = true;
}
sharp axle
# mint anvil another quick question: i want to send a server rpc to spawn an object, but i wa...

You can send an Network Object Reference back to the client if you need to. But if this object is going to be owned by the player then you should probably use SpawnWithOwnership()
Also, the Network Object already has a .IsSpawned field you can use
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/serialization/networkobject-serialization/

Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects

mint anvil
sharp axle
sly scroll
mint anvil
sly scroll
#

is that possible or would that require implementing an entire client prediction system like u mentioned

tribal stream
#

i just completed all the steps on here and got it to do the circular spinny thing its supposed to do when its done correctly. https://docs-multiplayer.unity3d.com/netcode/current/tutorials/get-started-ngo/

i have no idea what to do next tho, the next pages don't seem like anything i need to do just more generalized advice for things i can do.

Use this guide to learn how to create your first NGO project. It walks you through creating a simple Hello World project that implements the basic features of Netcode for GameObjects (NGO).

#

i'm not sure where to go from here. but i'd like to add my player prefab thing onto an actual model i've rigged. is it too soon for that?

sharp axle
sharp axle
tribal stream
#

ohh, i had just discovered them the other day or so

#

i'll go take look and see

mint anvil
sharp axle
tribal stream
mint anvil
tribal stream
#

when i googled code monkey the first one popped up

#

so i was a bit confused at first

mint anvil
#

same

#

last question for today, i promise xD so, in my strategy game, shouldn't i just disable the code on the clients? for example the ship movement is simulated on the server and has network transforms, so no need to also run it on the client right? just sync the waypoints and targets that the players set?

sharp axle
mint anvil
sharp axle
sharp axle
mint anvil
#

if older rts didn't use that and worked fine then what have they done
(the game my game is inspired of is from 2006)

sharp axle
mint anvil
sharp axle
mint anvil
#

i really want to know what the original game did

#

because it worked fine

#

it used lockstep tho

#

i know that because i got so much desyncs

#

i think just to set targets/waypoint will have a delay in my game... but idk how to do that rollback stuff so ... yeah
i have no money for a server so the problem will be it's just players as the server/host

sinful tendon
#

Good morning, I'm trying to connect my firebase realtime database to my Unity project but I'm getting this error:
I even tried to add reference to my db using GetInstance and a url still didn't work, here's how I reference the db:

FirebaseDatabase.GetInstance("url");
dbRef = FirebaseDatabase.DefaultInstance.RootReference;
sinful tendon
#

I got it fixed, had to go to my google-services.json file and add the following: "firebase_url": "my url", dependency

tribal stream
#

idk if this is a noob question or not, but after i get the netcode all set up can i export all that, like the scene settings and scripts so i can just re-import that into future multiplayer games i make?

and if so is it as simple as just ziping it all up or do i have to build it?

crude ridge
#

is there a reason that only my host player gets moved to the new spawn position and not the client?

        foreach (ulong id in CustomNetworkManager.Singleton.ConnectedClientsIds)
        {
            Transform spawn = GetRandomSpawnPoint("GamePoint");
            GameObject plr = CustomNetworkManager.Singleton.ConnectedClients[id].PlayerObject.gameObject;

            plr.transform.position = spawn.position;
            plr.transform.rotation = spawn.rotation;
        }```
sharp axle
sharp axle
crude ridge
sharp axle
# crude ridge Yes

Only the owner can move the player in that case. So you would need to either change ownership temporarily or send an RPC

sharp axle
crude ridge
#

I assume its osmething like

#

GetComponent<NetworkObject>().RemoveOwnership();

move to position

GetComponent<NetworkObject>().ChangeOwnership(clientId);

sharp axle
crude ridge
#

I see

#

How do I wait a tick 😳

sharp axle
crude ridge
#

Ah

carmine lichen
#

Im using the Simple FPS template in Photon, when i run it, it says i need to have a connection plugin assigned. Where do i find that? I dont see a connection plugin to assign

mint anvil
#

hello again,
so in my fps, if i hit an enemy i run code to deal damage (ifServer local, if not send a serverrpc)
if the health is 0 i want to run Kill() on the player, but how do i do that? if i do it like the damage dealing it doesn't work.
my brain can't just not think that far yet i guess 💀
(the server can't kill clients i think.. it's just not working.. maybe the damage code is wrong too idk)

 public void GetDamage(int damage)
    {   
        
        if (health.Value >= 0)
        {
            if(IsServer)
            {
                health.Value -= damage;
            }
            else
            {
                GetDamageServerRpc(damage);
            }
        }
        else if(health.Value <= 0)
        {
            
            if(IsServer)
            {
                Kill();
            }
            else
            {
                KillServerRpc();
            }
            
        }
        UpdateHealthBar();
    }

    [ServerRpc(RequireOwnership = false)]
    void GetDamageServerRpc(int damage)
    {
        health.Value -= damage;
    }
    [ServerRpc(RequireOwnership = false)]
    void AddHealthServerRpc(int healing)
    {
        health.Value += healing;
    }



    [ServerRpc(RequireOwnership = false)]
    void KillServerRpc()
    {   
        health.Value = maxHealth;
        Respawn();
    }

    void Kill()
    {
        health.Value = maxHealth;
        Respawn();
    }
sly scroll
#

hey i just switched my NGO game to webgl, and after updating the transport and my code to use wss, i'm getting a bunch of wierd errors in relation to some jobs:

System.IndexOutOfRangeException: Index 0 is out of range of '-1' Length.
This Exception was thrown from a job compiled with Burst, which has limited exception support.
0x00007fff34dfc9a9 (cc720dfe2700bd1c79b2915b24328f8) Unity.Collections.NativeArray`1<long>.FailOutOfRangeError (at G:/Unity/NGODemo/Library/PackageCache/com.unity.burst@1.8.11/.Runtime/unknown/unknown:0)
0x00007fff34e0d9d3 (cc720dfe2700bd1c79b2915b24328f8) Unity.Networking.Transport.NetworkDriver.InternalUpdate (at G:/Unity/NGODemo/Library/PackageCache/com.unity.burst@1.8.11/.Runtime/Library/PackageCache/com.unity.transport@1.4.0/Runtime/NetworkDriver.cs:914)
0x00007fff34e0af36 (cc720dfe2700bd1c79b2915b24328f8) f00744ec48cd0864aed85ed9873e2356
0x00007ffe9ed45545 (Unity) ExecuteJob
0x00007ffe9ed46890 (Unity) ForwardJobToManaged
0x00007ffe9ed4290b (Unity) ujob_execute_job
0x00007ffe9ed41ec1 (Unity) lane_guts
0x00007ffe9ed44864 (Unity) worker_thread_routine
0x00007ffe9ef03e25 (Unity) Thread::RunThreadWrapper
0x00007fff657b257d (KERNEL32) BaseThreadInitThunk
0x00007fff67a8aa58 (ntdll) RtlUserThreadStart

theres a few others, but im just wondering what this is. my project seems to work fine but is there something i forgot to do after switching to webgl?

crude ridge
#

Can you not do private NetworkList<int> chosen = new NetworkList<int>();? I'm reading it will lead to memory leaks apparently?

#

Instead your apparently supposed to only initiliaze it in awake?

sharp axle
sharp axle
sly scroll
#

thanks. that just reminded me that i completely forgot to switch to the relay transport

crude ridge
# sharp axle That's right. in Start() or Awake()

I see. I thought moving initlization into awake would fix it, but im still having an issue where my int networklist has a bunch of items, but they are like all weird? the server adds either 1 or 0, but then on the client it reads like 213213213, -1234, etc...

#

very weird numbers

sly scroll
#

additionally, the game seems to work fine on its own, bbut when trying to have multiple players, the network manager doesnt spawn the player prefab for each player

crude ridge
sly scroll
#

yup. thats what i meant when i said updating my code to use wss

crude ridge
#
        foreach (Transform section in sections)
        {
            List<Transform> glass = new List<Transform>();

            foreach (Transform trans in section)
            {
                glass.Add(trans);
            }

            chosen.Add(Random.Range(0, glass.Count));
        }

        ApplyGlassRpc(RpcTarget.ClientsAndHost);

        CustomNetworkManager.Singleton.OnClientConnectedCallback += plrID =>
        {
            ApplyGlassRpc(RpcTarget.Single(plrID, RpcTargetUse.Temp));
        };```
#

How can I modify that code so that I can wait for the network variable to be updated before I send out the Rpc?

#

Networklist is the chosen variable btw

sharp axle
sharp axle
crude ridge
sly scroll
#

im using lobbies

crude ridge
#

Ig I could try OnListChanged , but if im adding a bunch of elements to the list on the server, wont the client get a bunch of events for list updated?

#

I would only want it to be notifed when the final element is added

sharp axle
crude ridge
#

Ah

#

Alr, lemme try it out

sharp axle
sly scroll
#

no. i actually managed to fix that part, but im still getting the errors

crude ridge
# sharp axle It will only update once per tick.

Sadly it looks like the event is called multiple times, which is what I feared. What I might try doing is making a temp networklist, add all the items to it, and then set the global networklist to the temp one

#

Looks like that doesn't work either

#

Prob since I can't do smt like this NetworkList<int> test = new NetworkList<int>();

void jolt
#

What is your favorite network platforms like photon pun and mirror

crude ridge
#

Idk if it's really production ready tho

#

But at least we have lord @sharp axle to help us out 😂

sharp axle
crude ridge
#

Oh interesting I didn't know that

sharp axle
#

Also the UGS services are framework agnostic so you use ohoton or mirror with them just fine.

sharp axle
crude ridge
#

can I do smt like networkList = new NetworkList<int>(regularList);?

sharp axle
crude ridge
#

Looping through the old one anywya

sharp axle
crude ridge
#

Wdym per frame?

#
    void Awake()
    {
        chosen = new NetworkList<int>();

        chosen.OnListChanged += changeEvent =>
        {
            Debug.Log("list changed!");
        };
    }```
#

in another functiuon being run on the server:

#

        foreach (Transform section in sections)
        {
            List<Transform> glass = new List<Transform>();

            foreach (Transform trans in section)
            {
                glass.Add(trans);
            }

            chosen.Add(Random.Range(0, glass.Count));
        }```
crude ridge
sharp axle
crude ridge
#

ive been testing only on host

#

let me try it on the client 🥱

#

yup it also happens on the clients

#

In any case, I was able to come up with a different way to accomplish the same thing using numeros events

#

So for now this issue is solved

lime gale
#

in 2024 which toturial i should start for networking in unity engine ?

spare tapir
#

I have a question: I was following a tutorial that making game server. The chapter 6 example has render manager and it is peer to peer. But the chapter 8's example is a Server-Client model without render manager. So I'm thinking how to debug and check the sent and received msg from client in the case of chapter 8? The tutorial doesnt mentioned it.So I'm kinda confused.And advice?

#

What is the program like that put in dedicated-server? Is that an exe? Does it has any render or window? How do I debug it?

sharp axle
sharp axle
sharp axle
mint anvil
sharp axle
mint anvil
sharp axle
mint anvil
sharp axle
subtle tulip
#

NullReferenceException: Object reference not set to an instance of an object
Photon.Pun.PhotonTransformView.Update () (at Assets/Photon/PhotonUnityNetworking/Code/Views/PhotonTransformView.cs:61)

subtle tulip
spare tapir
sharp axle
spare tapir
#

Thx!I c

#

Another questeion : Why do we need bit stream when read and write the pack? Is it possible to make a bit stream system in C#? What about BitConverter Class?

#

Any cases that write some bits to pack like 5 bits or 13 bits instead of byte(8 bits)?

#
                                      uint32_t inBitCount )
{
    uint32_t nextBitHead = mBitHead + static_cast< uint32_t >( inBitCount );
    
    if( nextBitHead > mBitCapacity )
    {
        ReallocBuffer( std::max( mBitCapacity * 2, nextBitHead ) );
    }
    
    //calculate the byteOffset into our buffer
    //by dividing the head by 8
    //and the bitOffset by taking the last 3 bits
    uint32_t byteOffset = mBitHead >> 3;
    uint32_t bitOffset = mBitHead & 0x7;
    
    uint8_t currentMask = ~( 0xff << bitOffset );
    mBuffer[ byteOffset ] = ( mBuffer[ byteOffset ] & currentMask ) | ( inData << bitOffset );
    
    //calculate how many bits were not yet used in
    //our target byte in the buffer
    uint32_t bitsFreeThisByte = 8 - bitOffset;
    
    //if we needed more than that, carry to the next byte
    if( bitsFreeThisByte < inBitCount )
    {
        //we need another byte
        mBuffer[ byteOffset + 1 ] = inData >> bitsFreeThisByte;
    }
    
    mBitHead = nextBitHead;
}``` This is the code that in the sample project write in C++. The project C++ server and C++ client. I wanna move some basic part of client to C# and make game with Unity.
#
    {
        uint nextBitHead = mBitHead + inBitCount;

        if(nextBitHead > mBitCapacity)
        {
            ReallocBuffer(Mathf.Max(mBitCapacity * 2, nextBitHead));
        }

        uint byteOffset = mBitHead >> 3;
        uint bitOffset = mBitHead & 0x7;

        byte currentMask = (byte)~(0xff << (int)bitOffset);
        mBuffer[byteOffset] = (byte)((mBuffer[byteOffset] & currentMask) | (inData << (byte)bitOffset));

        uint bitsFreeThisByte = 8 - bitOffset;

        if (bitsFreeThisByte < inBitCount)
        {
            mBuffer[byteOffset + 1] = (byte)(inData >> (byte)bitsFreeThisByte);
        }

        mBitHead = nextBitHead;
    }``` This is what I convert to C#. Am I doing right? Or maybe not nesecessary to do this? I'm not sure... Any suggestions?
calm fulcrum
#

at what point should i start learning networking

sharp axle
waxen quest
#

The unity Netcode sometimes spawn players in Vector3.zero position.

Even I debugged and checked passed position but still many times it just spawns player to zero position.

I tried it with SpawnAsPlayerObject and InstantiateAndSpawn

Both do same thing.

Can someone help me fix rhis

waxen quest
#

Sure

#

I calculate random pos and rot and pass it in here. I debugged and it always passes non zero pos and rot. But Unity SOMETIMES spawns player in zero

    public void SpawnClient(ulong clientID, Vector3 pos, Quaternion rot, bool isClientOwner)
    {
        if (isClientOwner)
        {
            NetworkObject.InstantiateAndSpawn(
                playerPrefab,
                NetworkManager,
                clientID,
                destroyWithScene: true,
                true,
                forceOverride: true,
                pos,
                rot);
        }
        else
        {
            NetworkObject.InstantiateAndSpawn(
                playerPrefab,
                NetworkManager,
                NetworkManager.ServerClientId,
                destroyWithScene: true,
                false,
                forceOverride: true,
                pos,
                rot);
        }
    }
#

@crude ridge here

crude ridge
#

where do you call SpawnClient from?

waxen quest
#

Its called in my Random Pos and Rot calculator script. But the issue is in this one. Because the debug comes correct inside this

#
spawnPoint = new Vector3(x, hit.point.y + player_spawn_height_offset, z);
        
Utils.DebugLog("[SERVER] Spawning client " + clientID + " at spawnpoint " + spawnPoint + " found in " + attempts + " attempts");

        Quaternion rotation;

        if (randomRotation)
        {
            rotation = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
        }
        else
        {
            rotation = fixedRotation;
        }

        SpawnClient(clientID, spawnPoint, rotation, true);

crude ridge
#

why do you pass in NetworkManager as a parameter?

#

these are all the paramters of the InstantiateAndSpawn function

waxen quest
crude ridge
#

InstantiateAndSpawn(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)

waxen quest
#

Yes i am using that thats why

#

I even tried it with SpawnAsPlayerObject and behaviour is same in both

#

It only does it Sometimes not all the time

#

The player snaps to zero position

#

sometimes

waxen quest
crude ridge
#

umm thats weird, i dont think thats the correct function. is this in the networkmanager?

waxen quest
#

is this correct?

#

So there is also other method

NetworkManager.SpawnManager.InstantiateAndSpawn(
    playerPrefab.GetComponent<NetworkObject>(),
    clientID,
    destroyWithScene: true,
    isPlayerObject: true,
    forceOverride: false,
    pos,
    rot);
#

Can anyone explain forceOverride in simple terms.

#

"forceOverride": Whether you want to force spawning the override when running as a host or server or if you want it to spawn the override for host mode and the source prefab for server. If there is an override, clients always spawn that as opposed to the source prefab (defaults to false).

spare tapir
#

When to use bit level to read and write packect in network?

teal cedar
#

Damn, will be NGO over suitable for fast - paced games like FFS shooters or I am forced to wait until Dots is production ready and then use netcode for entities

vital sapphire
#

Is there any way to make networking work for LAN networks (so for devices connected on the same wifi network) without any relay or lobby? Any good tutorials? I have followed a few threads here and there but it doesnt work and I feel i'm not googling correctly cuz I dont get many clear answers

waxen quest
waxen quest
normal cedar
#

now i "just" gotta figure out the ipv4 adress

waxen quest
#

I do set Joiner client address same as host but it still does not connect

#

it just stuck on Start Client

#

and does not get connected to host

sharp axle
spring pilot
#

hey guys, does anyone know of a VoIP solution that uses the games host/server to host the VoIP locally instead of on an outsourced server somewhere else? I'm a bit concerned about running up a bill for hosting VoIP servers and was wondering if people could just do it themselves while hosting games :/

teal cedar
sharp axle
teal cedar
sharp axle
teal cedar
spring pilot
#

hey guys, is there a way to RPC audio clips for a voice chat solution?

vital sapphire
normal cedar
vital sapphire
normal cedar
#

honestly maybe but i do not know if it is worth it

spring pilot
spring pilot
#

or 25 server ticks

sharp axle
spring pilot
normal cedar
sharp axle
#

Vivox has a rather crazy 5k CCU free tier

sharp axle
spring pilot
#

I mean

#

say if I have 4800 Hz audio

#

to save money

vital sapphire
sharp axle
spring pilot
#

its just kinda internally frustrating to know that my game is dependant on a proprietary doohickey tho :/

normal cedar
#

just have a field you can copy paste the IPv4 address of the host and connects that way

#

unity just screams at me the endpoint / server adress is invalid

#

oh figured out small mistake, I was pasting the IP from discord and it had a "newline" thingy after it hence why the IP was invalid

#

still not able to join though, failed to connect

sharp axle
normal cedar
#

Networkdiscovery was for the new depricated Unet no?

#

when i clicked on it i also saw this so i thought it was UNet specific

#

while im using unity transport

sharp axle
normal cedar
#

oh shoot lemme check it out ^^

#

thanks upfront

#

Shouldve looked at it sooner! the server discovery works excellently

#

though my friend hosting still is not working

#

I'll just leave it as a firewall thing and wait with it until i can try out on someone elses computer 😅

#

Thanks still though

vital sapphire
#

apparently my laptop is the problem, we got another person to test and it works on their laptop as well

normal cedar
#

the rage within me

#

only a couple hours tho 🙏

tame valley
#

What is the best way to initialize Player network objects spawned with dependancies? NetworkManager spawns Player, but what if my player has a dependancy for ActionController, I don't want to create multiple ActionController objects for each object spawned (ie having it as component), I just want to have a single instance and just inject the dependancy where I need it

TLDR; Whats the best practice to inject dependancies into Player gameobject which gets spawned through NetworkManager

Should I just use Zenject for DI, and not think about it?

fluid walrus
sharp axle
alpine crescent
#

I have an application based on firebase database, now I want to change the database of this existing project. I already replaced the json file with my new one i created. The leaderboard is clear when i open the game but now after i play the scores and names don't get updated.

waxen quest
#

It's been months and I haven't figured out

sharp axle
#

But I had thought that particular bug of it being one frame at origin had been fixed.

waxen quest
#

Yeah that's the only work around for now

waxen quest
#

This is happening in Host

sinful tendon
# alpine crescent please can you elaborate?

Sure, the google-services.json file you import into your project may have a missing dependedncy, so under "project_info" object you add "firebase_url": and specify your firebase realtime database url

summer otter
#

Is it not possible to use an Interface for NetworkSerializable Data? I Got this Interface : public interface ITriggerData : INetworkSerializable and a concrete Implementation public struct MouseClickData : ITriggerData which implements public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter. But When I try to use it in my ServerRPC I got this failure: error - HandleActionRequestServerRPC - Don't know how to deserialize binrev.ITriggerData. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. Why? BTW, ITriggerData is empty, contains nothing.

fluid walrus
summer otter
#

Ok, that's an argument.

vale basin
#

I had this working for multiplayer before but now that I've added propper character movement (not just wasd) it does this

mint anvil
#

uh it's me again, i have a shipai movement script with an interface for mod support and stuff
mod interface:

     NetworkVariable<Vector3> Waypoint { get; set; }

ship ai script:

public NetworkVariable<Vector3> waypoint = new NetworkVariable<Vector3>(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);

    public NetworkVariable<Vector3> Waypoint
    {
        get { return waypoint; }
        set { waypoint = value; }
    }

but i can't change the waypoint in my selector script:

mod = ship.GetComponent<Mod>();
mod.Waypoint.Value = newWaypointPosition;

i get an error

NullReferenceException: Object reference not set to an instance of an object
Unity.Netcode.NetworkVariable`1[T].set_Value (T value) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.6.0/Runtime/NetworkVariable/NetworkVariable.cs:65)

again, maybe i am just dumb.

sharp axle
mint anvil
sharp axle
sharp axle
#

You can install 1.8 by name in the package manager and specify the version

spare tapir
#

I have a byte array declared as private in MyUDPClient.cs. I think I shouldnt declare it as public? I have another BitStream.CS trying to access the array and convert it to bits. But I can't since it's private. I'm confused how to design it...

analog tide
#

I have a question how do I execute a commande for all my clients ? When I am the host ?

sharp axle
analog tide
#

If I send a clientrpc then if I put the value in a playerprefs I can use it after with the right playerprefs name ?

#

How do I call a clienrpc btw ?

sturdy cloak
#

Host acts like a client and a server so if the host calls a client rpc it will broadcast the message to itself and other clients.

A clientrpc can only be called by a server. But Clients can trigger server rpcs that will trigger a clientrpc.

There is some example code if you want at this link:https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/message-system/clientrpc/

ClientRpc and ServerRpc are legacy features of Netcode for GameObjects and have been replaced with the universal RPC attribute. This documentation is for legacy use. For current projects, use Rpc instead.

analog tide
#

Thank’s a lot for telling me all this I was a bit lost because it’s my first time

analog tide
#

@sturdy cloak can i use a playerprefs to send data to my server ? or should i use another system ?

sharp axle
analog tide
#

ohhh it's locally stored ok so to set a player class like being a sniper it could work ?

#

Because i'd like to :

  • When i start the lobby queue it saves the current loadout
  • The host get all the datas from the clients
  • When the game start the host send back all the datas to the clients like (Weapons, gadget, throwable)
    But i don't know how to do it
sturdy cloak
#

Okey so the way i would do it (im not sure if this is the best way).

I would make a NetworkList<CustomPlayerData>.

The customplayerdata will hold all the needed data and it has to be a struct and to hold only primitive data like ints,fixedstrings,floats etc (clientId, playername, loudout etc...)

Then than on Start Client the client will send their data through a server rpc to write to the list and add themselves to the list, now the host( server) has all the data sent from the client. All the clients will listen to the OnValueChanged for the NetworkList and that way whenever something changes for the NetworkList they will know what to do.

#

PlayerPrefs would be good way to store the data locally but yeah Cloud Save is the way to save data.

#

If your game is a casual one that hackers will not hack on its a okay approach

analog tide
#

i don't want to make a casual game so i see what you mean

sharp axle
analog tide
#

yeah every items have an ID

paper blaze
#

Hello. I'm looking to implement a online database for my project but am unsure what to use exactly. Any recommendations?

#

Right now I'm looking into the Unity > Gaming Services > Cloud Save

sturdy cloak
#

That sounds about right and use Unity Economy for any kind of online currency.

austere yacht
sly scroll
#

what is considered the best solution for having players own items in a game (like an item server)? I'm making a multiplayer ccg (using NGO) and want to have a system where players can collect cards and also need to be able to communicate with my game in an intuitive way. i need to be able to associate data with the players in a way thats persistent and doesnt allow for clients to modify their items in any way

sharp axle
icy silo
#

steam multiplayer is not free, never was, (lot game dev say free-mp-valve its wrong), wish descriptions of those who have real world example calculation of a multiplayer games per anno, large community joins lobby, but 50% off than expensive, min pricing $.99 + transaction free starts by $.49 50% to $4.99 at 90% https://partner.steamgames.com/doc/store/pricing #steam-Lobby$

sharp axle
uncut wren
#

Lobby is, every time without fail, throwing me a 404 on QuickJoin

sharp axle
uncut wren
#

I have allowed it through my firewall and i certainly still have internet

#

will quickjoin give a 404 if there are no lobbies to join?

sharp axle
paper blaze
#

Is it possible to use Unity Gaming Service to store data structures like serialized variables?

austere yacht
sharp axle
paper blaze
#

Thanks

robust silo
#

I have a super simple netcode game which has two buttons "create lobby" and "join lobby". When I run two clients with ParrelSync, one creates the lobby and the other joins, and both are switched into another scene. However, when my friend tries to join the lobby from his computer, he does join the lobby, but his client doesnt switch into the game scene. Why might this be?

I have spent a few days looking for solutions and would much appreciate any help.

Code here: https://forum.unity.com/threads/loadscene-works-locally-but-not-over-network.1550588/

sharp axle
robust silo
sharp axle
robust silo
sharp axle
silk minnow
#

what is the easiest way to make a multiplayer game? im making a map strategy game and rn I have programmed some interactions between the player script and the map. I just need to make it so that each player controls a player script

#

I started following this one tutorial, but it failed to download the packages from git

austere yacht
silk minnow
#

easiest?

#

or any tutorial that will actually work?

austere yacht
#

use unreal and make a first person shooter with the builtin framework

#

In unity, use any game object based framework. NGO/mirror/fusion/etc.

silk minnow
#

I dont want to make a first person shooter. I am making a 2d map strategy game

#

how much better is unreal than unity for a multiplayer fps game anyway?

austere yacht
#

it’s not necessarily better, it’s just preconfigured in a way that you basically have a (boring) networked fps right out of the box

#

Making anything else is extra work.

#

all popular game engines are selling the fantasy that making games is easy (if you use their engine), but that fantasy gets a hard reality check real quick when you start with multiplayer.

#

so while to an experienced network developer its probably relatively easy to make a simple 2d strategy game, there is just no way to cram all the necessary knowledge into a tutorial that gets you anywhere.

silk minnow
#

bruh literally all I want for the time being is to make it so that when they click the map, in changes the color of a strategic area to the color of the player's country

austere yacht
#

best thing you can do is take one of unity's (or others) network example project and study it until you really understand what they are doing, then adapt that to your game

sharp axle
silk minnow
#

I am following this tutorial, but I am lost as to how he got that little window in the top right corner

sharp axle
mint anvil
#

how do i use a transform as a network variable

zinc marten
#

@mint anvil

mint anvil
#

ugh

zinc marten
#

yes life is tough, i am currently trying not to commit seboku creating a VR multiplayer game

sharp axle
#

Just had a thought about using NetworkVariable<(Vector3, Vector3, Vector3) but I have no idea if tuples will work

mint anvil
#

yeah i have the rework/code everything, i thought this would work ._.

west sequoia
#

@sharp axle how is that possible that matchmaker is sending server informations to clients before i set ReadyServerForPlayersAsync since the call is async?

#

Clients connect before the awaited spawnedCardBattleBoardManager.Inizialize function

severe ruin
#

does anyone know what could have caused this error in the image?
ArgumentException: Serialization has not been generated for type System.UInt64[]. This can be addressed by adding a [GenerateSerializationForGenericParameterAttribute] to your generic class that serializes this value (if you are using one), adding [GenerateSerializationForTypeAttribute(typeof(System.UInt64[])] to the class or method that is attempting to serialize it, ... The rest of the thing states that the error comes from a NetworkVariable. And doing the Generatewhatever things does not resolve my problem.
The potential source i belive is this, cause this is the only network variable with a ulong

public NetworkVariable<ulong[]> MetaUserIds = new NetworkVariable<ulong[]>(new ulong[0] {}, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Server);

Is it not possible for network variables to store ulong arrays?

west sequoia
severe ruin
#

i dont use any NetworkLists in my own code, so i doubt its the source of the error

west sequoia
sharp axle
# severe ruin does anyone know what could have caused this error in the image? ```ArgumentExc...

Arrays of C# primitive types, like int], and [Unity primitive types, such as Vector3, are serialized by built-in serialization code. Otherwise, any array of types that aren't handled by the built-in serialization code, such as string], needs to be handled through a container class or structure that implements the [INetworkSerializable interface.

sharp axle
west sequoia
#

the moment that i commented it everything was awaited properly

#

seems like is not really awaited or there is something that is not working with it

severe ruin
# sharp axle You can not https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics...

Ah ok, i believe i got it to work by manually implementing dome logic for it.

    public struct MetaSessionUserIDs : INetworkSerializable
    {
        public ulong[] Ids;

        public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
        {
            if (serializer.IsReader)
            {
                var reader = serializer.GetFastBufferReader();
                var length = reader.Length;
                if(length == 0) {
                    Ids = new ulong[0];
                    return;
                }
                if(length % 8 != 0) return;
                if(!reader.TryBeginRead(length)) return;
                Ids = new ulong[length / 8];
                for (int i = 0; i < Ids.Length; i++) reader.ReadValue(out Ids[i]);
            }
            else if (serializer.IsWriter)
            {
                var writer = serializer.GetFastBufferWriter();
                writer.TryBeginWrite(Ids.Length * 8);
                for (int i = 0; i < Ids.Length; i++) writer.WriteValue(Ids[i]);
            }
        }
    }```
west sequoia
silk reef
#

is it not possible to call a ServerRpc from a client OnNetworkSpawn ? I sometimes see Trying to send ServerRpcMessage to client 0 which is not in a connected state

#

nevermind, call came from somewhere else 😦

vital sapphire
#

I'm really forgetting some core things, but I can't figure it out

But I have a script Player_Stats on my player prefab that gets spawned by the networkmanager itself. Now this holds name, icon, mesh, etc...

Now I have an Input field and I want whatever you type in there to change the name inside the Player_Stats script from your own player prefab.. now how do I get a reference to this player prefab? It's been a long day and I can't make any sense of the forum posts

sharp axle
vital sapphire
#

ahh my script was MonoBehaviour instead of NetworkBehaviour 😔 I was already finding it very weird something simple as that didnt work

#

thanks!!

analog tide
#

Hey ! I want to play a particle system for all of my clients depending of how many player are in a trigger collision should i do this ?

    void StartRareServerRpc()
    {
        Debug.Log("StartRareClientRpc");
        StartRareClientRpc();
    }

    [ClientRpc]
    void StartRareClientRpc()
    {
        Debug.Log("StartRareClientRpc");
        particleSystem.Play();
    }```

and in my script 
```List<GameObject> players = new List<GameObject>();
    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Player"))
        {
            players.Add(other.gameObject);

            if (players.Count >= 2)
            {
                StartRareServerRpc();
            }
        }
    }```

I did put my script as networkBehaviour and i put an network object on my gameobject
analog tide
#

having an issue on my client where they can't see the animation playing

sharp axle
# analog tide having an issue on my client where they can't see the animation playing

The NetworkAnimator component provides you with a fundamental example of how to synchronize animations during a network session. Animation states are synchronized with players joining an existing network session and any client already connected before the animation state changing.

prisma scroll
#

I have come across my first major hurdle and I'm really struggling with understanding why what happens, happens 😄

I have a class PlayerController : NetworkBehaviour, this is the player object that spawns in the scene.
Notably, I have a network variable
private NetworkVariable<ulong> steamId = new NetworkVariable<ulong>(writePerm: NetworkVariableWritePermission.Owner);

I set it on Start like so:

        private void Start()
        {
            if (IsOwner)
            {
                steamId.Value = User.Client.Id.id.m_SteamID;
            }
        }

Then, I call the following code to get avatars:

        private void OnSteamIDChanged(ulong oldSteamID, ulong newSteamID)
        {
            SetPlayerAvatar();
        }
        
        public void SetPlayerAvatar()
        {
            Debug.Log(this.steamId.Value);
            CSteamID steamId = new CSteamID(this.steamId.Value);
            Friends.Client.GetFriendAvatar(steamId, avatarTexture =>
            {
                if (avatarTexture != null)
                {
                    _icon.texture = avatarTexture;
                }
            });
        }

Here's the weird part... on a client, it works fine. Both avatars are visible.
On the host, only their own avatar is visible. Why is this? O_o

#

The steam id value on the host for the connected client is 0. Only one avatar is visible on the host's PC - their own.

sharp axle
prisma scroll
sharp axle
analog tide
sharp axle
analog tide
#

so in the code i did it won't play for the client do you know why ?

uncut wren
#

I'm trying to think of a way to get around a certain issue with NGO, wherein gameobjects with a modified hierarchy are unable to spawn on other clients

#

has anyone managed to find a way to get round this?

sharp axle
sharp axle
uncut wren
#

I was thinking more in the context of a weapon customiser sorta thing

#

I guess the easiest way to do it would be just disabling the unused components?

sharp axle
fringe imp
#

anyone know if its a big deal to use the way ive always used to move characters (setting velocity and using a dynamic rigidbody) when doing multiplayer?

sharp axle
abstract copper
#

if its client-authoritative and you just set the non-local-players rigidbodies to be kinematic, it's not a big deal

mint anvil
#

again, i want to jump from a bridge

i have a network transform to set a target of a spaceship, because transforms don't work as network variables, and i have to use network variables because everything runs on the server and otherwise the client can't set the target of the ship, but how can the ship now move to the target -> network transform in the code if i can't get the position?

gray bone
#

hello,
I'm creating lobby with Fishnet and it works great. clients are spawned in the lobby, host clicks on start game and both clients go to game scene. however, I can't figure out how to spawn the player. if there is any guide about this, I'd really appreciate it.

fluid walrus
mint anvil
fluid walrus
fluid walrus
# mint anvil Uh i am confused

if i'm understanding it right you want to set a reference to a particular transform within the ship? so rather than setting a variable to the transform, set it to an id value like "engine 3" and let the other client look up where that transform is on their end

mint anvil
fluid walrus
fluid walrus
#

how about making an array of transforms on the spaceship script? then the "id" you send is just the index in that list of the transform you're targeting and it's super easy to look them up

mint anvil
#

but what is with in general to set an enemy ship as a target to follow/attack

fluid walrus
#

NetworkObjectReference sounds like what you need?

mint anvil
fluid walrus
#

yes, it's basically just a wrapper around the object's id

mint anvil
#

ok

mint anvil
mint anvil
somber lantern
#

what updated tutorial will let me add multiplayer to my 2d game

#

i cant find any

sharp axle
mint anvil
#

@sharp axle i swear without you I would have given up 100 times already

hidden spear
#

Hey everyone, I am currently working on a 2D roguelike multiplayer game and am intending to upload it onto steam. I don't really have experience in game development and mostly self taught myself and made games for fun. Im reaching out to get someone's opinion about the multiplayer aspect of the game. Right now i am using Photon's PUN Hosting for my game and so far has been working somewhat. I would just like to get an opinion if i should continue using photon or maybe switch to some other method to host multiplayer because i thought about it for a little longer and came to realize that photon might possibly not be the best option due to future additions to the game such as things requiring steam profiles and players not hosting there own lobbies that would accommodate their ping and possibly much else. I just don't know if im stepping in the correct direction with the multiplayer as it is something i've never done at all and have no knowledge, would something such as a custom dedicated server hosting be better for my game or what is your take on it?

sharp axle
hidden spear
sharp axle
sharp axle
analog tide
#

Hey I have a small question I made a network list of ulong player ids and I have some memory leak warning that just pop up do you know why ?

fluid walrus
analog tide
#

yeah here is the error :

Unity.Collections.NativeList`1:.ctor(Int32, AllocatorHandle) (at .\Library\PackageCache\com.unity.collections@1.2.4\Unity.Collections\NativeList.cs:116)
Unity.Netcode.NetworkList`1:.ctor() (at .\Library\PackageCache\com.unity.netcode.gameobjects@1.8.1\Runtime\NetworkVariable\Collections\NetworkList.cs:14)
RareObjectScript:.ctor() (at Assets\RareObjectScript.cs:11)

here is the code :

{
    new ParticleSystem particleSystem;
    public NetworkList<ulong> playerIds = new NetworkList<ulong>();
    public Material material;
    public bool isAlreadyTaken;```

The 11 line is the network list
fluid walrus
#

oh right you're creating the list in the constructor and never freeing it, NetworkList uses a native allocation in the background so you need to make sure you call Dispose when you're done with it

#

you probably want to create it in Start or Awake and dispose it in OnDestroy

analog tide
#

well i never destroy the gameobject exept when i finish the game

fluid walrus
#

the warning is probably only happening in editor then?

analog tide
#

maybe how can i check if the error is still here in build ?

fluid walrus
#

just run a build and look at the logs

sharp axle
#

I'm pretty sure NetworkList is supposed to self Dispose. I might be wrong though

fluid walrus
#

actually yes it's a networkvariable so it does automatically iirc, but only in OnDestroy? so instances created in the editor might not

analog tide
#

where do i see my logs for build game ?

fluid walrus
#

find the log file in the build folder or connect from the console

analog tide
#

doesn't seems to have the error in build

mint anvil
tawny briar
#

Is NGO suitable for small scale open world games, like an MMORPG?

austere yacht
tawny briar
#

Orpg then, lol

#

Or smorpg? angerjoy

austere yacht
#

NGO can make the sync bit of a small world smorpg but it doesn’t give you any of the database stuff. Small world == no world partitions/phasing/instancing.

#

the complexity is still there even if you have just a few ccu

sharp axle
tawny briar
#

I'm not afraid to write code but I don't want to reinvent the wheel if I can avoid it

granite stump
#

Can someone help me?
I keep getting this error:
Client is not allowed to write to this NetworkList
I've tried ServerRpc/ClientRpc and changed the Write Permission to both server/owner and I still get it.

austere yacht
sharp axle
sharp axle
granite stump
sharp axle
granite stump
#

I'll keep that in mind. Thank you.

hallow carbon
#

Hey there => I'm using NGO. I add children to a prefab with a network object at runtime, then spawn that prefab but the Children are not spawned on clients. Is it something I'm not supposed to be able to do because the template prefab in the PrefabNetworkList doesn't have these children in it ?

fluid walrus
wispy spire
#

and secound script

hallow carbon
wispy spire
#
using System.Collections.Generic;
using UnityEngine;

public class gamemeneger : MonoBehaviour
{
    

    public void SpawnGracza()
    {
        Vector3 pozycjastart = Vector3.zero;
        GameObject mojGraczGO = PhotonNetwork.Instantiate("Gracz", new Vector3(58.29f, 0f, -837.0149f), Quaternion.identity, 0);
        mojGraczGO.GetComponent<FirstPersonMovement>().enabled = true;
        mojGraczGO.GetComponent<Crouch>().enabled = true;
        mojGraczGO.GetComponent<Jump>().enabled = true;
        mojGraczGO.transform.Find("First Person Camera").gameObject.SetActive(true);
        GetComponent<PhotonView>().RPC("SpawnujGraczaRPC",PhotonTargets.AllBuffered,  gracz.mojgracz.nick, mojGraczGO.GetComponent<PhotonView>().viewID);

    }
    [PunRPC]
    void SpawnujGraczaRPC( string nick, int pvID, PhotonMessageInfo pmi)
    {
        GameObject nowygraczGO = PhotonView.Find(pvID).gameObject;
        nowygraczGO.name = "Gracz_" + nick;
        gracz gracz = gracz.ZnajdzGracza(pmi.sender);
        gracz.playerObject = nowygraczGO;
        if (gracz.team == Team.BLUE)
        {
            gracz.playerObject.transform.Find("Man_Full/Man_Cloth_Face_Mesh").GetComponent<Renderer>().material.color = Color.blue;
            gracz.playerObject.transform.Find("Man_Full/Man_Balaclava_Mesh").GetComponent<Renderer>().material.color = Color.blue;
        }
        if(gracz.team == Team.RED)
        {
           gracz.playerObject.transform.Find("Man_Full/Man_Cloth_Face_Mesh").GetComponent<Renderer>().material.color = Color.red;
            gracz.playerObject.transform.Find("Man_Full/Man_Balaclava_Mesh").GetComponent<Renderer>().material.color = Color.red;
        }
        if (gracz == gracz.mojgracz)
        {
            gracz.playerObject.transform.Find("Man_Full").gameObject.SetActive(false);
        }
        else
        {
        gracz.gameObject.transform.Find("Man_Full").gameObject.SetActive(true);
        }
    }
}```
#

the person who enters the game does not see the players who entered earlier, why?

#

if you want w can dent script: gracz

sharp axle
hollow yarrow
#

Is there any possible drawback of passing ownership of a game manager (a netcode manager [manages current round player, their current round action, etc])?
I would assume private variables and methods are different between what is currently in the Host and the current Owner unless they are changed in a ServerRpc call, is that correct?

I ask because I was trying to do server rpcs but without ownership of the game object (the game manager in this case) it fails, so after searching I reached two ways to solve it: set all server rpcs as RequireOwnership = false (plus checking if the sender is the current player) or changing the owner every turn between players. I was leaning to changing the ownership because it would look cleaner, but I'm pretty new and not sure if it's safe passing ownership of an important netcode manager to a [not trustworthy] client.

granite stump
#

Hi. How can I sync the change of a string so it's the same on all clients? I have 2 players and each will generate a code based on their actions.

granite stump
#

I'll look into it. Thanks

sharp axle
hollow yarrow
shut heart
#

❤️ kb/s send to host and <4 kb/s send from host is good? This is rough estimates for 2 peer to peer players, so if there are 5, the host would receive 10-15 kb/s and send out around 4 kb/s to players. keep in mind this is done in webrtc, was really trying to keep the bandwith low, but ran into some issues where i need to increase it a bit, so i'm wondering if these numbers are fine.

austere yacht
shut heart
#

why?

austere yacht
#

because you want players to see what other players are doing right?

shut heart
#

atleast for positions, host doesnt relay instantly the data, it pools and sends it as one message

austere yacht
#

depening on your type of game ofc, if its "real time" or "live", its n^2

shut heart
#

i still dont see why it has to be

austere yacht
#

it doesnt "have to" be, if you only update players that are in close proximity, ofc the number goes down, but you can't get out of O(n^2) data unless your players can't see each other

shut heart
#

lets say we ignore all the other stuff like player joined, player left, player died, etc. etc. just position. I take all the position data, serialize it, turn it into a byte array, send it to host. Host adds that to a list of pooled position data, and sends it out every X ms to each player

#

oh yeah

#

now i see it xd

#

nevermind, yeah for host it*s n ^ 2

#

but for peers its n

austere yacht
#

in true peer to peer, its n^2 for all peers, but you don't have p2p you have host-based networking

#

which is the same as server based, with more annoying code

shut heart
#

true

clear flint
#

Can someoen help? Im trying to add servers to my game, but everytime I try to join a server it pauses the game and gives me this error

lime gale
#

Hi im watching
PHOTON FUSION 101 - Part 2_6 Set up a multiplayer game

and i have a problem in my code or bug i dont even know

i dont get any error but my players dont spawn i dont know what i did wrong

#

all i know is i dont get log for if (runner.IsServer) {

#

i dont see runner.IsServer or player joined

#

also my "Basicspawner" get destroy after clicking on host
is it normal ?

lime gale
#

i went and find the github sample , it work , i even copy and paste everything that was important about it (copy and paste scripts and even the prefabs ) but still it not working on my projects but it work on the second project (sample from github ) i dont get it why

#

but 1 thing i notice is

#

after i click on host button my "BasicSpawner"
gameobject
in my project just destoy

but on his project
change his position and go inside DontDestoyOnLoad
and i have no idea why

craggy tinsel
#

Is someone familiar with netcode for gameobjects, lobby and relay by unity? I have this bug which I wasnt able to fix in hours

vivid viper
#

yo can anybody help me a thing with photon? when i move a person it moves all players across the network but i'm not sure how to fix it

ruby copper
#

Hello, I am making 2D networked game with Unity netcode for GameObjects. I actually succeed making server authoritative player movement with Server Reconciliation, Client Prediction etc.

Now I am adding projectiles to the game that stuns the player when it hits him. So I am getting desyncs because the player hit on server side is not at same position as client prediction on local. Someone has some articles or theory in order to understand what's the optimized way to handle this ?

Thanks a lot.

sharp axle
zealous prism
#

im using photon, and for some reason only the host of a room is being rendered, while everyone else is invisible and cant be collided with other players, is there a fix to this

zealous prism
#

might it have something to do with the spawning? or the launching script

wide girder
signal bone
#

best way to handle it is to hide it

#

smooth the client correction so that its not an instant teleport, send the correction immediately after the knockback so it reaches the client sooner, etc

#

i think 😹

zealous prism
signal bone
#

also for stuns and slows which have a duration, that needs to be properly handled during rewinding and replaying inputs like evilotaku said 👍

#

so they expire ping amount sooner in time than for the server so that the client returns to predicting

analog tide
#

Hello guys having a little issue,

                GameObject bullet = Instantiate(bulletPrefab, this.gameObject.GetComponentInChildren<WeaponParts>().weaponMuzzle.transform.position, weaponSpawner.transform.rotation);
                bullet.AddComponent<BulletScript>();
                bullet.GetComponent<BulletScript>().bulletSpeed = weaponSpeedBalisitic;
                bullet.GetComponent<BulletScript>().direction = (hit.point + dispersion - this.gameObject.GetComponentInChildren<WeaponParts>().weaponMuzzle.transform.position).normalized;
                bullet.GetComponent<NetworkObject>().Spawn();```

with this code i spawn my bullet and give it a speed and direction but in my bulletscript it won't have the speed and direction

```public override void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();
        
        Debug.Log("Bullet spawned with" + bulletSpeed + " speed and " + direction + " direction");
        GetComponent<Rigidbody>().AddForce(direction * bulletSpeed);
    }```

this is the bulletscript
sharp axle
analog tide
#

well if i put the bulletscript on my prefab will it work ?

#

and not putting the script at runtime

sharp axle
drifting plaza
#

How jank is this solution for combatting fly hacks (one of my gamemodes includes wall running in any plane): Find the plane the player is standing on at any given frame. Calculate the angle between said plane and the player's delta position vector from last frame and check if it falls within an acceptable range/

analog tide
#

i have the data in my bullet but it won't add a force to it ?

#

should i make the add force to the network rigidbody ?

sharp axle
analog tide
#

well seems like the addforce to my rigidbody won't work even if he has a network transfrom,rigidbody and correct data from the networkvariables

sharp axle
crisp drift
#

Hi, I'm currently doing some comparative research about networking solutions, and I was wondering about what are some examples of games that use Unity's solutions?

analog tide
#

ohhh i got a warning : NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. Are you modifying a NetworkVariable before the NetworkObject is spawned?

#

i know why ok just need to fix it

#

perfect thank's a lot

sharp axle
crisp drift
#

yeah,
I just wanted to get a better idea of the kinds of projects people make with 'em
thanks a ton

analog tide
#

Having a bit of trouble with this code : ```public float mouseSensitivity = 400f;
NetworkCommunication networkCommunication;
public Transform playerBody;
float xRotation = 0f;

void Start()
{
    networkCommunication = GetComponentInParent<NetworkCommunication>();
}

void Update()
{
    float MouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    float MouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

    xRotation -= MouseY;
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    

    transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    playerBody.Rotate(Vector3.up * MouseX);
    networkCommunication.RotatePlayerServerRPC(playerBody.rotation);
}``` when i am a client when i move my mouse on the X axis the player shake left and right can someone help me with it ?
sharp axle
analog tide
#

it's using an network transform

#

it's not spinning like it shakes

#

i'm making a vid for u

split hedge
#

Hey, the error is Only server can spawn NetworkObjects

drifting plaza
#

I have CPSR working for speed /teleport hacks, but I have nothing controlling for direction

sharp axle
sharp axle
sharp axle
drifting plaza
sharp axle
analog tide
drifting plaza
#

that is what I'm doing. But the issue is I need to figure out something to compare it to.

#

I have the player's new position, and the player's old position. I have that vector. Now to make sure they aren't teleporting or speed hacking I check the magnitude of that vector to make sure it's within a certain range based upon player's game state. The issue I'm trying to tackle is direction. How do I make sure the player doesn't fly straight up at a normal speed or clip? Normally, you could just check y component / you would only do these calculations on the x-z plane. However, because I am doing wall running, the y component won't always be the direction they are moving in if they decide to start flying.

sharp axle
drifting plaza
sharp axle
drifting plaza
#

that way I don't really need to worry too much about synchronization just checks for anti cheat

drifting plaza
#

If a player sends a "false" position, the server and all other clients are 1) going to treat that as a real position , and 2) the server is going to check it with their input

#

so the client's actions in whatever the position is on their screen will all be invalidated once they have to be checked by the server

#

If I'm being dumb, please correct me

sharp axle
drifting plaza
#

I have a few questions. 1) If the client blocks a rollback ,that would only screw them over, right? 2) True it is more work on the server because they have to verify all inputs; is that going to be a lot of work on a dedicated server? I plan on having max 40 players. Let's say its about 2000 lines of code at O(1) time complexity, if the server is running at 30 or 60 ticks per second, that means 2.4 or 4.8 million lines of code, respectively, per second. Is that unreasonable? I'm not familiar.

#

@sharp axle sorry I forgot to react

#

I was always under the impression that managing the network traffic was the important part, but 5 m lines of code a second sounds like a lot

sharp axle
drifting plaza
#

And if it is parabolic it would be pretty linear parabola considering were not expecting much error that frequently, I'd think. anyways maybe im competely wrong. But thanks for your time, it's really cool of you to help out all the people here

crisp crag
#

Question to the community what is a good yt that starts tutorials for beginners.

drifting plaza
crisp crag
drifting plaza
crisp crag
#

Kk

#

Not in unity

sharp axle
#

I would recommend Code Monkey's videos on both counts

drifting plaza
#

Personally, if you have no c# experience I'd look specifically for a c# tutorial first.

#

If you do have, then Code monkey is great

crisp crag
#

Okay

#

But I don't

#

So what would u recommend

sharp axle
#

He is actually starting a C# course for beginners

drifting plaza
#

Oh, well that sounds good then

crisp crag
#

Okay thanks for the help

drifting plaza
#

I always tell people that before you go into game programming, you should learn the basics of OOP, which he probably covers

#

If his tutorial series isn't complete, there are plenty of other places to learn, although im not familiar I absolutely know they exist

drifting plaza
sharp axle
drifting plaza
crisp crag
#

Last question since I'm a beginner should I learn unity or Roblox coding?

drifting plaza
crisp crag
#

Oh k

drifting plaza
# sharp axle I've never benchmarked it myself. But if clients are also interacting with each ...

I'm gonna try to break it down mathematically. Lets say you have n number of clients and each client interacts with other clients at a rate of n/c (c is constant) That would mean we could say the number of interactions between clients is equal to n^2 / c. Furthermore, each client has a certain amount of actions they would do on their own no matter what, so we can define this as n * d. So we'd expect the number of requests on the server for all these interactions to similar to O((n^2 / c) + n * d)

#

I guess there is no guarantee, that n/c is correct, it'd probably be close n^x/c or perhaps x^n, it's hard to tell

mint anvil
#

it no longer shows up under the netcode components and is grayed out on the objects its attached to

sharp axle
mint anvil
#

and i restarted it many times, i also went back to the old version and it's still broken

#

no error just looks like this

analog tide
#

To send to a client that he takes damage i need to make a client rpc with param ?

#

or a simple networkvariable and an oncollisionenter work ?

sharp axle
mint anvil
sharp axle
livid nexus
#

Hey. I’m working on using Netcode for Gameobjects for multiplayer.

How should i be setting up the cameras for each player? I am using cinemachine (also for the first time), where the camera and virtual camera is a part of the player prefab that gets instantiated when they connect to the server. However, whenever a new client joins the server, everyone’s camera just gets switched to theirs

odd girder
sharp axle
# livid nexus Hey. I’m working on using Netcode for Gameobjects for multiplayer. How should ...
GitHub

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

fierce seal
#

Hi, I'm using NGO 1.6.0 on Unity 2022.3.10f1

Actually, when I start the Network Manager as Host, it correctly spawns the player's prefab.
But if I do a Server / Client configuration, the client will never spawns the player's prefab...

Of course, my Client is correctly connected to the Server.

I hope someone has the solution to this problem.

Thanks in advance. 🙂

sharp axle
fierce seal
placid onyx
urban berry
#

Hello everyone, I've been working with NGO over the past month, and everything is working as excepted with the exception of having high RTT and lag in the game. If the RTT is 1000ms, it roughly appears that it takes 1000ms for an action to occur on other clients like shooting projectiles.

Before I give up on NGO and experiment with another solution I thought I'd get some thoughts here.

Notes

  • The high RTT happens even with only 1 player online
  • It seems the longer the server is up, the higher the RTT becomes
  • We are targeting WebGL, but have also been testing in a Windows application
  • We are using a Dedicated Server with Unity Cloud Game Server Hosting and Relay with WebSockets to allow WebGL
  • We've also tested without WebSockets/WSS/Relay
  • If I ping the Server IP directly from my command prompt the ping is around 40ms

Packages

  • Netcode for GameObjects 1.8.1
  • Unity Transport 2.2.1
  • Multiplay 1.1.1
  • Relay 1.0.5
  • Lobby 1.2.0
  • Multiplayer Tools 1.1.1
  • (Unity 2022.3.18f1)

Full Information:
https://forum.unity.com/threads/high-rtt-with-ngo-dedicated-server-relay.1553579/#post-9683618

urban berry
#

I've also noticed today that when I upload a new build to Unity Cloud Game Server Hosting, the files sync, then go into a "Ready" state, but then never has any progress during the installation. Not sure why that's happening. The only way for me to get it to update is to delete the server, fleet, building config, build, then start over.

Normally when I upload a new build the server installs the files right away.

livid nexus
#

Hey i am trying to get my cinemachine working with my netcode for gameobjects setup.

I have two windows, one for the editor and one for a build. I am finding that whenever i start a host or client in my editor, my cinemachine works properly and follows my player. However, no matter what is selected (host or client) for my build window, the cinemachine just never seems to follow my player and sits at the default position

#
    public override void OnNetworkSpawn()
    {

        if (IsOwner)
        {
            _audioListener.enabled = true;
            _virtualCamera.Priority = 1;
        }
        else
        {
            _audioListener.enabled = false;
            _virtualCamera.Priority = 0;
        }

    }
#

I've got no errors or anything. I dont think it is a network issue because my cinemachine doesnt work in my build window, regardless of if its a host or client

urban berry
craggy tinsel
#

hello, i am using netcode for gameobjects. i have a problem with client movement. i have two projects, in one it works perfectly fine ( that was my demo project where i test stuff) however in my main project the client simply doesnt move. i tried wasd movement but client doesnt move but i see that the client is trying to move (moving feet and legs etc, he is also animated but doesnt go forward)
tbh i used the main menu from a youtuber tutorial which included a lobby etc and i believe i am doing a mistake there.

#

and this is the second project where it is working. the prefab list and character database confuse me too. i watched two tutorials but the one providing the main menu and networking tutorial doesnt show how character movement works and the characters only stuck in the air so i watched a second tutorial on how to change the character movement script so it works in coop

#

i am sure the issue is with the player prefabs and character database

fierce seal
cobalt pier
#

what would be best networking for an fps multiplayer?

sharp axle
analog tide
#

i have a quick question, as my game is a big multiplayer game and we can have a lot of server i'm wondering if i can broadcast a message trough all my clients currently on the game or not ?

#

Like if i make a maintenance on it and i want that everybody see the same message at the same time without making a update of the files

wraith steeple
#

https://hastebin.skyra.pw/fidupezike.csharp I got TargetParameterCountException: Parameter count mismatch. error. I kinda know why but I have no idea how to fix it, btw if you are wondering what im tryinh to do it is everytime a player join a key, value of player id and nickmae pair will be added to the dictionary which get update eveytime new player joins

#

its photon fusion 2 btw

icy flint
#

Hey, I need some help figuring something out. We are completely moving to Unity Networking right now.
We already implemented Unity Authentication and Unity Lobby.
We Would now like to also implement Relay (so we don't need to worry about NAT and Port Forwarding and shit like that) aswell as NGO.

How do we properly integrate Relay with Lobby? I know they work well together as that is what it says in the docs, but there is not really tutorial how to connect them (or I missed it)

icy flint
#

cool thanks

#

would something like this be appropriate to auto refresh the Lobby list?

IEnumerator RefreshGameList(float waitInSeconds)
    {
        var delay = new WaitForSecondsRealtime(waitInSeconds);
        while (true)
        {
            var lobbies = LobbyManager.Instance.GetLobbies();
            foreach (var lobby in lobbies.Result.Results)
            {
                var gameListEntry = Instantiate(gameListEntryPrefab, gameListContent);
                gameListEntry.GetComponent<GameListEntry>().SetLobby(lobby);
            }

            yield return delay;
        }
    }```
ok no its not xD it causes my whole unity to just freeze 😄
sharp axle
icy flint
#

this is the GetLobbies:

public async Task<QueryResponse> GetLobbies()
    {
        var query = new QueryLobbiesOptions
        {
            Count = 10,
            Filters = new List<QueryFilter>
            {
                new(field: QueryFilter.FieldOptions.AvailableSlots,
                    op: QueryFilter.OpOptions.GT,
                    value: "0")
            },
            Order = new List<QueryOrder>
            {
                new(asc: false, field: QueryOrder.FieldOptions.Created)
            }
        };
        return await LobbyService.Instance.QueryLobbiesAsync(query);
    }```
sharp axle
#

I avoid using while(true) at all costs to prevent infinite loops

icy flint
#

could you tell me how you would refactor the code?

sharp axle
icy flint
#

well something doesn't work properly, once I start the game my unity zu freezes:

    private IEnumerator RefreshGameList(float waitInSeconds)
    {
        var delay = new WaitForSecondsRealtime(waitInSeconds);
        while (true)
        {
            var lobbies = LobbyManager.Instance.GetLobbies();
            foreach (var lobby in lobbies.Result.Results)
            {
                var gameListEntry = Instantiate(gameListEntryPrefab, gameListContent);
                gameListEntry.GetComponent<GameListEntry>().SetLobby(lobby);
            }

            yield return delay;
        }
    }

    void Start()
    {
        _refreshGameListCoroutine = StartCoroutine(RefreshGameList(5));
    }

    private void OnDestroy()
    {
        StopCoroutine(_refreshGameListCoroutine);
    }```
#

but you are right, I will just add a refresh button.

flint siren
#

Hello, good afternoon, I hope you are all doing well. I have a question: I would like to create a multiplayer client-server P2P game for Steam. Is there anything I should consider, such as pricing or any advice you wish you had heard before starting?

icy flint
#

Hey I need some Networking help.
I have now managed to successfully connect Relay, Lobby and NGO (nearly).

But my problem is: when the second player joins, both players get spawn on top of each other and I control both players, is that caused by my Movement Script?

sharp axle
icy flint
icy flint
#

okay so I managed to fix it a bit by using this code:

        if (IsLocalPlayer) return;
        transform.GetComponentInChildren<AudioListener>().enabled = false;
        transform.GetComponentInChildren<Camera>().enabled = false;
        transform.GetComponentInChildren<PlayerMovement>().enabled = false;
        transform.GetComponentInChildren<LadderClimbing>().enabled = false;
        transform.GetComponentInChildren<MouseLook>().enabled = false;```

but there is still multiple problems with that:
Animations are not synced network players are just tposing or stuck in the idle animation
#

also shouldn't it be IsOwner when trying to do server authoritive movement?

analog tide
#

Hey having a bit of an issue, i'm trying to attach a gun to a player that i instantiate but it won't set as parent when i spawn it : ```
public void SpawnWeapon(SO_Weapons weaponSpawn)
{
weapon = weaponSpawn;
if (weaponSpawner.transform.childCount > 0) Destroy(weaponSpawner.transform.GetChild(0).gameObject);
GameObject weaponSpawned = Instantiate(weapon.weaponPrefab, weaponSpawner.transform.position, new Quaternion(0, 0, 0, 0), weaponSpawner.transform);
weaponSpawned.GetComponent<NetworkObject>().Spawn();
weaponSpawned.transform.SetParent(weaponSpawner.transform);

}```
#

my parent is an network object and my guns have a network object and network trannsform

sharp axle
# icy flint okay so I managed to fix it a bit by using this code: ```csharp if (IsLo...

The NetworkAnimator component provides you with a fundamental example of how to synchronize animations during a network session. Animation states are synchronized with players joining an existing network session and any client already connected before the animation state changing.

sharp axle
analog tide
#

how would you do it ?

sharp axle
# analog tide how would you do it ?

I'll attach it with a physics joint if it really needs to be a Network Object. Most of the time you can get away with just instantiating a regular game object locally, Then you can do whatever you want with it

analog tide
#

well i need all my players to see the current gun you are holding

#

after for a prototype is it really useful

sharp axle
analog tide
#

ohhhhhh i see

#

so you have a naked player and you instantiate the elements to other clients with network variables

analog tide
#

that will make a lot of work to change everything

analog tide
#

@sharp axle having a bit of an error "GetComponent requires that the requested component 'SO_Weapons' derives from MonoBehaviour or Component or is an interface."

Like a made networkvariables to cast int... and i need to acces my component which is a scriptableobject and i have this error i understand it but i can't resolve the error

sharp axle
urban cape
#

I've got an issue where if I try and move the players position to somewhere else when its spawned it will stay stuck unable to move

#

It works perfectly fine just spawned in without changing its position whenever i start as host

#

Not only will my input not go through it seems as if the network manager doesn't like it, as the player is completely stuck

#

I feel as if this a simple fix and a desync issue with teleporting

#

but I don't know the answer and I really need the help asap

sharp axle
# urban cape

Change Start() to OnNetworkSpawn(). If SpawnReference is in the scene then you will need to Find it when the player spawns

urban cape
#

I used OnNetworkSpawn with the same issue

analog tide
# sharp axle Yea. a scriptable object is not a component. so you won't be able to GetComponen...

while i try to build my game with the new AssetDatabase.LoadAssetAtPath
i use the dependence using UnityEditor; as asked but i keep having a build fail
"Assets\BulletCreator.cs(82,18): error CS0103: The name 'AssetDatabase' does not exist in the current context"
and my 82 line is
"weapon = AssetDatabase.LoadAssetAtPath<SO_Weapons>("Assets/ScriptableObject/Player/Weapons/W_" + weaponSpawn.Value + ".asset");"

sharp axle
analog tide
#

ohhhh ok i'll try thta

analog tide
#

well i don't have any error but it won't work anymore 🤣

#

it won't load a ressource

sharp axle
analog tide
#

yeah i put it in a Resources folder well there is folder in folder to let it clean and i know it's case sensitive i made a copy path but still won't work

livid nexus
#

Hey I've got a question. I have something in my scene. I want it such that when a player spawns in (using netcode for gameobjects), that specific script attached to said something finds the player that is local. How can i do this?

sharp axle
#

Resources.Load

sharp axle
spice breach
#

is it preferable to have server determine available servers, eg load balancing (C->S->S1 or S2) or should the client ping each server directly (C->S1 or S2)?

flint siren
#

Hello, good evening, I wanted to ask, what do you think about Fish-Net?

livid nexus
#

Hey so let’s say I have a prototype game that has multiplayer already using Netcode for gameobjects.

I can join as a server, host, or client in my game. I am curious to how setting up local split screen would work if I already have this server/client/host stuff set up. What would be the general idea for how split screen is handled? Is it possible to have split screen players on one device and someone else joining as another client?

#

ie like is it possible to set it up such that another client can join but is split screen with the client (or host) that is on its same device?

#

My inputs are also handled by the new Unity input system

fluid walrus
#

i haven't actually tried it but ngo has made some steps at least towards supporting multiple NetworkManagers in a game - that said i think even if that works you'd probably be better off implementing it separately

#

unless you want each player to have a totally separate copy of the world, stuff like spawning and object ownership would be a nightmare

livid nexus
#

Yeah. Conceptually would it be just like the second split screen player is joining as a client or something? And just running its own version of the game as if you were online?

fluid walrus
#

yeah, that would be the idea

livid nexus
#

Gotcha

fluid walrus
#

normally you'd want one world with two cameras rendering to different parts of the screen, rather than two worlds though

livid nexus
#

So it’s mostly just a matter of setting up a client connection that when you join, sets up a split screen window with the host and making sure the inputs go to the right player

fluid walrus
#

yes, but again, probably don't do this

livid nexus
#

Wouldn’t I need to do this if I want players to be able to be in different scenes from each other?

fluid walrus
#

that's already something you probably want to avoid if at all possible in NGO, let alone while trying to make it work in splitscreen

livid nexus
#

So for a small-scale but open world game with low-intensive graphics, would it be best to just have the entire game in one scene?

fluid walrus
#

well if you want players to be in totally different areas you have to manage which set of network objects each one can see, whether or not they're in different scenes

#

trying to make that work in splitscreen would be a massive waste of effort

sharp axle
stable dust
#

i see a lof of different options when it comes to networking i want to make a simple tag game which option is reccomended for a simple game like that?

sharp axle
stable dust
#

are any of them easier to use then others?

vital summit
#

Hello my friends, may I ask a question? I am using Netcode for Gameobjects and am able to sync Animation through a network animator. For my locomotion I have a blend tree going. The correct animation/ horizontal and vertical parameters are networked. But these parameters keep bouncing to zero making animation jitterish. Any way to lerp that parameters over the network? Any workaround for blend trees? I would be very glad for any hint or info about networked blend trees.

vital summit
#

Is resolved

wraith tendon
#

Hey guys, for a game i have to implement a system of Request/Response between the server and some clients

I tried to do it by calling a Server RPC that then calls a Client RPC as a response for everyone


public class simplemovement : NetworkBehaviour
{
    public float speed;
    private float Move;
    private Rigidbody2D rb;
    private SpriteRenderer sr;
    private BoxCollider2D bc;
    private Color[] colors = { Color.red, Color.blue, Color.green};
    private int currentColorIndex = 0;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
        bc = GetComponent<BoxCollider2D>();
        sr.color=colors[currentColorIndex];
    }

    // Update is called once per frame
    void Update()
    {
        if( !Input.GetMouseButtonDown(0)) return;
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        if( bc == Physics2D.OverlapPoint(mousePos) ){
            currentColorIndex = (currentColorIndex + 1) % 3;
            sr.color = colors[currentColorIndex];
            sendColorServerRpc(colors[currentColorIndex]);
        }
        
    }

    [ClientRpc]
    public void colorClientRpc (Color color)
    {
        sr.color = color;
    }


    [ServerRpc]
    public void sendColorServerRpc(Color color)
    {
        colorClientRpc(color);
    }


}

but it just doesn't do anything

#

(i have a basic network manager that can spawn servers and clients)

copper socket
wraith tendon
#

Oh yeah it works now ! Thanks

copper socket
#

I think it's a small problem, but i have no idea of the best solution
I have a network list of players and when the host starts the game 2 things are happening:

  1. I need to choose a player for the Artist role
    Players[artistIndex] = Players[artistIndex].SetRole(PlayerRole.Artist);

  2. I need to notify clients that the game is starting
    NotifyGameStartClientRpc();

The problem is the sync of the order of these events
On the Host side, it works as it is in the script,
but clients have incorrect order, they receive game start and then the list is updating

analog tide
#

Hey guys i'm wondering how to get my player latency on ms i'm looking on internet but it's not really accurate
I managed to get this line pingText.text = NetworkManager.Singleton.NetworkConfig.NetworkTransport.GetCurrentRtt(NetworkManager.Singleton.LocalClientId).ToString(); but i still haven't my current ping from the server

#

I think it’s not the good function to use

sharp axle
sharp axle
mental citrus
#

I have watched tutorials over tutorials about how to make syncronization happen between host and client, but i still cant get over this bug ive spent hours trying to troubleshoot, as the host i can move a gameobject around and it syncs on the client, when i do the same on the client it does not sync, tutorials told me to add a client network transform, i did but that didnt fix it, it could be because all the tutorials ive seen so far use a player prefab and i do not but i really need some help fixing this xD

copper socket
sharp axle
mental citrus
sharp axle
steady iron
#
private async void OnClientDisconnect(ulong clientId)
        {
            if(clientId == HostNetworkId && !GetNetworkManager.IsHost && clientId != GetNetworkManager.LocalClientId)
                await UserDisconnect();
            
            //await UserDisconnectServerRpc();
        }

        public async Task UserDisconnect()
        {
            var nm = GetNetworkManager;
            if(!nm.IsListening || nm.ShutdownInProgress)
                return;
            LoadOfflineScene();
            HideLobbyCode();
            if(nm.IsHost)
                nm.ConnectionApprovalCallback -= HandleConnectionApproval;
            await LeaveOrDeleteLobby();
            _connectionStatus = ConnectionStatus.UserDisconnect;
            nm.Shutdown();
        }

        private async Task LeaveOrDeleteLobby()
        {
            if(_lobbyAPIInterface.JoinedLobby == null || GetNetworkManager == null)
                return;
            var lobby = _lobbyAPIInterface.JoinedLobby;
            var joinedLobbyID = lobby.Id;
            if (lobby.Players.Count <= 1 || NetworkManager.Singleton.IsHost)
            {
                await _lobbyAPIInterface.DeleteLobby(joinedLobbyID);
                if (debugMode)
                    Debug.Log($"Deleted the lobby with the ID {joinedLobbyID}.");
            }
            else
            {
                await _lobbyAPIInterface.RemovePlayerFromLobby(AuthenticationService.Instance.PlayerId, joinedLobbyID);
                if (debugMode)
                    Debug.Log($"{AuthenticationService.Instance.PlayerId} has left the lobby.");
            }
        }```

```cs
if (leaveOnEscape && Input.GetKeyDown(KeyCode.Escape))
            {
                await UserDisconnect();
            }```

Hi, me and my teammate are trying to disconnect the player when they hit escape and load them into the lobby scene but we keep getting errors and dont know why, we have been trying to patch it for about 2 and a half hours now.
#

These are the errors we keep getting. Also, they are all client side errors.

sharp axle
steady iron
#

We want all players to load the offline scene when the host leaves and if a client leaves, only that client should be loaded back into the menu

sharp axle
steady iron
# sharp axle When the host leaves the network will disconnect all clients as well. You can th...
        public async Task UserDisconnect()
        {
            var nm = GetNetworkManager;
            if(!nm.IsListening || nm.ShutdownInProgress)
                return;
            LoadOfflineScene();
            HideLobbyCode();
            if(nm.IsHost)
                nm.ConnectionApprovalCallback -= HandleConnectionApproval;
            await LeaveOrDeleteLobby();
            _connectionStatus = ConnectionStatus.UserDisconnect;
            nm.Shutdown();
        }

        private async Task LeaveOrDeleteLobby()
        {
            if(_lobbyAPIInterface.JoinedLobby == null || GetNetworkManager == null)
                return;
            var lobby = _lobbyAPIInterface.JoinedLobby;
            var joinedLobbyID = lobby.Id;
            if (lobby.Players.Count <= 1 || NetworkManager.Singleton.IsHost)
            {
                await _lobbyAPIInterface.DeleteLobby(joinedLobbyID);
                if (debugMode)
                    Debug.Log($"Deleted the lobby with the ID {joinedLobbyID}.");
            }
            else
            {
                await _lobbyAPIInterface.RemovePlayerFromLobby(AuthenticationService.Instance.PlayerId, joinedLobbyID);
                if (debugMode)
                    Debug.Log($"{AuthenticationService.Instance.PlayerId} has left the lobby.");
            }
        }```
#

would this be the only code needed then?

#

we tried using that code, when the client disconnected, the host got these 2 errors

#

and the client got these errors

carmine walrus
#

I keep getting this error after spawning a player prefab inside a test scene using unity's network manager

#

naturally it doesn't tell me what class is causing the problem, and deleting objects and components one by one until I found an answer didn't help much

#

I tried adding a generic cube as the player prefab, and as soon as it's spawned the same error flares up

#

...found the problem

#

but not the solution

#
private NetworkVariable<int[]> TeamMembers = new NetworkVariable<int[]>
(
    new int[4],
    NetworkVariableReadPermission.Everyone,
    NetworkVariableWritePermission.Owner
);

unity seems to be throwing a hissy fit over this array, so I assume I did something very wrong here trying to create a network array

steady iron
carmine walrus
#

that's some timing

carmine walrus
#

cheers lads

sacred prawn
#

I'm trying to figure out how to make a weapon that can fire a fireball projectil but not successful yet. I'm using a game object with a particle effect on and a rigidbody and set a velocity to the rigidbody. I'm using a VRCObjectPool to spawn the projectile and then set a velocity on it. Now I could add a VRCObjectSync on this one but my idea was that I could save some network load by just setting the initial velocity of the object on all clients, but unsure how to do this with the network pool.

If I do not use a network pool i can just spawn a new object on all clients and set the velocity, but if i use a VRCObjectPool i guess i kinda want to refer to the same object? So this is what I do right now but that will only make the object move on one client and stand still on the others, well right now becase projectilePool.TrySpawn() will fail on all but one. But it should at least show a general idea of how the thoughts goes and someone can explain how it should really be done.

FireProjectile is called on all clients.

public void FireProjectile()
{

    Debug.Log($"FireProjectile {_localPlayerName}");
    var obj = projectilePool.TryToSpawn();
    if (!Utilities.IsValid(obj))
    {
        Debug.LogWarning($"Unable to spawn projectile from pool {_localPlayerName}");
        return;
    }
    Networking.SetOwner(Networking.LocalPlayer, obj);
    var spawnPoint = projectileSpawnPoint.transform;
    obj.transform.SetPositionAndRotation(spawnPoint.position, spawnPoint.rotation);
    var projectileScript = obj.GetComponent<Projectile>();
    projectileScript.Initialize(spawnPoint.forward, projectilePool);
}
steady iron
sharp axle
#

Disconnecting Players

carmine walrus
#
    NetworkList<int> TeamMembers;
    [SerializeField] TeamData[] teams = new TeamData[4];
    
    void Awake()
    {
        instance = this;
        TeamMembers = new NetworkList<int>();
    }
#

I tried using .Add(0) on awake, start, OnNetworkSpawn and even a function being called by the first player to enter the game as a host

#

every time I get a null reference exception

#

line 28 in GameManager is TeamMebers.Add(0); from this snippet:

    public void DoTeamSetup()
    {
        TeamMembers.Add(0);
    }

which is called from the player's OnNetworkSpawn here

public override void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();
        if (!IsOwner) { return; }
        GameManager manager = GameManager.instance;
        if (IsServer) { manager.DoTeamSetup(); }
        team = manager.getTeamMembers(0) <= manager.getTeamMembers(1) ? 
                manager.GetTeam(0, true)
            :   manager.GetTeam(1, true);
        Material[] mat = mesh.materials;
        mat[0] = team.teamEquipMaterial;
        mesh.materials = mat;
    }
#

I either get a null reference or a length 0 error

sharp axle
carmine walrus
#

well crud. do you suggest I keep it in a regular gameobject then?

#

or rather a non-singleton script

sharp axle
#

Personally, I avoid singletons all together. Keeping it local in the scene and just grabbing it with FindObjectByType() is not a big deal

carmine walrus
#

same problem

#
public class MultiplayerVars : NetworkBehaviour
{
    public NetworkList<int> TeamMembers;
    
    void Awake()
    {
        TeamMembers = new NetworkList<int>();
    }

}

on the player's prefab, as a test:

    public override void OnNetworkSpawn()
    {
        base.OnNetworkSpawn();
        if (!IsOwner) { return; }
        GameManager manager = GameManager.instance;
        if (IsServer)
        {
            MultiplayerVars mpv = FindObjectOfType<MultiplayerVars>();
            if (mpv)
            {
                mpv.TeamMembers.Add(0);
                mpv.TeamMembers.Add(0);
            }
            
        }
#

the MultiplayerVars script was placed inside an empty

livid nexus
#

Hey so I am trying to get a small open world network to work. I want it to be something similar to how multiplayer works in stardew valley for example, where it is player hosted and the client has authority.

My idea was that the world would be divided up into different scene. I would like the players to be able to be in different scenes from each other as well. Does anyone have a conceptual outline for how this would be handled? Is there a common/standard way this is approached?

For example, can the client send an RPC to the server (aka host player) to switch scenes?

austere yacht
livid nexus
#

Is it worth splitting the world up into different scenes then?

#

I’m just curious as to how this is typically done in games made in Unity

#

Before I go deep into making my own system it would be good to know how most people tackle this idea if that makes sense