2

I am currently creating a two-person multiplayer game and have stumbled upon a problem when trying to spawn a game object from the client.

In my Defender class I have a function which gets called upon each time a player recruits a unit.

 void RecruitDefender(DefenderBlueprint blueprint)
    {
        defender = blueprint.gameObject;   
        Player.instance.CmdSpawnDefender(defender, transform.position, transform.rotation);
    }

If I spawn the units in this RecruitDefender-function they spawn just fine, but they will only spawn locally. In order to make them appear for both server and client I tried to instantiate the unit from the player class through a [Command]:

public class Player : NetworkBehaviour
{
    [Command]
    public void CmdSpawnDefender(GameObject defender, Vector3 position, Quaternion rotation)
    {
        GameObject _defender = (GameObject)Instantiate(defender, position, rotation);
        NetworkServer.Spawn(_defender);
    }

However, this gives me the error "The Object you want to instantiate is null" when trying to spawn from the client; the player located on the server can spawn without any problems. The problem seems to stem from the fact that the game object "defender" is null for the client in the Player class, which seems strange as it has a value in the RecruitDefender class. As far is I have understood Unet (which I admit is limited) you should be able to pass game objects to [Command] functions. Does anyone have an idea of what the problem could be here?

Martin V
  • 65
  • 1
  • 4
  • So when you send the `CmdSpawnDefender` to the server, does it send it back to the client? – Halden Collier Aug 27 '19 at 13:54
  • No, it's not. I have tried different combinations with [ClientRpc] but I do not think that the spawning should have to be handeled on the client? Instantiating on the server and then have the NetworkServer.Spawn create copies to the clients seems to be a logically way to do it in my head, but I may be wrong. – Martin V Aug 27 '19 at 14:51
  • 2
    You may be interested to hear that UNet is [deprecated](https://docs.unity3d.com/Manual/class-NetworkBehaviour.html). One alternative you can use is Photon/ PUN2. When you spawn a prefab with their engine using [PhotonNetwork.Instantiate](https://doc.photonengine.com/en-us/pun/current/gameplay/instantiation) (it needs to be in the resources folder for this), it will be spawned on each client, and synchronized accordingly. – Philipp Lenssen Aug 27 '19 at 16:28
  • Sorry for the late reply. I am aware that it is deprecated, but as I am new to Unity and there isn't much documentation on their new networking system, I went with the old one. I will check out Photon and hopefully that will be easier to work with. Thanks! – Martin V Sep 18 '19 at 06:40

0 Answers0