- Home /
[Multiplayer] Unable to spawn non-player object using NetworkServer.Spawn() call
I am new to Unity. I am working on the multiplayer networking concepts in unity by creating simple multiplayer Pong game. So far I have added Network Transform and Network Identity components to my Player object and fed Player object prefab to Network Manager's Player slot. So, now I am able to run multiple instances of game (one as host and other as client) and player movements are tracked and updated fine in both client and host.
Now I want to add a ball object (non-player object) to both the clients and detect collisions of this object with players and update ball position in all clients properly. For this, I have added Network Identity and Network Transform component to 'Ball' prefab and fed this prefab to Network Manager's Spawnable Prefabs slot. 'Ball' prefab also contains script to instantiate and spawn using NetworkServer.Spawn() method. But, ball is not spawn using this script. I am missing something here or Is there a better approach to this? Following is my code for spawning a ball object -
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class BallSpawner : NetworkBehaviour {
[SerializeField]
private GameObject ballPrefab;
GameObject ball;
NetworkHash128 ballAssetId;
void Start()
{
ballAssetId = ballPrefab.GetComponent<NetworkIdentity>().assetId;
ball = Instantiate(ballPrefab, Vector3.zero, Quaternion.identity) as GameObject;
}
public override void OnStartServer()
{
NetworkServer.Spawn(ball);
base.OnStartServer();
}
}
Any help is highly apppreciated. I have wasted quite sometime solving this problem. Thanks
To what object is this script attached?
$$anonymous$$oreOver you should move all the content of Start()
to OnStartServer()