I am using Mirror to handle the networking aspect
When I spawn an object on the network, I Instantiate it on the server and then use NetworkServer.Spawn to notify all clients to spawn the object.
However, when this object is eventually spawned on the client side, it seems to be spawned at the wrong position for a few seconds and then corrected itself and move to the correct position as is reflected by the server. Is there something I am not doing? Is this normal?
Also I noticed if I changed the Network Sync Mode to 0, then it will only spawn in the wrong spot for a split second.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class EnemySpawner : NetworkBehaviour
{
public uint theId;
public int maxNumEnemies;
public int spawnDelay;
public GameObject enemyToSpawn;
float curSpawnTime;
BoxCollider2D boxColl;
// Start is called before the first frame update
public override void OnStartServer()
{
curSpawnTime = spawnDelay;
boxColl = GetComponent<BoxCollider2D>();
}
void Start()
{
if (!isServer) return;
theId = netId;
}
// Update is called once per frame
void Update()
{
if (!isServer) return;
if (transform.childCount < maxNumEnemies && curSpawnTime <= 0.0f)
{
Vector2 spawnPoint = new Vector2(Random.Range(boxColl.bounds.min.x, boxColl.bounds.max.x),Random.Range(boxColl.bounds.min.y, boxColl.bounds.max.y));
curSpawnTime = spawnDelay;
SpawnEnemies(spawnPoint,netId);
} else
{
curSpawnTime -= Time.deltaTime;
}
}
[Server]
void SpawnEnemies(Vector2 spawnPoint, uint theId)
{
GameObject gobj = Instantiate(enemyToSpawn, new Vector2(60.7f,1.3f), Quaternion.identity);
gobj.GetComponent<EnemyController>().parentNetId = netId;
NetworkServer.Spawn(gobj);
}
}
The way I've organized things, in the hierarchy I have:
Enemies
Area1
Spider(Clone)
Spider(Clone)
Area1 has the EnemySpawner script. The spider is registered a spawnable prefab. Both Area1 and the Spider have a NetworkIdentity with no boxes checked. Additionally, the Spider has a NetworkTransform and NetworkAnimator.