0
\$\begingroup\$

I am creating a game in unity and I have a prefab that I instantiate on center occasions. What I want to do though is after instantiating the prefab. Get a handle to it and call a specific public method from the script attached to it. One method would be to put that part of code in the start function of that script. But what if I do not want that code to run as soon as the prefab is instantiated? How can I get a handle to it and manually call that specific method?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

GameObject.Instantiate returns an Object reference that you can then cast. Use GameObject.GetComponent() to get a component of type T from that gameobject. Since scripts are components, you can get them through this method.

So:

GameObject prefab;
GameObject prefabInstance = GameObject.Instantiate( prefab ) as GameObject;
if( prefabInstance != null )
{
    var myScriptReference = prefabInstance.GetComponent<MyScript>();
    if( myScriptReference != null )
    {
        myScriptReference.MyMethod();
    }
}

So, we instantiate like normal and get a reference to the created game object. Then we check to make sure the result wasn't null for some reason. If that went okay, we can get a reference to our script using GetComponent. Using the script reference, we can call the method with want.

Also note in Unity 5 a generic version of instantiate was added. This means the second line can be changed to:

GameObject prefabInstance = GameObject.Instantiate<GameObject>( prefab );

Which makes things a little cleaner. The reason we need to cast in the first place is because Instantiate is actually an Object method, not a GameObject method.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .