Hi, im new to Unity and Netcode and i have a question:
With netcode i can choose if the playmode is starting as client, server or both over “Multiplayer” → “PlayMode tools”, how can is check in a c# script if im running as server or client?
The “UNITY_SERVER” definition is set when i build the game and then run it, is there something similar in playmode?
Well, a workaround would be to check the worlds that got created. If there is a server world, the game also runs the server. On the other hand: why do you want to check this?
I took a look into the package sources and inside “ClientServerBootstrap” i found the following line:
public static PlayType RequestedPlayType => (PlayType) UnityEditor.EditorPrefs.GetInt("MultiplayerPlayMode_" + UnityEngine.Application.productName + "_Type");
I assume you could use the same code to determine the playtype, but don’t forget to surround it with #if UNITY_EDITOR
and #endif
, because otherwise it’ll work in the editor but not in a build.
I am using a NetworkUtility class:
(note: i am only using the Simulation Gorups)
public static class NetworkUtility
{
public static World GetServerWorld()
{
return GetWorld<ClientSimulationSystemGroup>();
}
public static World GetClientWorld()
{
return GetWorld<ClientSimulationSystemGroup>();
}
private static World GetWorld<TWorld>() where TWorld : ComponentSystemGroup
{
foreach (var world in World.All)
{
if (world.GetExistingSystem<TWorld>() != null)
{
return world;
}
}
return null;
}
public static bool IsClientWorld(World world)
{
return world.GetExistingSystem<ClientSimulationSystemGroup>() != null;
}
public static bool IsServerWorld(World world)
{
return world.GetExistingSystem<ServerSimulationSystemGroup>() != null;
}
}
@Flipps : your GetServerWorld
and GetClientWorld
do the exact same thing. I guess the server one is supposed to use the ServerSimulationSystemGroup
, isn’t it?
Thanks both of you!
Richard, your solution works fine.
Thanks Flipps for your solution, i’ll try that one, but first i’ll have to read more about SimulationGroups etc.
EDIT: i want to check this, because i have one project for the client and the server and i have a empty scene to start with in which i check if i have to load a “menu scene”(if started as client) or if i can directly load the real game scene.
You are right, thanks for the hint!
I didn’t do it myself, but the documentation mentions that you can implement your own bootstrapper with your own, custom logic (and your own configuration).
and @Flipps code is basically my first suggestion. Since you probably want to create your own bootstrapper, it looks more like a workaround to me tbh.