- Home /
Network.Instantiate fired from client AND server
Hi,
I'm trying Unitys network functionality for the first time. My current problem is the following: A player can Network.Instantiate
a building that will automatically spawn units for him. this works fine, the building is created for both client and server.
But when the building spawns the unit the Network.Instantiate
for this unit is fired by both the server and the client (as the building exists on both) and therefore i'll have two units. If I GameObject.Instantiate
the unit, i'll end up with one spawned unit on each client and server, but i guess that i'll have virtually two units then, because they are not connected via network. I'd like to try this in a non authoritive server approach first, if its possible. I'm not sure wether this piece of code helps. How do I fix this?
void FixedUpdate() { if (spawnsCreep == null) { return; }
timer -= Time.deltaTime;
if (timer <= 0)
{
Spawn();
timer = spawnTimer;
}
}
void Spawn() { GameObject offspring = Network.Instantiate(spawnsCreep, GetComponent<Transform>().position, Quaternion.identity, 0) as GameObject; int id = GetComponent<CombatBehaviour>().GetPlayerID(); offspring.GetComponent<CombatBehaviour>().SetNetworkPlayerID(id); }
Note: Both the units and buildings NetworkView are already added in the prefabs.
Edit: Of course after asking the Question, a quick and dirty solution came to my mind:
if (Network.isClient)
{
return;
}
Seems quick and dirty, works for the moment. But i'm not sure if its the optimal way to build on.
Answer by Bunny83 · May 17, 2011 at 01:53 PM
If the script is only responsible for spawning the units, just disable or remove the script on all other clients (server included). Just check in Start if you are the owner of this building.
if (!networkView.isMine)
{
Destroy(this);
// or
enabled = false;
}
if you still need some functionality of this script you can restrict the spawning to the owner just the same way:
void Spawn()
{
if (!networkView.isMine)
return;
[...]
Sorry to bring this up again, but if I would instantiate something by using this method that I only want to be used on the client instantiating it and the server, would traffic still be sent to the other clients as well (and just be ignored)?
@$$anonymous$$estR: Sorry, but i'm not sure what you mean ;) If you Network.Instantiate an object, it will be instantiated on all peers. All peers have to have an object with this networkviewID or you get massive errors. In theory you can delete a "networked" object only on one client, but the updates will still be sent and causes errors because there's no receiver.
I've seen your question about SetScope, i will answer there since it seems related.