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?