How to instantiate: monobehaviour script from another GameObject

I am having trouble with this and I am a bit on google that helps me.

All in all, if a script comes from MonoBehaviour, it cannot be created using the "new" keyword. Good. So I've been looking at how to do it and it seems like getting a GameObject and then getting a GameComponent is the way to go ... But it's not very far.

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

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'm getting looks like this: "Unable to implicitly convert type" Assets.scripts.NetworkManager "to" UnityEngine.GameObject ""

The problem comes when I add ".GetComponent ();" part. Now it seems obvious that if a function looks for a Component type and instead gets a NetworkManager type that won't work ... And this is where I am stuck. I have no idea how to get this to work and I have surpassed my 15 minute google search limit.

+3


source to share


2 answers


If you want to create a new networked GameObjects manager, you should take some time to get to know "prefabs". You can make the Network Manager GameObject one of them by dragging and dropping it from your scene to one of your folders. Instantiating the prefab is as easy as:

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

      



This will create a new GameManager NetworkManager object in your scene.

As you said, your script doesn't work because it gets the component and stores it in the GameObject. Just change the type of the variable to the component type or if the component is script for the class type. In your case change GameObject networkManager;

to NetworkManager networkManager;

and it will work.

+2


source


If you have a prefab, you can create it.

GameObject g = Instantiate(prefab, position, rotation) as GameObject;

      

If the GameObject is already in the scene, don't create it unless you want more than one. You can just find it.



GameObject g = GameObject.Find("GameObject Name");

      

Then you ask how do I get the script attached to the GameObject. Like this:

ScriptName s = g.GetComponent<ScriptName>();

      

+2


source







All Articles