Creating player controlled 'units' using Netcode for Gameobjects

Currently I’m trying to use what I’ve learned from the netcode for gameobjects course to create a 1v1 multiplayer game where each player has units. Players will issue commands to these units and wont control them directly.

The player object looks something like this:

public class PlayerController : NetworkBehaviour
{
//…
public List Units { get; private set; }
//…
}

and the Unit looks like this:

public class Unit: NetworkBehaviour
{
//…
public enum UnitType
{
Magician,
Knight,
Warrior
}

public NetworkVariable<int> hp = new NetworkVariable<int>();
public NetworkVariable<int> maxHp = new NetworkVariable<int>();

//…
}

When the game scene loads on the server I spawn the Player as player object, and then assign that player 3 random units. I spawn the player using this method:
NetworkObject.SpawnAsPlayerObject(ulong clientId, bool destroyWithScene = false)
and spawn the units using this one:
NetworkObject.SpawnWithOwnership(ulong clientId, bool destroyWithScene = false)

The units are all visible in the scene and animating properly.

However, Inside the PlayerController, I also want to locally instantiate a health bar in the UI for each unit the client owns.
Unfortunately, this only happens for the host. On the client I get a nullreferenceexception because Units is always null.

Why does the client not see the Units, even if they are spawned with client ownership?
Is this a good way to handle spawning units under the player’s control? If not, how would you approach things differently?

Thanks,

grifster

Wild guess (I don’t know the MP stuff that well) but it’s probably because the server is spawning the units, and the server is on the host. The server will need to let all clients know that they need to spawn instances themselves as well

If you make your list of a units a NetworkList, you can sync it across to the clients so they can reference it. Our old multiplayer course (using Mirror networking) was actually an RTS game, so it has functionality like this. You could checkout the repo for that course and get some ideas on how to handle units.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms