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