Search Unity

Turn prefab into gameobject! (NetworkServer.spawn())

Discussion in 'Scripting' started by forsrobin, Feb 17, 2018.

  1. forsrobin

    forsrobin

    Joined:
    Feb 10, 2018
    Posts:
    4
    Hello!

    Im kinda new to unity and im working on my multiplayer RPG game.
    Im at the stage where i want to spawn in objects so other's can se it to but to do that i need to spawn in an GameObject but my current spawn script uses a prefab.


    private void PlaceCubeNear(Vector3 clickPoint)
    {
    var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
    //carrot.transform.position = finalPosition;

    Instantiate(plantPrefab).transform.position = finalPosition;



    NetworkServer.Spawn(plantPrefab);

    }

    I cant use "plantPrefab" because it spawn in a prefab.
    What should i do to be able to spawn in my object.

    I have tried converting it to a game object but i cant seem to figure it out!
    Thanks in advance!
     
  2. ihgyug

    ihgyug

    Joined:
    Aug 5, 2017
    Posts:
    194
    To "convert" a prefab into a gameobject you could declare a GameObject variable and then GameObject myGameObject = Instantiate(plantPrefab) etc...
    You can then use the myGameObject variable as an actual game object.
    Maybe there are better ways to do it.
     
  3. Syganek

    Syganek

    Joined:
    Sep 11, 2013
    Posts:
    85
    First of all use Code tags when posting code in your future post. Don't copy paste it directly.

    Secondly @ihgyug answer is correct you need to store the GameObject that is created with Instantiate() method.

    Code (CSharp):
    1. var plantObject = Instantiate(plantPrefab);
    2.  
    3. plantObject.transform.position = finalPosition;
    4.  
    5. NetworkServer.Spawn(plantObject);
    For a better method: you need to check if your problem can be resolved by Object Pooling. You can google the meaning of this method but basically it works that you already have some objects on your scene but they're disabled and you're enabling first one that is disabled rather than doing Instantiate().
     
    forsrobin likes this.
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  5. forsrobin

    forsrobin

    Joined:
    Feb 10, 2018
    Posts:
    4
    This helped me, thanks :D