How to create prefab instance and add it to the scene from script
I give up to try again after 3-4 hours and need some help. All what i want is create an object (prefab) on scene after player press Spacebar. So my code now:
using UnityEngine;
using System;
public class PlayerController : MonoBehaviour
{
public GameObject missle;
public PlayerController()
{
}
void Update()
{
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
transform.Rotate(0, x, 0);
transform.Translate(0, 0, z);
if (Input.anyKeyDown)
{
Debug.Log(Input.inputString);
if (Input.inputString == " ") {
missle = Instantiate(Resources.Load("Assets/Prefabs/Missle.prefab")) as GameObject;
};
}
}
}
And i keep getting error "The Object you want to instantiate is null."
My path to prefab:
Answer by misher · Sep 14, 2018 at 12:14 PM
First. If you want to load the prefab using Resources.Load()
your prefab should be in a folder called "Resources" or in a subfolder (like "Resorces/Prefabs"). You can also have multiple "Resources" folders in your project. Second, when loading asset with Resources.Load()
you must specify only relative path to your asset in one of your resources folders, like Resources.Load("Prefabs/Missle");
. Note that you don't need to put any file extension at the end (no .asset). Third, i can see you are trying to instantiate your prefab in MonoBehaviour script. You can directly reference your prefab using serialized field instead of loading it from resourced:
[SerializeField] GameObjecct prefab; // reference
...
var missle = Instantiate<GameObject>(prefab);
Fourth. If you want to do something when user press space bar:
void Update () {
if(Input.GetKeyDown(KeyCode.Space))
{
var missle = Instantiate<GameObject>(prefab);
}
}
Im strict done your instructions: 1) Put [SerializedField] GameObject $$anonymous$$issle;
outside methods but had no luck and got error: The type or namespace name
SerializedField' could not be found`. And also i dont get what prefab
in your example is, i thought here must be some path to him. 2) I moved my prefab to "Resorces" folder and tried again with my old code but with new path: missle = Instantiate(Resources.Load("$$anonymous$$issle")) as GameObject;
result the same. Also i tried pathes "Resorces/$$anonymous$$issle" and "Assets/Resorces/$$anonymous$$issle.prefab" but no luck. And this code: var missle = Instantiate<GameObject>(Resources.Load("$$anonymous$$issle"));
produce an error: "Argument #1' cannot convert
UnityEngine.Object' expression to type `UnityEngine.GameObject'" Any other suggestions please?
NV$$anonymous$$, it was just an typo in your answer about Resources folder an im double it. Finally it work, but only with my old code and just new path. If you can explain errors with your code im glad to read it. But anyway thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220612174610im_/https://answers.unity.com/themes/thub/images/avi.jpg)