Search Unity

How to create a network gameobject from script

Discussion in 'Netcode for GameObjects' started by Strong_Hammer, May 20, 2021.

  1. Strong_Hammer

    Strong_Hammer

    Joined:
    Aug 8, 2015
    Posts:
    4
    Hey,
    I am creating a game object in script, the idea is the user can change the shape of the game object, this is all done in script and uses no prefabs. I am looking to use MLAPI to be able to spawn this user created gameobject on both server and client.

    My plan was to create a empty gameobject, add network object and network transform and run myt create script on network start. make this a prefab. This does not seem to work.

    I did the tutorial with the players moving and was hoping to bsaically expand that, but without the prefabs this seems to be a blocking point. Any ideas?
     
  2. luke-unity

    luke-unity

    Joined:
    Sep 30, 2020
    Posts:
    306
    If you do this you have to make sure that your manually created prefab is registered before you start MLAPI. This has to be the case on every client.
     
    Strong_Hammer likes this.
  3. Rodakai

    Rodakai

    Joined:
    Apr 3, 2014
    Posts:
    9
    How would this: "you have to make sure that your manually created prefab is registered before you start MLAPI" be done via code?
     
  4. Rodakai

    Rodakai

    Joined:
    Apr 3, 2014
    Posts:
    9
    If anyone comes across this and was wondering how to do it, here's a code snippet you could use. :)


    Code (CSharp):
    1.     void addNetworkPrefabFromResources(string resourcePath, bool isPlayerPrefab)
    2.     {
    3.         var prefab = (GameObject)Resources.Load(resourcePath);
    4.  
    5.         NetworkPrefab networkPrefab = new NetworkPrefab();
    6.         networkPrefab.PlayerPrefab = isPlayerPrefab;
    7.         networkPrefab.Prefab = prefab;
    8.  
    9.         networkManager.NetworkConfig.NetworkPrefabs.Add(networkPrefab);
    10.     }
     
    trombonaut, VLRSOFT and Noobassaurus like this.