Adding a component to an object over UNET?

Hey there, this is mostly a question of the best way to do something.

So I want to add components to an object that is networked with UNET (Unity’s current networking system), however, if I do that, the new components don’t communicate properly. Basically, the big problem I find specifically is that a client can’t call commands, even though the identical component was added to the host.

Anyway, I’m just asking for the best way to do this. My current method involves despawning the player then respawning it. But this seems like a horrible way to do this.

Anyway, thanks in advance for help!

adding NetworkBehaviour components to spawned objects at runtime is not supported.

There is a way around that though. I’ve implemented it here successfully. Mind that it’s not what I’d call a simple approach. It requires things to more or less be built around it.

The idea is to create prototypes of the objects you want to spawn, with all their optional components pre-attached, and keep them disabled somewhere, as a sort of runtime prefab. Then, for each of those prototype objects, you set up a custom spawn handler (using a unique id for each). In that spawn handler method, you instantiate the prototype object you created.

It’s not really the same thing as adding components at runtime, because the components do need to be added in advance for each prototype object, but if you’re making things that use script components as behaviour modules, then this approach works well. Different types of objects can have different sets of modules.

This approach worked for me because it made sense to keep the object prototypes cached in my project, but it can be generalized to do objects with components added completely at runtime, what you’d do is create a logic object factory system, which creates prototypes on request, by setting up an empty gameobject, attaching components to it (along with network identity and all), and registering a spawn handler to instantiate that object, then you can call NetworkServer.Spawn with that object’s unique ID.

I know this is a bit late, because UNET is on its way out already, but for those of us that are version-locked into using it, this is a way to do it.

Cheers