Search code examples
c#unity-game-enginegameobject

How to instantiate a : monobehaviour script from another GameObject


I'm having trouble figuring this one out and am finding little on google that helps me.

In unity, if a script derives from MonoBehaviour, it cannot be instantiated using the "new" keyword. Fine. So I've been looking at how to do this, and it seems that getting the GameObject, then getting it's GameComponent is the way to go... But it's not going very far..

So I have a GameObject called NetworkManager. Attached to it is a script called NetworkManager. I have another GameObject called Main, attached to it is a script called Main (surprise!). Basically what I want to do is "instantiate" the network manager within the main script, so that i can do things like networkManager.hostServer() or networkManager.kickPlayer() and so on.

This is my main.cs script:

public class Main : MonoBehaviour {

Player player;
GameObject networkManager;
UiManager uiManager;

// Use this for initialization
void Start () 
{

    player = new Player(Network.player, Environment.UserName, 0, 0);
    networkManager = GameObject.FindGameObjectWithTag("NetworkManager").GetComponent<NetworkManager>();
    uiManager = new UiManager();

}

The error I am getting is as follows:" Cannot implicitly convert type 'Assets.scripts.NetworkManager' to 'UnityEngine.GameObject' "

The problem arises when I add the ".GetComponent();" part. Now it seems obvious that if the function is looking for a Component type and is instead getting a NetworkManager type that it wouldn't work... And that's where I'm stuck. I have no idea how to get this to work, and I've surpassed my 15 minute limit on google searching.


Solution

  • If you want to instantiate new Network manager GameObjects you should use some time to get to know "prefabs". You can make your Network manager GameObject into one of those by dragging it from your scene to one of your folders. Instantiating a prefab is as simple as:

     Instantiate(NetworkManagerPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    

    This will create new NetworkManager GameObject into your scene.

    As you said, your script is not working because it is getting the component and storing it to GameObject. Just change the type of the variable to the type of the component or if the component is a script to the type of the class. In your case change GameObject networkManager; to NetworkManager networkManager; and it will work.