Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Coding my own Network.Instantiate() ?

Discussion in 'Multiplayer' started by jshmrsn, Feb 6, 2010.

  1. jshmrsn

    jshmrsn

    Joined:
    Jan 31, 2010
    Posts:
    8
    I'm having some issues with Network.Instantiate() so was wondering if I could script my own substitute version to try and build upon that and give me more flexibility.

    Is this possible with common scripting or wold it require lower level access to Unity's internals?

    In Network.Instantiate()'s docs, it's mentioned that "Behind the scenes, Network Instantiate is simply a convenience function built around RPC calls. It serializes an identifier of the prefab that is to be instantiated, serializes all allocated NetworkViewID's, serializes the position, and send it across the network using an RPC call."

    I understand most of this, but I don't understand the "an identifier of the prefab" part. How would I access such an identifier?

    Thanks,
    Josh
     
  2. DrHotbunz

    DrHotbunz

    Joined:
    Feb 14, 2009
    Posts:
    315
    Network.Instantiate()is just a convenience function to spawn prefabs that have network views that are already setup and the objects spawn on all the clients.

    Obviously you could just Instantiate an object on every client and then setup the the network view.

    I have zero trouble with Network Instantiate but I have heard others recommend against them. I think Robur doesnt like them which is normally a sign they dont work too well.

    What problems do you have with it ?
     
  3. Ethan

    Ethan

    Joined:
    Jan 2, 2008
    Posts:
    501
    I am using Network.Instantiate too, but in combination with OnSerializeNetworkView() i get some bugs from time to time (like some others around here, too)

    If you use RPCs only it should/could work fine.
     
  4. Der Dude

    Der Dude

    Joined:
    Aug 7, 2006
    Posts:
    213
    In an RPC you can only send primitive Types and NetworkViewIDs. So to identify which prefab should be spawned you need to identify it somehow. I usually do this by having an array with all of my prefabs. Then when I want to instantiate one of them I send an int representing the index of the array where the Prefab is I want to instantiate.

    Below is a little code snippet that should show what I mean.

    Code (csharp):
    1.  
    2. public GameObject[] myPrefabs;
    3.  
    4. public void LocalInstantiate(Vector3 pos, int prefabID)
    5. {
    6.     networkView.RPC("RemoteInstantiate", pos, prefabID, Network.AllocateViewID());
    7. }
    8.  
    9. [RPC]
    10. public void RemoteInstantiate(Vector3 pos, int prefabIndex, NetworkViewID viewID)
    11. {
    12.     //Instantiate here
    13. }
    14.  
    [/quote]