Instantiate PreFab with C# Script

Hi,

I've found online that the best way to instantiate a game object type is with the following statement:

GameObject go = Instantiate(Resources.Load("MyPrefab")); 

This does not work for me, does it require more using statements than:

using UnityEngine; using System;

I am getting the following error:

Assets/Scripts/Instantiate.cs(54,67): error CS0426: The nested type `Load' does not exist in the type`UnityEngine.Resources'

In the root of your Project hierarchy make a folder called 'Resources', put your prefab in that folder. My prefab is called DamageText and here is my working code:

GameObject textObject = (GameObject)Instantiate(Resources.Load("DamageText"));

Tested using C# with Unity 2.6.

you can create any public variable type that is a children of component or GameObject and instantiate it with this function. the return type of Instantiate is UnityEngine.Object and you should cast it if you want to asign it to a variable of type GameObject. so just (GameObject) before the Instantiate and it will work well. you should have the resources folder with the prefab in it thow.

GameObject go = (GameObject)Instantiate(Resources.Load("MyPrefab")); ;

or

GameObject go = Instantiate(Resources.Load("MyPrefab")) as GameObject; 

see MSDN topics for as keyword and topics about casting for more information.

This is what I would do

at the top put

public Transform whatYouWantToInstantiate;

then wherever you want to instantiate

Instantiate(whatYouWantToInstantiate);

That's the simple way...

Christian Stewart

im getting ‘The variable `go’ is assigned but its value is never used’

I found a video explaining this pretty good if you still need help, also tells you how to spawn a rigidbody: Unity 5 - How To Spawn Objects Using a Trigger - YouTube