Hi! I'm making a space simulator and I've been tinkering with the networking API in order to add network support to it. Up to this point, I've managed to create a server and make a client connect to it, but I'm having some problems when trying to instantiate prefabs by using Network.Instantiate().
Here's the scenario: I have a "Cockpit" prefab that uses a public variable in order to store a reference to an "AstronautCamera" (which is another prefab that needs to be instantiated dinamically in order to share it with the rest of the network). While I was working in the single-player version (where the elements of the scene were statically placed) I would create the cockpit and the camera using the editor and drag and drop the camera to the public variable slot. Now, I cannot do that when the prefabs are dinamically instantiated, so how can I make the cockpit object hold a reference to the camera after both elements have been instantiated?
A possible solution would be to get a reference to the cockpit's script and manually assign the public variable to the camera's prefab, but I'm sure there's have to be a cleaner way. Do you have any suggestions?
I have done this quite a bit with the project I am working on.
This works even if you do not currently have any versions of the prefab in the scene.
This is a .js example but you will get the point anyways.
public var cockpit : GameObject;
function Awake(){
cockpit = Resources.Load("CockpitPrefabNameHere");
}
This will only work if you have your prefabs stored in the Resources folder in your project but putting all your prefabs there will make loading them whenever you need them easier. This way when you Network.Instantiate(), on everyone's game the prefab will load the reference to the other prefab automatically.
Side Note: Network.Instantiate isn't the best way to go about creating things in the game, manually using RPCs to instantiate the prefabs on all the clients and allocating networkviewid's yourself is a much better way of going about it.
while trying to do things such as this I use this method
var cockpit = GameObject;
function Update()
{
if (cockpit == null)
{
cockpit = GameObject.FindWithTag("cockpit");
}
}
I've heard that this isn't a very processor efficient way but it's working fine for me and I have used this in nearly every script as nearly everything for me needs to be dynamically assigned. I'm using it in update just incase a player is destroyed and respawned. If you don't have this problem you could use it in `function Awake` or `function Start`
Thank you all for your answers! I've finally solved it by adding a public function to the Cockpit's script called SetAstronautCamera and I invoke that function right after the network instantiation, like this: