I am creating a 2 player multiplayer RTS style game. I have a script that spawns prefabs as children to the player object, these children have references to scripts that need to be populated. The code works on the host client but when the second client joins its references are not populated.
This code successfully spawns the Prefab Game object and works as intended on the Host Client, however on the second Client’s the ParentPlayer variable is not being populated. Any help would be appreciated, Thank you.
You instantiate PrefabGameObject as tempGameObject, but then instead set ParentPlayer and spawn tempBG. I have no idea where tempBG comes from, but I’m sure you should be doing all this to tempGameObject instead.
Also setting “ParentPlayer = this” I don’t think will even sync, assuming it is a SyncVar, because your script isn’t one of the supported SyncVar types.
Lastly, Unet doesn’t support GameObjects with NetworkIdentity components as children of other objects (you mention they are spawned as children, though you’re code doesn’t appear to include actually setting them as children). You’re likely to get unexpected behavior if any of your NetworkIdentity components are attached to GameObjects which aren’t at the root of the scene hierarchy.
temBG is tempGameObject, I just forgot to rename it elsewhere in the forum post, this has been fixed.
As for the sync var section, if the script reference cannot by synced since it is not a supported type how should I go about this differently? A lot of other code depends on this ParentPlayer variable being able to be referenced.
You set it through some other means. I often use unique identifiers for this sort of thing. For example, when creating the object on the server I might increment a ulong, assign that unique value to a syncvar, then spawn the object. Then on any other object which needs to make this connection I have it find the object with the specific unique identifier. As far as finding the object quickly, when the object spawns I might have it add itself to a client side list so it can be quickly iterated over later.
There’s other ways to handle it too. Supposedly I’ve read you can send NetworkIdentity components for spawned GameObjects in RPC’s, though I’ve never successfully seen it working.