#archived-networking
1 messages · Page 2 of 1
making a multiplayer 2d game and I can see thru other players camera anyone know how to fix?
(Photon.Pun)
You should not have multiple cameras on the client.
There should only ever be one camera per instance.
People like asking which is "better" when really you should be asking yourself "Which one do I want to work with?", "Which one fits my project and has the features I need?"
Without any details about your project, you can't reasonably expect someone to say one is better than the other
how can i make a system where people watching a game can join, with photon or something else ( my first goal is The server move the model and clients only observe)
I assume you mean via Twitch. The same way you handle anyone joining the game. With something like Unity Relay where they have a server that points to your peer to peer host. Might also be possible to embed their tcp/ip connection info in the link itself and avoid a relay service, but it'd be easier just to embed a join code and connect to a relay service.
Thank you, I will check that
I'm using NCGO personally. It's fairly simple to use if you like to mostly concern yourself with: (send message to all clients), (send message to host), (send message to specific client), (synchronize primitive data between two participants). If you have a host setup rather than a dedicated server, and if your networking solution is very p2p focused, imo NCGO is great. I've learned it pretty much by spending two days reading the docs and watching Tarodev's 2 videos.
Yeah, I always wanted LAN multiplayer because most of my games aren't really designed for actual global multiplayer gameplay anyway
I'm definitely gonna try Netcode out
I am networking my Rigidbody FPS controller, it's working but my players are jittering and are not synced with the actual location of the player
This is a huge step to be honest, despite the issue
I'll try to fix the issue then build on top of it
My decision:
LAN/Party games - Netcode for GameObjects
Full-scale Global Multiplayer (If I ever make one) - FishNet or Photon
I get this error ClientRpc method must end with 'ClientRpc' suffix!
public void RpcTakeDamage (int _amount, string _sourceID)
{
if (isDead)
return;
currentHealth.Value -= _amount;
Debug.Log(transform.name + " now has " + currentHealth + " health.");
if (currentHealth.Value <= 0)
{
Die(_sourceID);
}
}```
I am porting Brackey's multiplayer from Unet to Netcode
nvm
I just have to rename the method
does anyone know of any good info or tutorials on how to set up a multiplayer system in a game like escape from tarkov, where players load into a continuous game, play, and get out with the gear they acquired? i've been looking but i cant find any good info on it.
Can anyone tell me where to find the Unity Netcode for Gameobjects Client Network Transform script ?
the documentation links to something outdated, and also is outdated in itself
@patent fog Thank you so much! <3 Can't for the life of me not understand how this is not directly included in the Network for Gameobjects package
yeah they hit 1.0 though, could/should have been in main package (?) 🤷♂️ Not following closely enough though
It's not, unfortunately, even with 1.0.2 being out
vs fusion site:
@night thunder Maybe it will come later, or maybe they consider it a hack and allow it for demo only ? ANd don't really expect you to use it in prod ?
Dunno, really blind guessing here
🙂
@patent fog pretty sure that would/should be mentioned on the documentation in some way then... but with all the different versions of editors and packages, i think current Unity is not nearly as beginner friendly as it was at some point 🙂
True, hard to follow nowadays with all these experimental packages, taking infinity to reach production state 🙂
the component kinda warns against itself in the comments
and as a general rule, never trust user input, allow the client authority over the Transform seems a really bad idea to me
should be 100% okay for a little couch co-op game among 4 friends though
like this boss room sample
looks like the kind of scope network for gameobject is intended, right ?
I'm not a coder, I know about clientside/serverside things and how things can be hacked and stuff, I just wanna prototype stuff, nothing for serious production
3 years ago i could download Mirror, slap Client Network Transforms on prefabs and bam it was working
Nowadays everything becomes such a hassle with unity
yeah this will be totally fine for learning the ropes, and again, you don't expect you friends to cheat, so as long as you don't release towards unknown public, that'll do 👍
@patent fog but since we are on the topic and you seem to be quite familiar, most games do infact trust user input first, and only divert from it if the server disagrees with it right? I'm not waiting my 50ms ping for my character to move inside my local game that is networked to a server
yes you described client prediction
but in the first part of your sentence, having the server validate and override the position, is going back to server authoritative model
🙂
By reading this component class, it looks like it will never let you perform this check on the server side
How so? The server will always get the position information of the player, and could simply do a check if the new position is even possible to reach given the players movement speed and other conditions, or am I missing something?
having the server validate client input and eventually fixing it afterwards, is called server reconciliation
Exactly how you would do it yourself on a server authoritative model, you have good logic for a non-coder 😉
Though I'm talking in the context of this component particularly
I'm just talking theory here :D I do know C# but I don't know advance mathmatics
I don't know the internals of Network for Gameobject, but it looks like there's an event when the server will asks to know who's authoritative, the client will grant itself authority. So at this point I guess the server just assume it will not do anything else with this transform```cs
/// <summary>
/// Used to determine who can write to this transform. Owner client only.
/// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
/// </summary>
protected override bool OnIsServerAuthoritative()
{
return false;
}
it's like parents asking their kid if they are allowed to boss them, the kid says "no, thanks" and parents won't even try harder to change the kid's mind :p
so now the kids does whatever he wants and parents have no opportunity to intervene
Is that a set-in-stone thing or can the server still revert this during runtime? Or at least make changes to, lets say position, overriding the local authority?
Ah well that answers it
Again never dig how it works internally, but the name OnIsServerAuthoritative suggests an event callback (because of the OnSomething)
I assume that event is checked every frame where a network command is sent (?)
or maybe it's a one-time check and then this network object is always trusted ?
Don't know really, sorry
because it's an event, it makes much more sense that it's not an only once thing
So yeah maybe you can change authority during runtime (which is doable for others network libraries actually)
And probably removing the component is enough to switch authority (?) 🤷♂️
Lot of speculation here, I'm talking withtout knowing ^^
Can a server simply remove components (of a client authority)? I imagine that would be something that could be circumvented locally, but again I'm not really a coder
The docs surely have chapters about authority, otherwise they don't deserve the 1.0 release tag 😅
Oh good question :p
Ah I see :D I Will look into that another time :) Do you know what the purpose of this Client Network Transform is then, if it is advised not to be used (in stuff where server authority is important)? Is it intended for just fun local multiplayer stuff, or just a work in progress and not quite finished yet? Any info? :C Again, the documentation doesn't really say anything in regards to this
I have no info so maybe someone else can answer. But yeah all statements you made are valid assumptions
Ay okay, so currently people who use netcode for gameobjects are probably writing custom code, I am assuming
Was very much hoping for it to be a semi-plug-and-play solution, guess that would be too easy :/
so yeah to summarize, good for havng things easily sync their movement and quick prototyping, won't cause any concern for fun local multiplayer, never use that for public online commercial project 🙂
For the little I've seen about this solution, I'd say it's middleground
don't have to code your own transport/messaging system, but no it's not 100% plug-and-play, you need to add your own gameplay (though with the samples they made a good job it seems, feel free to inspect their code)
Plus you'd need additional services for hosting and matchmaking for example
if i wanted to set a variable to false after an anim finishes playing, what would be the easiest way to do so?
is there a built in unity method that lets u do this?
Not really a network question ? more like #🏃┃animation 😉
Anyway one solution could be animation event on the last frame of the animation. See: https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
I don't use animation, so other than that, not sure if Unity provides callbacks or events for end of animation
oops sry wrong chat, thx for the help anyways!!
@patent fog Thanks for all the insight, very helpful! One last thing I'd be interested in, if you'd be so kind, is how would I imagine someone "hacking" a game, would they just access lets say the variable that controls movement speed somewhere in the ram where its stored, and then since they move fast locally and send position info to the server, the hack would be successful? If so, could I somehow replicate this so I can test my own ideas to catch or prevent this from happening?
Dude you sure you're not meant to be a coder ? ;p Yep, you describe a cheat engine. Lets you inspect Memory assignation and find variables.
Also for networked games, you can use sniffers to see webrequests going away from your computer towards the server, and if any param is let for the client to set, you can send your own requests and cheat (let's say for example a buy button for a market: if one of the params is the quantity, you can add way more, hoping there's no server authority ^^)
Not sure I can post the link to Cheat Engine, even for educational/debugging purposes only (?)
I remember Mirror having a great introduction documentation on the topic, hopefully it was this link https://mirror-networking.gitbook.io/docs/faq/cheating
Hell no, I get nightmares only by reading the word quaternion, let alone trying to figure out what namespaces are and why I should care >_>
Aight guess its time to experiment then, again thanks for the help!
haha don't worry quaternions make sense for no human 🙂 Good thing is you don't have to understand them (I don't) to use them. And you didn't pick the easiest of topics as example ^^
Alright and time for me to go to bed, glad we could have this little talk
Have fun !
what's the correct way to network footsteps?
Please, can someone advise on following
We are currently building a multiplayer game with Unity engine and similar to Mario Kart (https://mariokarttour.com/en-US).
We want to implement a game with Server-Client architecture and want to know a good framework which can work with following requirements:
- Supports Web-GL, Android and iOS deployments.
- Independent master and client logic development in separate projects.
- Server Authoritative with full access to server control and deployment .
- Integration of 3rd party services such as Matchmaking, Leaderboard, Analytics, Remote Game Config, etc.
- Dedicated support/ Community Support
Thanks!
I couldn't find a better place to ask this, so here goes... Where are Unity's logs located from running a headless server on an Linux machine (Ubuntu)? Thanks in advance.
best place would have been google https://docs.unity3d.com/2021.1/Documentation/Manual/LogFiles.html
having a few issues using mirror networking, my players cant see the animations, even though i have a network animator on client auth with my animation linked, and the players also seem to flash and fall through the ground then back up repeatedly, any ideas what could cause this?
all commonly used unity networking frameworks assume that the client and server are to be the same project, if you split the projects you loose most of the benefits of these frameworks.
im trying to get JSON data from an API call, but im getting HTML data instead, does anyone know why?
i want to call this :
i did this :
when i open the link manually, it shows the JSON data
is it possibly because of cloudflare or something doing browser checks?
yes
is there any way around this?
just look at the html what it says
it says "checking browser:"
hmm
usually your target service would have an API that takes some form of authentication (a token) that binds the request to a user account for rate limiting
Hi, what is the proper architecture and library for making and deploying WebGL multiplayer game
I'm learning PUN now and they said PUN doesnt really support WebGL socket well, they recommended using their server Photon Cloud
I also read somewhere and they said I should make a server using node.js, but i dont really know sure how to combine that with PUN and how to override PUN socket
anyone have experience in this?
I have no idea where you get your info but that's mostly wrong, sorry.
PUN supports WebGL but we'd recommend Fusion by now. It's a much more up to date networking solution and also supports WebGL.
The Photon Cloud is the managed backend for PUN and Fusion alike. It makes your life easier as it provides matchmaking, load balancing and more without the need to setup and run machines yourself.
thanks for your response. I will try to learn it.
@austere yacht Thanks for response are there any suggestions.
Cons: If server and client logics are on same project, I think there will be security issues.
Having issues with mirror, my players seem to flash there and not and also fall into the ground and back up, and my weapon animation doesnt show either, ill attach my player controller code and a screenshot if anyone can help me out it would be appreciated, been stuck on it for a while now and dont want to continue until i can sort it out, cheers
The animation code is on the last line in firing, not sure if i have done that wrong and thats why animations dont show? im very new to unity but mainly just want the player flickering / falling fixed. I also have a network animator on the player and linked the animator on the pistol
I looked through those but the closest I could find does not point to the files, that's why I had to ask here. @austere yacht
you can exclude server code from the client build with pragmas, for example #if SERVER_BUILD and if you keep all your client/server/shared code in partials or separate classes this is fairly straight forward and easy to validate in a code review.
Hi, I'm currently exploring the unity's netcode for gameobjects for my online board game. I just started to implement the multiplayer aspect (starting from generating the board) but I get the issue where the client cannot spawn some cells locally but the server did spawned everything correctly. I worked along the API documentations and tutorial. These are the console logs. I'm sure the prefab for the spawned cells is registered in the NetworkManager. The missing pattern though is the same every time but also doesn't have a specific pattern so I cant quite figure out what went wrong with the generating algorithm either. I am very new so may be the log would help me identify the problem I've done that I don't know . Could someone help me , sorry I'm a beginner.
plz halp
A guy is helping me make a game in Unity and I had a question regarding storing the player's info and stats, as to help prevent hacking and modifying the file. We are using Photon for the game server, but as far as the player's information and having accounts linked to them, what would anyone recommend? Thanks!!
im new to doing multiplayer things and am trying out unity netcode, how can I send a message to the host for example "jump" from a client
Photon is a company, not a product. You need to be more specific.
With a RPC https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/messaging-system/index.html
An introduction to the messaging system in Unity MLAPI, including RPC's and Custom Messages.
Do they offer any protection against hacking or altering the game stats or features?
Or who would...?
the only protection against hacking is air-gapping your network or writing secure code, your middleware can only make sure it itself is written securely
Thanks!
IMO the way to do that would be to not network it at all. That is, footsteps should be left behind by the local instances, so they would require no network sync of their own. Assuming whoever is leaving footsteps behind is already net synced, that way wherever those are in any given client, they would be leaving footsteps behind themselves.
that is to say, I'm assuming it's preferable to have footsteps be visibly consistent with whatever is leaving them behind than to be accurate to the actual path travelled, so there is no need to ensure each footstep is synced. It can just be a local effect that happens on each client.
Hey guys. Just started working on a prototype for a multiplayer game using Netcode for Gameobjects.
With 2 players spawned in I cant move the client player at all unless I disable the Network Transform component but then it doesnt update the position. Am I missing something?
Also if this helps. This is the movement script
Hi, I wanted to make a multiplayer game and upload it to unity but it says that photon doesn't support webGL builds. Is there another multiplayer runner that supports webGL?
Or can you make multiplayer WebGL games with photon? It's actually not that clear
I believe you can get some sort of extension for Netcode for Game Objects that works with WebGL
I understand that the basic package does not support it tho
Unity Multiplayer with webGL is definatly possible somehow, theres many internet games made with unity that have managed it somehow
such as Fall boys lmao
looks like the pinned msgs for this channel list some of the options for mulitplayer with unity
You're using a Rigidbody, add a Network Rigidbody script onto your player
Also, don't use NetworkTransform
use ClientNetworkTransform
it overrides the former by making it not require ownership to interact with Rigidbodies
Also noticed you are working on 2D, my bad
but I networked my Rigidbody movement using this
I dont seem to have a ClientNetworkTransform.
Hold on
A small-scale cooperative game sample built on the new, Unity networking framework to teach developers about creating a similar multiplayer game. - com.unity.multiplayer.samples.coop/ClientNetworkT...
Here you go
Ahh so we need to write everything ourselves in that script?
Nope
It is essentially NetworkTransform
Just attach that script to your player and see what happens
How do we import it? Using the url doesnt add it in Unity
Just copy paste the code
Am I missing something? Its 22 lines and seems to be only overrides. Nothing is actually doing anything
You're not missing anything
That script is the only thing you will replace NetworkTransform
You don't need to download the whole github repo
For some reason, this script isn't syncing My default Player prefabs transform across the different clients
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Would appreciate any help on this thanks!
How does fishnet compare to unity's netcode for game objects? I saw some performance benchmarks where fishnet looks faster. Wondering what feature differences there are though? Anyone have any experience with either?
perhaps asking in the official unity networking dc would be good
Awesome thank you!
its in the pins
ah, thanks!
Networking newbie here, should I put the lobby system in a separate scene from the game or is that overcomplicating it? I'm using netcode for gameobjects and the lobby/relay system if that matters
I normally do, just to keep things seperated
I need much help
I normally don't ask for help but I've been struggling with this for a good few days and I have no more clue as to what is happening
This is my script, and it's worked fine for a few months, but as soon as I made my project build for IL2CPP and UWP, it stopped working
most of it is ignorable and game-specific, but the important part is that ConnectUsingSettings() returns true, but the state is "Connected to NameServer", and OnConnectedToMaster() never gets called
After changing the photon dlls to use IL2CPP and enabling full logging, I get this cool error(about 1 every 3 frames) that google seems to know nothing about:SendOutgoingCommands ignored socket is not connected. pid:65535 UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object) UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[]) UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:Log(Object) Photon.Realtime.LoadBalancingClient:DebugReturn(DebugLevel, String) ExitGames.Client.Photon.EnetPeer:SendOutgoingCommands() ExitGames.Client.Photon.PhotonPeer:SendOutgoingCommands() Photon.Pun.PhotonHandler:LateUpdate()
any help is helpful, and if you decide to reply (with any ideas), ping me
How did you change that? Afaik you don't need to do anything to the DLLs.
what function can i call in photon that will run when a player joins the room
in the import settings
I was just grabbing at straws (is that the expression?) but I can change it back
any recommendations for what to use for networking? are photon and mirror different modules?
so, I was trying to understand what kind of servers does multi player games like fall guys or Valorant use?
Does the services deployed there use UDP for relaying information about other players and their state , and then gRPC for invoking actions?
or is it simply gRPC or webRTC for everything?
I'm trying to set up relay but I get this error when trying to create an allocation:
nvm i just messed up the argument order
I'm very new to this but I personally watched this video.
https://www.youtube.com/watch?v=x8C63oZMrTU
I decided to go with netcode that just released and so far I'm impressed by how easy it is to setup.
uh riot games has its own custom authoritative server side with predictive client side
Ok but there must be some code/running on it, right?
So what protocol is used for multiplayer stuff.... or specifically if i want to create one such server what would i need to do?
you could try writing your own server with nodejs and host it with say heroku
it most likely wouldn't be as fast as PUN or NetCode because those are insanely optimized, but if you're willing to try go ahead
i dont suppose the server would be RESTful
So what kind of api would i need to create
most likely websockets
I've only used nodejs for web-based games and websockets are the best mo
imo
I'm not sure how to integrate that with unity, but there are def tutorials
Hi! I'm taking a look to the new networking for gameobjects, but I can't find how to use it with the steam transport. Anyone has a solution?
There's a Steam transport made from the community in this dedicated repo https://github.com/Unity-Technologies/multiplayer-community-contributions
(Never tried it, I just know it's there)
I'll let you try 😛
Yeah haha, I just found that too!
But it seems like there are two Steam options, SteamNetworking and Facepunch
I will need to check the differences
Steamworks is a set of APIs made available by Valve to allow developers to create integrations with Steam.
This ranges from the simple things like getting the local player's name, to more complicated things like server lists and UGC (Workshop Stuff)...
Thanks! ❤️
So, I installed the package.. but I can't find the facepunch transport..
Looks like you installed the ENET transport, and it is indeed in the list
By quickly reading the wiki, looks like facepunch get installed by dropping the dll files into your project, not through the package manager
Actually wait
the community extensions though, do get their install through the package manager
might be easier 🙂
Oh I see now, you blindly followed these instructions
you need to switch enet with whatver transport you'er interested in
@azure mango Hope that makes sense and get you unstuck
Sorry couldn't warn you before because I didn't try netcode for gameobject yet, just discovered that right now while investigating for you ;P
Oh lol I understood that wrongly xd, I readed like, with this you install everything and then select the transport 🤦♀️
Thank you hahaha
Actually now that I'm reading it, you might be interested to install the whole extensions package, not only the transport
Comes with some nice additional utilities
but depends on your game, as you see fit 😉
Have fun !
n.n
looks like netcode is also using websocket with UDP
Websocket is always TCP
Whats the best way to do weapon movement? i have a parent constraint linked to my main camera and it works well for the player, but it doesnt sync over the network as moving up and down
You probably shouldn’t sync cosmetic effects like that
I want other players to see where others are aiming
then sync the transform of the weapon
It rotates with the player body but just unsure on the up and down movement that follows the canera
I thought it'd be fine with a parent constraint as the weapon is apart of my player (only have 1 wep so far)
As the player the gun rotates to follow the camera just others don't see that
you still need to sync it
it’s a component
Best not to do multiplayer as a first project
Yeah I know, I like the challenge though, more doing it for fun. Just making a basic co op shooter to mess aroubd with mates
it’s not the challenge
Never going to be a finished game haha
it’s just impossible to do it sensibly without knowing the engine before setting it all up
Got my map made, players , water, wind, reloading, ammo count, health and basic ui, just gotta work on shooting and respawn and I'm happy haha
and multiplayer being multiplayer, you can’t just change it all mid project
Yeah I know I'm probably doing stuff in a bad way, watching videos and mashing what I learn together
Yes, that’s generally very unproductive in the long run
But good enough for having fun with it for a while
ive learnt xD
as i said, more a hobby than anything
quick one, would it be a network transform or transform child as its a child object?
child
rogey
Hi. I’ve read multiple times that a multiplayer objects makes the game 3x the effort so I’ve always avoided it. However, seeing that network for gameobjectss is 1.0 I keep thinking it might not be like that
The use case for my game is co-op, so it allows me to ignore the anti cheat, match making and public server aspects
Does this still mean 3x the effort?
nothing fundamental changes regarding multiplayer with netcode for gameobjects
you can still do the exact same things with the exact same amount of effort reaching the exact same performance you could before with other packages
the idea that netcode for gameobjects is only for coop peer to peer multiplayer (code monkey opinion) is silly btw.
Oh I wants trying to say that (I didn’t see that opinion from code monkey)
I was more asking if coop peer to peer is something that is feasible or if it 3x the project size as people usually mention
Unity's lead netcode engineer seems to share that silly opinion 😛
You can get away with a lot more and lean on to more services, so I would say that yea, it's a lot easier.
Maybe that’s because it doesn’t have any builtin mechanisms that facilitate competitive multiplayer or MMOs and they want to manage expectations. Seems to me the ‚mid level api‘ concept got lost somewhere
It probably is primarily that, but I have no idea what kind of reworking of the MLAPI they have been doing and what the state of that might be.
I think the "you can still do the exact same things with the exact same amount of effort reaching the exact same performance you could before with other packages" is misleading unless you start every project on these frameworks by completely removing everything except the low level messaging API.
Even then you are probably going to find pretty major differences
They all amount to the same thing. What you can and can’t do with these frameworks is totally up to your custom code on top of them.
What is the best way to move my weapon up and down? having trouble getting it to sync. It works fine for the player but for the other players they see the weapon staying still. It rotates with the player body but i cant seem to get the up and down to sync to other players. I have tried putting it under the main camera, but then players cant see the weapon at all, maybe because main camera is disabled if youre not the main player? i have also tried having it under the player body and using a parent constraint, works good for the player but still stays still to the other players.. Have also tried a network transform child that didnt work either. What is the best way to sync the up and down movement?
Help I am going crazy I am using NetCode and a really basic character, when I start as a host it works and as soon as my client joins I can not control host character anymore cuz both controll the client that joins
not necessarily "the solution" but putting if(!IsOwner) return; at the start of your update function might solve some issues
I don't really know then sorry.
Thank u for trying atleast :)
Anyone got any ideas? it all works fine but when a client joins the host can not move his own character anymore only the client
Let me explain more detailed: When I host the game it works fine I can move the character normally and when I join on a client the client can move exactly like it should but when I go back to the host the camera has frozen and the host controlls the client and the client controlls the client so the host is left unmoveable.
This is the character
I really hope someone can help me I am new and I really want to learn :(
Please can someone please help me out, only the host can move and I can't figure out why my code isn't working. I am very new to unity networking
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class PlayerScript : NetworkBehaviour
{
public Rigidbody2D rb2D;
public NetworkVariable<Vector2> Position = new NetworkVariable<Vector2>();
public float speed = 10f;
void Update()
{
if (!IsOwner) return;
Move();
}
void FixedUpdate()
{
if (!IsOwner) return;
rb2D.MovePosition(Position.Value);
}
public void Move()
{
if (NetworkManager.Singleton.IsHost)
{
Position.Value = rb2D.position + GetInput();
}
else if (NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsHost)
{
MoveServerRpc();
}
}
[ServerRpc]
void MoveServerRpc()
{
Position.Value = rb2D.position + GetInput();
}
private Vector2 GetInput()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
return new Vector2(x, y) * speed * Time.fixedDeltaTime;
}
}
If movetoward() is inside fixedupdate is it deterministic?
Question I'm trying out the new Unity netcode but if I spawn a player prefab the client is not the owner of the object?
Which seemed strange to me? is this correct?
The client would be the owner of the player prefab
If there are 4 clients there will be 4 prefabs and each client will be the owner of one of those prefabs
Ah I tried it like this now
public override void OnNetworkSpawn()
{
if (IsOwner)
{
examplePlayer = Instantiate(playerInputPrefab);
exampleCharacterCamera = Instantiate(cameraPrefab);
}
if (IsServer)
{
exampleCharacterController = Instantiate(playerPrefab);
exampleCharacterController.GetComponent<NetworkObject>().Spawn();
}
if (IsOwner)
{
examplePlayer.Init(exampleCharacterController, exampleCharacterCamera);
}
}```
But didn't seem to work
In your network manager in the scene is there a player prefab assigned?
Ah I see, the example CharacterController is null as it is being spawned on the server so it loses refference
I guess there is not an easy way to find that instance or you spawned player
Pls help
I think you're not supposed to use Start and awake methods with network. It might mess with your host's rigidbody reference when your client joins, I assume.
Better use the joined callback (don't remember how they're called)
Networkvariable are readonly for the client by default. So quickfix might just be to override that permission in the constructor (check documentation for details).
But then your client becomes authoritative, so beware.
I think a better way is to register to the onValueChanged callbacks 🤔 but honestly I didnt really read your code carefully :p
Quick answer I would expect NOT
How would I be able to move units in a deterministic fashion?
Hmm I think there is a onNetworkSpawn function
so i have a raycast with a trail on for when i shoot my gun, how can i sync the trail across the network so other people can see it?
you drive it with the same parameters on all clients
movement seem to work fine now but as soon as a new player joins everyones camera goes to them can someone see what i am doing wrong
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
public class FirstPersonLook : NetworkBehaviour
{
[SerializeField]
Transform character;
public float sensitivity = 2;
public float smoothing = 1.5f;
Vector2 velocity;
Vector2 frameVelocity;
private void Awake()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
if (!IsOwner) return;
// Get smooth velocity.
Vector2 mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
Vector2 rawFrameVelocity = Vector2.Scale(mouseDelta, Vector2.one * sensitivity);
frameVelocity = Vector2.Lerp(frameVelocity, rawFrameVelocity, 1 / smoothing);
velocity += frameVelocity;
velocity.y = Mathf.Clamp(velocity.y, -90, 90);
// Rotate camera up-down and controller left-right from velocity.
transform.localRotation = Quaternion.AngleAxis(-velocity.y, Vector3.right);
GetComponentInParent<FirstPersonMovement>().transform.localRotation = Quaternion.AngleAxis(velocity.x, Vector3.up);
}
}
you are running a script that only the local player needs to run on all players
@austere yacht sorry I am now how do I fix that?
check NetworkBehaviour.IsLocalPlayer
If a NetworkObject is assigned, it will return whether or not this NetworkObject is the local player object. If no NetworkObject is assigned it will always return false.
I have a networkobject assigned to the player prefab do I need one for the camera aswell?
the camera does not need to be synced
it just needs to follow/point at the right object and be controlled by the right inputs
well, i would advise you understand the concepts so you can decide for yourself if its "good"
if you ask if the code you show is good, then no, its bad code
but it may work or produce the effect you want regardless of that
it does not work the client can not move its camera
and the hosts camera gets set to the clients camera on client join
well, host based netcode is confusing
you just have wrestle with it until you figure out why it isnt working
and you can only figure that out by really understanding what it means to do do host based vs dedicated server
i have been trying for days lol
how did you approach solving it?
tbh im so lost rn lol
well, you picked the most annoying and difficult way to learn multiplayer
what is the easier
its much easier if you do it with a dedicated server
oh
then you can ignore all the cases where the client is also the server and all your assumptions about authority and ownership get messed up
maybe there is a way to do simple multiplayer without authority in a host-based architecture that is easy to understand but idk about that, authoritative host based multiplayer is a mess to understand
conceptually what you need to do is: direct all input only to the local player and on join attach the camera to the local player (not the new join)
public class Player : NetworkBehaviour {
void OnNetworkStart() {
if (IsLocalPlayer) {
GrabCamera();
}
}
void Update() {
if (IsLocalPlayer) {
ReadInput();
HandleInput();
}
if (IsServer)
TickSimulation();
if (IsClient)
HandleUpdatesReceivedFromServer();
}
}
im trying to make a co op game that wont really matter if there is "cheating" lol so how do i just let the client manage everything
there is always a server that handles distribution of the updates and you need to send all updates to it so it can do that, you just don't have to worry about permissions and validation, meaning you can force the server to do what a client tells it instead of having clients ask nicely for it to do something, in both cases you have to deal with conflicting requests from different clients, that's what ownership does and to keep thinks simple only the owner of a thing can change it. the only thing authoritative servers do is retain that ownership on all objects but the player objects which then are generally only used as communication routers.
in a way clients handling stuff themselves (each running their own sim) is more complicated than doing it all on the server (running one shared sim)
im trying to use this right now and I am getting no where I am so lost
have you followed one of the example projects?
The Bitesize Samples repository provides a series of sample code as modules to use in your games and better understand Netcode for GameObjects (Netcode).
okay i got somewhere both cameras work as the should but the client can not move only look around
idk why tho
should I use a client network transform or network transform on my player prefab
guess i will just have to give up on my dream
I have an issue where my client player moves a lot slower than the host player does anyone know how fix it?
How can I send messages to all clients as a client?
How can I spawn a object as Client? I'm to stupid! I only can find answers on how to spawn as Server but I just want to spawn a GameObject with ownership as Client
Just how
GetComponent<NetworkObject>().SpawnWithOwnership(clientId);
Netcode for Gameobjects' high level components, the RPC system, object spawning, and NetworkVariables all rely on there being at least two netcode components added to a GameObject:
I did that but I always get the error, Only Server can spawn NetworkObjects
I just want to spawn with an ServerRpc or whatever idk
Yeah you could call a server rpc and give ownership to the one that called it
I've written a custom messaging handler and whenever I send a message to other clients as a client I receive the error: InvalidOperationException: Can not send unnamed messages to multiple users as a client
Ye but I have this Problem:
I instantiate a Object on a Client, I want to spawn the NetworkObject-Component, buuuut all th einformations about the Object are on the client. The server has no Idea wich Object this is and I dont know hot to say to the server as a Client something like:
Ayo mister Server, see that NetworkObject overthere? Spawn it! And the Owner shall be ClientID...
https://www.youtube.com/watch?v=3yuBOB3VrCk&t=2s at 43:15 he talks about spawning network objects
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
Quantum Console https://assetstore.unity.com/packages/tools/utilities/quantum-console-211046?aid=1101l96nj&pubref=ngo
FREE Third Person...
thx
He doesn't really talk about giving ownership though
I already figured that out, I found literally anything, but a solution on my problem 😂
Yes but only on the server... :/
can you check if(IsOwner)
GetComponent<NetworkObject>().SpawnWithOwnership(OwnerClientId);
He only talks about how to spawn it on the server. Is there even a way to spawn anything as a client?
When you call the serverrpc to spawn the network object from your client also send OwnerClientID and on the server say GetComponent<NetworkObject>().SpawnWithOwnership(sentOwnerClientID);
I guess try that once?
Yes, thats not the problem, i just dont understand how to send the object to the server. I instantiate a Object on a Client and want to spawn it. But I cant send the Object to the Server to spawn it on the server. I know how to send the ID I just need to know how to send a networkobject.
Basically I want to remove the restriction of clients not sending messages to other clients
There are a couple of way you could do that. You could give the prefab a guid and send the guid.
whats a guid?
globally unique id
Uhmmmm.... 😅
if you have a list of prefabs you'd like to instantiate and send an index of the prefab you want to instantiate instead of the whole thing you could grab the prefab from the list given the index on any device
So I should instantiate on the Server?
That's my understanding if it isn't letting you instantiate on the client.
I can Instantiate on the client but I cant spawn
*on the client
someone else may be better suited to help you. I'm working on a project that is deterministic so all of my objects are instantiated locally and I only send input.
but yeah i'd instantiate them on the server and not worry about ownership
if/when i make my game multiplayer, how would i go across making your player see something that others cant? for example, the fps hands have to be put in a janky looking position to look right in the camera, but i dont want other players to see it since it looks really weird from any other perspective. how could i basically create a set of hands that only the player sees, and a set that only other people see
ping me if your responding please.
Enable/disable the fps model depending on if its local player or not
Or play with Layers
Howdy smart people! Can someone provide a solid guide on using and understanding how to get started with Mirror? Their on site tutorials show you how to get it running with steps and code snippets but I can’t find anything that explains what each new line and piece of code actually does and how to utilise them outside of that specific tutorial
Hello, can someone guide me?
I'm trying to make a game. In which user have to connect with its Facebook. Not sure how games show the Facebook option to login through Facebook.
If anyone can guide me, that would be great.
When using Netcode with unity lobby/relay service is there any way to get lobby pings? So for example I'm doing Lobbies.Instance.QueryLobbiesAsync() to pull a list of lobbies. Each lobby has a Relay join code. Is there a way i can get the ping to each lobby host?
hello, i cant seem to be able to install the Multiplayer Samples Utilities to have ClientNetworkTransform component
I watched this video, but I can't play with my friends how can I host the game so I can play with my friends on different internet connections?
how did you manage to download the client network transform?
i cant seem to download mine
or install a package from git URL "https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop"
yea this worked
thanks!
for some reason im not able to find that package through the git URL
im downloading a new editor version
maybe mine is outdated since last time i used unity was some months ago
Hey guys I have been working on a game using Netcode for Gameobjects and everything seemed to be working fine until I attempted to only have two build versions connect to eachother. When it’s the editor + a build connected together it all works properly and everything is correctly set. However whenever I have two builds playing together a lot of my ServerRPC seem not to work and it seems that a lot of data is not being sent over.
Hell everyone!
I am currently following a tutorial on netcode
and it is made my code monkey
at the start everything seemed to work
at the time I reached the animation part the animation worked fine but the client couldn't move only the host and second of all my client network transform was also added
Photon the company has many products like Fusion and PUN
and what is the best?
Pun
Cause I have trouble to sync the states (true and false, and vars) on PUN
Have you searched that on google?
yeah
I alr found smth but it is so complicated and Time wasting. There has to be an easier way
Send me the link
I will try to simplify it
for what?
You said you already found something but it is complicated?
Multiplayer Photon PUN RPC - Freezing Player Over The Network - Among Us Part 9
Download Script: https://github.com/smartpenguins/Unity-Random-Files/blob/main/AmongThem/CharacterMovement.cs
-Among Us Series Playlists-
with C#: https://www.youtube.com/playlist?list=PLrw9uFU6NhfOnEhqi7DRbx-eXiTrmbVGD
with Bolt: https://www.youtube.com/playlist?...
Only the part of sync with RCP
thats easy in the video but not in reality xD
I will check the video out and simplify once I have time
There's loads of networking solutions, if you don't like PUN try out Netcode for GameObjects or Mirror
Remember that multiplayer games can get really complicated really fast
Hello, do someone know how can I setup netcode so I can play from different internet connections??
Hello,
I'm trying to spawn a character on the server through a class, I want the client to have a reference to this spawned object.
How would I do this easily?
{
characterController = Instantiate(characterControllerPrefab, transform);
characterController.GetComponent<NetworkObject>().SpawnAsPlayerObject(OwnerClientId);
if (IsOwner)
{
playerCamera = Instantiate(playerCameraPrefab, transform);
playerInput = Instantiate(playerInputPrefab, transform);
}
characterController //how can the client know here about this class
}```
you don't you use one camera and make it follow the local player
oh i was instatiating each camera for each local player
hmmm it still doesnt work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
using Unity.Netcode;
public class NetworkCamera : NetworkBehaviour
{
[SerializeField] private CinemachineVirtualCamera virtualCamera;
void Update()
{
var playerTag = GameObject.FindGameObjectWithTag("Player");
virtualCamera.LookAt = playerTag.transform;
virtualCamera.Follow = playerTag.transform;
}
}
you can't find a local player with a tag, you need to check for NetworkBehaviour.IsLocalPlayer
and you should have the local player inject itself into the camera or a manager script, much more straight forward that way
you could maybe also find the local player via NetworkManager.LocalClient.PlayerObject
how would i inject the player into the camera?
im sorry im completely new to netcode and networking
not into the camera, into your networkcamera script
and you do that like with any other script
how would i implement the isLocalPlayer?
if (IsLocalPlayer)
{
have camera follow player(?)
}
hmm i see what you mean
i'd put the script in the player instead of the camera
its a property you inherit from NetworkBehaviour
that makes more sense yea
yea i know i just dont know how to use it properly
is it something like this?
maybe you need to work a bit more on the overall unity and C# fundamentals
and im just confused asf too
and yea been a while since i last used unity gotta recheck it again
well, netcode is confusing at the best of times, if you are also confused about c# and unity stuff you'll have a tough time
nono
i just mean
so i was using tags right
im just asking how i'd use the IsLocalPlayer
i know it inherits from NetworkBehaviour
like this
ah alright i was just confused about that
since the docs didnt really seem to answer my question, or i didnt search well enough
ill give it a shot
thanks!
alright i made it work
but i added a camera for each instatiated player
[SerializeField] private CinemachineVirtualCamera virtualCamera;
void Start()
{
virtualCamera = GetComponent<CinemachineVirtualCamera>();
}
void Update()
{
if (!IsLocalPlayer)
{
virtualCamera.enabled = false;
} else
{
virtualCamera.LookAt = this.transform.parent;
virtualCamera.Follow = this.transform.parent;
}
}
basically the camera will always look at its parent object which is the player
thank you for the help
this might not be the best solution but im satisfied for now
Could anyone help with with this problem
So when u create a room the player is fine but once the 2 player join both players cant move does anyone know why this is???
Hi there! I'm getting an error, Invalid network endpoint: 192.168.1.137:7777. Where 192.168.1.137 is the IPv4 of another computer on my network running a build of my project. Why might this be? (Please @ me if you respond) Thanks!
It may be important to note that on one computer, I'm inside the unity editor, and on the other one I'm running a build. I have also not muddled with server listen address at all.
where are you putting this address and what exactly gives you the error message?
I'm putting this address into the UnityTransport using NetworkManager.Singleton.GetComponent<UnityTransport>().sendConnectionData or smth
it was an example on the docs
but doesnt seem tto be working
well, you need to be more exact
the port should go into the port field and the address into the address field
this format of ip:port probably isn't valid
hello. how do i give write permission to clients?
How do i use photonNetwork.instantiate scene object???
Hello. I am working on a Multiplayer Game with NetCode for gameobjects and was wondering how to have a script run on the server and not clients. I would like the server to have a countdown to spawn in objects. I’ve tried serverRpcs but then it runs multiple times depending on how many clients there are. Any help will be very much appreciated
You can check the IsClient, IsServer and IsHost properties on all scripts that inherit NetworkBehaviour
How would I ensure it only runs once?
Could anyone help me plzzz???
Do the docs not cover it?
Helo, small question sorry if its stupid. I have a ClientNewtworkTransform (netcode for gameobjects 1.0), how can I code something like a ClientNetwrokMeshRenderer? That means, making changes from a client to its mesh renderer, and it being reflected on every other client and the server?
Should I use a server rpc, or a network variable, or is there something else available to achieve this?
What kind of changes do you want to apply to the renderer?
In this case, change the whole material
From one predefined material, to another (in a list)
This code will not work, as the client never updates the server not the rest of the clients
If it's something like a skin, I'd just share the skin Id or something. Then apply the correct material locally.
ok, so a server rpc then? which takes and applies that effect to all the players?
in this case, the material with its id
Yeah, an RPC would work.
ok, thanks
No
I was looking through
And couldn’t really see anything
To do with it
You've seen this page?
https://doc.photonengine.com/en-us/pun/v2/gameplay/instantiation#photonnetwork_instantiate
Yeah
So i found out eventually
About the syntax
But
It doesn’t really work how i want it
How do you want it to work?
So i have the player in the scene not as a prefab
And i want it so that when 2 players connect it uses the player from the scene
Not the prefab
And then gives every player a random number between 1-2 depending on what team they are
I don't think that's possible. You'll have to instantiate them manually via an rpc.
Oh how do i do that???
There's a section about it on the page I shared:
https://doc.photonengine.com/en-us/pun/v2/gameplay/instantiation#photonnetwork_instantiate
It's not using the rpc, but network events instead
It doesn't have to be a prefab. It uses the default unity Instantiation, so it could be any object.
Can it be a object from the scene???
Yes. Any unity object as I said.
Should probably look at unity instantiation if you ask questions like that. 😄
Would i have to do instantiateSceneObject???
no
Yeah i never use it when i make games unless im adding projectile based shooting or someth
Something
Never for the player
Doesn't mean you don't need to know about it. Or can't look at the docs.
Yeah i mean i know how to use it but I just never used it to spawn players
So would i have to write this public void SpawnPlayer()
{
GameObject player = Instantiate(PlayerPrefab);
PhotonView photonView = player.GetComponent<PhotonView>();
if (PhotonNetwork.AllocateViewID(photonView))
{
object[] data = new object[]
{
player.transform.position, player.transform.rotation, photonView.ViewID
};
RaiseEventOptions raiseEventOptions = new RaiseEventOptions
{
Receivers = ReceiverGroup.Others,
CachingOption = EventCaching.AddToRoomCache
};
SendOptions sendOptions = new SendOptions
{
Reliability = true
};
PhotonNetwork.RaiseEvent(CustomManualInstantiationEventCode, data, raiseEventOptions, sendOptions);
}
else
{
Debug.LogError("Failed to allocate a ViewId.");
Destroy(player);
}
}???
A player is a gameObject like any other, so there's no much difference.
U don’t have to instantiate the player if there in the scene
Next time follow the #854851968446365696 guidelines on sharing code.
I assume PlayerPrefab is the reference to the object you want to clone?
Ye the one from the scene
Then it should be fine I guess. You just need the to add other part that receives the event as well.
Would it be in the same script??
I've no clue where you put the first part, but it shouldn't mater that much as long as the script is in the scene.
aah
actually
Yeah the script is on a empty game object
Yeah, it should be fine.
Called spawnplayers
So should i put the other part into the spawn players script to
Or make a different one??
It can be anywhere, since it's a photon event. Logically it makes sense to put it in the spawn script.
Yeah makes sense
Let me try and see if this work thank u so much for the help
Why am I getting all these errors???
Probably missing a namespace using
I have photon.pun
what does you IDE sugest?
Using photon.realtime
Then do it
Yeah i added the 2 i needed
But i still have errors
It says for me to make a public byte
Share the whole script and the error details
what does your IDE suggest?
Making a public byte
Make it then.
It's part of using the network event. You can learn more about it here:
https://doc.photonengine.com/en-us/pun/current/gameplay/rpcsandraiseevent#raiseevent
Oh so making the byte was the problem???
Not making
It didn’t work the 1 players loading in and when the 2 player loading in the 2 player cant move and the 1 player can’t see the second player and the 2 player can’t see the 1st
Then you're doing something wrong. Share the updated code
Does photon print any logs in the console?
Are there any errors?
If photon doesn't print, increase it's verbosity
Could be that event code is not available. If you don't assign it value, it's gonna stay 0. And 0 is probably occupied by Photon internal events already.
Either way, seeing the logs should shed more light on the issue.
No
There is nothing in the console
At runtime?
Add a debug log to the spawn method to make sure it's even called.
And increase the verbosity of Photon
What do u mean by that???
verbosity is logs level. Usually it's set to errors only, but we want to see what's photon doing, so set it to the lowest level possible. It should be in the Photon settings asset file.
I can’t find the settings file
I went into the photon folder
And i have photon chat, libs, realtime and unity networking
I think it's in Photon - Resources folder.
You can also probably get there via the menu at the top
You should know where it is, because you wouldn't be able to use Photon in the first place if you didn't set it up. There's App id and whatnot.
I don’t have a resources folder
I set that on import
Well, what can I say, look it up...
Take a screenshot of the unity editor window
Of the whole unity editor window
Including the top menu...
Is there anything photon related in the window?
Btw, I wanted to ask earlier, but is there any reason you don't want to instantiate the player prefab?
Yeah
highlight server settings
Well, that's just a very poor design decision...
Ik
I can’t really change it now tho
Ok so pun logging is set to errors only
Should i set it to informational or full
set it to full for now
K
I have this
Menu for rpca
Rpcs
Would i have to do anything here by any chance
No. You're not using an rpc in this case
Is that after the spawning?
Ye
Is that on the server or the client?
Client
I have a room thing
So once the room is created
The player spawns
And then yeah
Thats
I mean, is it on the master client?
The console after that
Yes
a network event should be reflected in the logs afaik.
If it doesn't then your event doesn't work.
Ye there isn’t one
Ugh... I guess you didn't read the Raise event page after all..?
I did
Ok. Check the part about receiving the event again.
Yeah i have
But I don’t really understand what it means
Then ask instead of just ignoring it...🤣
Do you think it's gonna magically work if you don't follow the guidelines?
Well I copied the code
So I thought
And i just changed
Around some stuff like the pretab
Prefab
Gameobject
Copying the code is not enough. Networking is not a beginner topic. You need to understand what you're doing instead of just copying.
Check the final code example. Specifically the part about the implemented interface.
Then networking is too early for you.
No its cause there on about one thing and the example says another
Or learn to learn on the go. You're not gonna get far if you just copy stuff without understanding it.
Am i even on the right thing
Not really. The description corresponds exactly to the example.
If you don't understand something, google it. If you still don't understand, ask in the community. It's that simple.
Then you are on the wrong page. We are talking about RaiseEvent for 15 min or so already.
I can’t find any answers on google
All i find are the docs
To the same thing
Yeah and this page has the raise event
On it
Thought we were on about this
Then ask about what you don't understand specifically.
No we were not.
Well thats why i was confused
Cause u were on about a different thing
Ok now it makes sense im on the right page
Here's the first time I mentioned it:
#archived-networking message
Then I asked this and since then we(or at least me) were talking about RaiseEvent until now:
#archived-networking message
No, I clearly said "raise event page". But anyways, you know what to read now, so go ahead.
I read the raise event part right???
yes
The relevant part starts with:
To receive custom events, we have two different possibilities.
Ok so i have read it
What should i do from now
Cause im still super confused
On how am meant to implement this with my current
Code and way of making rooms and stuff
Well, it tells you about 2 options. Did you read what they are?
On enable and on disable???
Did you even read? It tells you the first option right after the sentence that I quoted...
The ioneventcallback???
the IOnEventCallback, yes.
I need it to receive custom events right???
Yes. You're raising a network (custom) event.
So you need to be able to receive it on the client.
Damn I thought networking with photon was mean to be simple lol
It is very simple
It just requires an intermediate+ understanding of C#, unity and coding in general.
You won't find a simpler networking solution.
Isnt there that mirror thing???
There is, but it's very similar to photon.
Networking is an advanced topic. It's repeated over and over again in #💻┃code-beginner
Yeah i know that im just new to networking with unity and stuff and i have no idea how to use photon
I do know how to use it a bit
But can’t find out
This one thing
The docs are there.
Im trying to do
Yeah but no matter how much i would read them nothing would help
If you don't understand the docs, it means that you either don't read them properly, or miss some prerequisite knowledge.
Because im trying to use the player from the scene instead of instantiating it
Then it's probably the latter. In which case either learn that prerequisite stuff or put the networking stuff on hold, until you're ready.
I do understand them but there was nothing on the docs on how to do this specific thing
But there was😅 Didn't you copy 90% of your code from a docs page just an hour ago or so..?
Yeah
Besides, docs are not supposed to give you a ready implementation of a feature. You need to be able to figure that out on your own.
So I didn’t have to write it out to save time lol
That's the difference between a beginner and intermediate coder.
The docs are there to teach you the api
I figured out a lot of stuff but ive been trying with this for like 4 days now
So I decided to ask here
That's fine, but you're still struggling with simple things after my explanation.
Yeah cuz its 4 nearly 5 am for me im tired af
Been at this for like 12 hours now
So thats why
Anyways, that convo is going nowhere. I'm not gonna tell you to stop doing what you're doing, but I'm not gonna spoon feed you either. Read the page, if there's anything unclear, google it, only then ask for help.
The issue is I don’t know what im trying to do with all this like what do i need a custom event for
To instantiate a player
I think we've already figured the part about instantiation.
I mean control a player
All you need to do is make your event work.
You can use any option you like.
But just a tip: don't try to avoid something you don't understand. Learn about it instead. That's the only way to improve as a coder.
It's not better or worse. I'd go with the interface method though, as it's cleaner.
Ok so does this code have to be inside the spawn player script or a separate script
What code exactly?
The one i was sending u before
Your code is fine. It misses some things to receive the event though. That's why you need to learn how to receive an event.
Oh ok
I could also try spawning the player
But i would have to recode
A good chunk of my stuff
Which I honestly dont know is a good idea
You can think about refactoring later. Get the event working first.
The issue is i have a camera in my scene and it follows the prefab but I can’t set that in a prefab it just doesn’t let me
And same with ui elements
Yeah but then there is like no point doing this if ima use a different way of spawning players later
Because the game will be like cs go so ima going to have to spawn the players
Anyways
When they die
If you're not gonna use an event, then there's no issue I guess..?
Just use the normal instantiation method
Yeah im just confused on how I would reference all the stuff
That the player needs
That's totally not a networking question anymore. You can ask that in #💻┃code-beginner
Could u just tell me by any chance cause it still to do with the networking stuff
It has nothing to do with networking. You'd reference objects the same way as you do in single player.
It doesn’t let me though
Cause the player is a prefab
What doesn't let you?
And the camera is in the scene
And not a prefab
And if i make the camera a prefab that causes the ui to not be a prefab
You'd need to assign the references at runtime after spawning the object.
And then doesn’t let me
With get component
I mean gameobject
That's one of the things you'll probably need to use yes.
As I said, I've no intention of spoon feeding you and this kind of questions are certainly not for this channel.
Yeah I understand I don’t really want that either I prefer finding out things by myself but after 4 days i just can’t
Im just going to make a prefab for everything i want to reference
And hopefully that works
That's probably not gonna work as you expect... Knowing how to reference things at runtime is one of the basic things you need to know to make a game(even just a single player game). I suggest you go to unity learn and to the beginner pathways.
I know how to do that
I don’t think i have explained what im trying to do here
Clearly enough
Thats my bad
I did the changes now i have a whole other set of issues
Networking related?
Yeah
Is kinda weird tbh
I really dont know whats going on
Well, if you can't explain it, I do t think I can help you either.😅
Yeah ik I don’t know how to explain this
So i have a orientation gameobject on the player determines were the player is facing and when the player is spawned everything is off when i press w he moves to the right
And everything is fine
Something to do with spawning???
Im using quaternion.identity
And a regular vector 3 for the spawning position
Sounds like an issue with your movement controller/input. Doesn't sound relevant to networking.
It is
Because when the player is in the scene its fine
And when spawn by the network not
Ok fixed it
My cam was not being assigned
So it was not networking issue after all
You said that your cam was not being assigned?
that has nothing to do with networking though.
Yeah im not to good at explaining stuff
The player was being spawned and the cam wasn’t with the photonnetwork thing and it was using the wrong cam
Okay. I'd say it 25% relevant to networking
Yes
Anyways now there is a even worse problem
I built the project
And when the second player join
S
Everything just goes mental
The 2 player sees themselves in 3rd person
The 1 player can move his camera
Everything is fine untill the second player joins
Sounds like you're not handling the controls for each player separately.
Well, you probably forgot it somewhere, seeing how player 1 can control player 2 camera.
No nobody can control the camera
I have a move cam script which follows the player
Should that be if view.ismine to
Or not
Depends. I've no clue what you're doing there and how it's following
and you're sure player is referencing the correct thing?
Yes could the problem be that there is only one camera in the scene
And there are 2 players
Trying to use that 1 camera
if it's not controlled via networking and has proper references, it shouldn't be a problem
Yeah but when 1 player is spawned
I have a var player = photonnetwork.instantiate
And the cam follows player.transform
Could that be causing issue or no
just to make sure: you're spawning the player in your camera script..?😅
No
The player is spawned with a empty game object
In the scene
Then when is the camera player field assigned?
That has a playerspawn script on it
Through code at runtime
The var
Player
Share the code then
All
If you can only share the relevant part, share the relevant part.
If u want me to shard with gdl space il do all
Screenshots i can do the relevant part if u want
I rather do all tho
Share the whole code then
You said you assign the camera Player field via code, but I don't see it anywhere in the code.
aah
nvm
Each time you spawn a player you assign the new player's PlayerTransform
So the camera would follow the last player you spawned
How would i do thag
That
With photon???
You already do it.
And that's the source of the issue
And it's not networking related
Wdym
It related to the player spawning right???
When you spawn the first player, the camera references the transform of the first player
Then when you spawn another player, it references the transform of the other player
How would i do that???
YOU ALREADY DO THAT
That's the issue. The camera(regardless of what client it belongs to) references the same player.
No i mean fix it
Make it so that each client camera references that client's player
That what im trying to figure out how to do
Either keep a list/array of players and make the camera pick their player from the list or add the camera to the prefab, so that it always references it's parent
How do i tell the camera what player to follow
How do i get the players photon id
Google it. Look through the photon docs or watch some tutorials. It feels like you've zero idea on how to use photon.
I don’t
Have any idea about photon
This project is so i can learn some more stuff about it
I made one before but that was just to see
And this is not the place for a photon basics lecture. There're enough materials for that online.
It was to just see how some stuff work
And now trying to make a propper game with it
Yeah but some don’t help with the problems i have
As I mentioned before, with intermediate + topics like that you wouldn't get an exact solution to your problem, you have to use docs and tutorials to understand how things work. Then use your own head to find a solution.
As for getting player's(or rather photon view) id, it's definitely in the docs.
Yeah it is im check through that
Although, in this case, you probably don't even need the id at all.
You only need to know what player belongs to the current client.
Anyways thanks for all the help and putting up with all my stupid photon beginner questions
hello im using netcode system and i want to spawn objects as client how could i do it?
objects can only be spawned from the server I believe
You should send a server RPC from the client to the server that tells the server to spawn it
getting the following error
(0,0): error <FirePistol>g__ShootServer|20_1 must not be static (at System.Void Pistol::<FirePistol>g__ShootServer|20_1(System.Int32,UnityEngine.Vector3,UnityEngine.Vector3))
from this line of code
ShootServer(pistolDamage, cam.transform.position, cam.transform.forward);
What does it mean exactly?
It complains that your method is static. Is it ?
not sure what that means xD very new to unity, this is what it calls
[Command(requiresAuthority = false)]
public void ShootServer(int pistolDamage, Vector3 position, Vector3 direction)
{
if(Physics.Raycast(position, direction, out RaycastHit hit) && hit.transform.TryGetComponent(out Player enemyPlayerHealth))
{
enemyPlayerHealth.playerCurrentHealth -= pistolDamage;
}
}
it also doesnt like me having "public" at the start of the command
Well the method itself is not static, that's one thing. Otherwise would be declared as public static void ShootServer()
"The modifier 'public' is not valid for this item"
🤔 is it unhappy with the Physics.Raycast() static call then maybe ? Not sure
not sure, was following a guide but its using fishnet not mirror, all ive changed is [ServerRpc] to [Command] and put using; Mirror; and network behaviour
Oh damn you love adventure
very very fresh at unity, just mixing and mashing a heap of guides, pretty happy with where im at, just need to work out the whole shooting side of things now
wasnt going to go the bullet object and was gonna use raycast and trails instead
Thanks, still the same issue though, doesnt like public
lol what ?
where is the method, can you show the surrounding code ?
probably didnt close a bracket or something like that
No worries, just next time use a paste site for big blocks of text
Yeah your method is declared inside FirePisotl ^^
yep hahaha
was looking at it for ages, and just noticed it once i pasted in here... rip
Happens a lot in the beginning, making sure your file is well formatted helps ^^
Happy to be your rubber duck 😛 Remember the error message, so next time it happens you know there's a syntax issue
Back to your original issue, is it solved now ?
Will do, thanks for your help mate
yeah theyre all good now
time to test if it works 😂
Alright 🤞
once this is sorted, time to add some giant spiders 😂 getting excited
What is a Command?
(Experienced in c#/unity but 0 in networking)
[SerializeField] private GameObject player;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Vector3 directionToPlayer;
[SerializeField] private float moveSpeed;
[SerializeField] private bool spottedPlayer;
// Start is called before the first frame update
void Start()
{
spottedPlayer = false;
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
if (spottedPlayer)
{
player = GameObject.FindGameObjectWithTag("Player");
directionToPlayer = (player.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToPlayer.x, directionToPlayer.y) * moveSpeed;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
spottedPlayer = true;
}
}
Hello, I'm trying to make it so the enemy follows the player that triggers it, but my prefabs all have the same playerID, which means that no matter what, the enemy will only follow one player, is there a way to go around this? (im using Netcode)
that's because GameObject.FindGameObjectWithTag("Player"); gets just one player
also you should not be using FindGameObjectWithTag in an update loop
[SerializeField] private NetworkObject player;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Vector3 directionToPlayer;
[SerializeField] private float moveSpeed;
[SerializeField] private bool spottedPlayer;
// Start is called before the first frame update
void Start()
{
spottedPlayer = false;
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
if (spottedPlayer)
{
player = NetworkManager.LocalClient.PlayerObject;
directionToPlayer = (player.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToPlayer.x, directionToPlayer.y) * moveSpeed;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
spottedPlayer = true;
}
}
}
i've been trying to use networkmanager.localclient now like the docs say
it worked but the enemy object wasnt syncronized
i tried adding a networktransform to the enemy and the problem still perstists now
how do i find the player id?
yea i want to get the id of the player who triggered it
I think you can get it from NetworkObject
np
It's a request sent from a client to execute code on the server (because of authority concerns). The docs will explain better than me https://mirror-networking.gitbook.io/docs/guides/communications/remote-actions
thanks ❤️
void FixedUpdate()
{
if (spottedPlayer)
{
player = GetNetworkObject(4);
directionToPlayer = (player.transform.position - transform.position).normalized;
rb.velocity = new Vector2(directionToPlayer.x, directionToPlayer.y) * moveSpeed;
}
}
i was able to make the enemy move towards that object id(4)
but the problem is this is hard coded
i was thinking more like
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
player = other.gameObject;
spottedPlayer = true;
}
}
```why do need the id?
just set player to the other gameObject in the trigger logic
hmmmm okay ill try that
Cannot implicitly convert type 'UnityEngine.GameObject' to 'Unity.Netcode.NetworkObject' [Assembly-CSharp]
its giving me this error
NetworkObjects always give a shit ton of errors
I started using WebSocket system for my multiplayer demo, I can send message client to server but how can I send a variable or something else server to client?
change [SerializeField] private NetworkObject player; to [SerializeField] private GameObject player;
i think you are missunderstanding networkobjects
i think so too ffs
they're really only there for the backend system
you rarely have to interact with them
ye
okay i changed the object type ill make another build
so i tried the other.gameObject and now the enemy is only following the client
why isnt this shit working omfg xD
been trying to fix this for 3 hours now
the enemy doesnt respond to the host now
ws.send(data) here you're sending data the server received back to the client
On the client you would also need a websocket library to be able to connect to server, send data, and receive data
based on what you're saying you already have a client though
nvm its working
thanks for the help man
really grateful
How can I get the netid of each player so when I damage someone I can run a client rpc to tell everyone they got damaged
trying to use this
void RegisterPlayer()
{
if(isLocalPlayer)
{
string _ID = "Player number " + GetComponent<NetworkIdentity>();
transform.name = _ID;
}
}
with mirror
[ClientRpc(includeOwner = false)] void RpcRegisterPlayer() will execute the method for every client except the owner
it doesnt seem to be getting the networkid number
which i need to use for a lot of things, damage, health, score etc
You're trying to add a NetworkIdentity component to a string
NetworkIdentity has a netId variable, surely you want to add that to the string instead?