Dynamically adding a Prefab to the scene
Hi, I'm new to Unity. All I want to do is write a script that takes a Prefab from the Resources folder, and puts it in the scene (as opposed to me dragging and dropping it). My prefab (called "Dummy") is in a folder called "Resources" within Assets, and I'm trying to load it into a GameObject called guy. However, with my code, I always end up with a null GameObject. What have I done wrong?
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public GameObject guy = Resources.Load("Dummy") as GameObject;
void Start () {
if (guy == null) {
Debug.Log ("IT'S NULL!!!");
}
Instantiate (guy, new Vector3(400, -2, 115), Quaternion.identity);
}
void Update () {
}
}
Hi, I $$anonymous$$now this is an old issue but Have you ever resolved it? I have the same problem right now and if you could help me it would be great
Answer by Tourist · Feb 16, 2017 at 04:03 PM
Don't call Resources.Load outside methods.
Dummy should be in a Resources folder.
public class Test : MonoBehaviour { public GameObject guy; void Start () { guy = Resources.Load("Dummy") as GameObject; if (guy == null) { Debug.Log ("IT'S NULL!!!"); } Instantiate (guy, new Vector3(400, -2, 115), Quaternion.identity); } void Update () { } }
Answer by jose_nadal5894 · Feb 17, 2017 at 10:09 AM
Oh thanks. However, in the meantime, I have already solved my problem. It was a specific configuration of layers in the scene management
Your answer
![](https://koobas.hobune.stream/wayback/20220612052308im_/https://answers.unity.com/themes/thub/images/avi.jpg)