C# Instantiating a Prefab by Script

I’ve been working on the Unity scripting videos and I’ve been trying to instantiate a prefab through script so I don’t have to drag the prefab into the inspector. However, I continually get: “The prefab you want to instantiate is null”. I’ve looked around and have seen a post stating:

If your prefabs are located in the Resources Folder, then you can load your prefab in that ways… it has been tested and works.

C#Version

GameObject testPrefab = (GameObject)Resources.Load(“/Prefabs/yourPrefab”);

But I cannot get that to work in my scene. Below is my code, which will work if the prefab is dragged onto the inspector panel:

using UnityEngine;
using System.Collections;

public class UnityInvoke : MonoBehaviour {
GameObject goPrefab;

// Use this for initialization
void Start () {

	InvokeRepeating ("SpawnPrefab",2.0f,2.0f);

}

// Update is called once per frame
void Update () {

	if (Input.GetKeyDown (KeyCode.Space)){
		CancelInvoke ("SpawnPrefab");
		Debug.Log ("Invoke Stopped");
	}


}

void SpawnPrefab () {
	int x = Random.Range (-2,2);
	int y = Random.Range (-3,2);
	int z = Random.Range (-1,1);
	GameObject goPrefab = (GameObject)Resources.Load("Assets/Resources/Prefabs/NewPrefab");
	Instantiate (goPrefab, new Vector3 (x,y,z), Quaternion.identity);

}

}

Any ideas?

Resources.Load expects the path argument to be relative to your Resources folder, so if your resource is named NewPrefab and is indeed located under “Assets/Resources/Prefab” you should only pass the relative path “Prefabs/NewPrefab”.

This is assuming your prefab is called NewPrefab.

First, the Unity Scripting Reference :

Note : Your Prefab MUST be in the Resources folder, NOT a subfolder

You can have multiple Resources folders, eg Assets/Prefabs/Resources , Assets/Models/Resources , but the prefab has to be in the Resources folder, not a subdirectory.

Then you just call the name of the prefab without an extension, in your case :

GameObject goPrefab = (GameObject)Resources.Load("NewPrefab");