0
votes
    void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Instantiate(Resources.Load("Objects/Level"), transform.position, Quaternion.identity);
    }
}

This is my code. I have an object named Level.obj inside of a folder named "Objects" inside of my Assets. I attempt to spawn it on top of the parent object of this script with Resources.Load("Object/Level"). I believe this code itself is correct because the console returns with "The Object you want to instantiate is null." upon pressing the spacebar. What's probably wrong is my parameters, specifically how I attempted to find the object. I have also tried Assets/Objects/Level as opposed to what's above.

2
If you want to use Resource.Load, your asset has to be under a folder named "Resources". If you wanted to leave your code the way it was, you'd have to put your asset at the path "Assets/Resources/Objects/Level.obj"Foggzie

2 Answers

3
votes

Add a public field public GameObject myPrefab; to your monobehavior.

Set it in the editor by selecting your gameobject and using the inspector.

Instantiate it like Instantiate(myPrefab, transform.position, Quaternion.identity);

You only need Resources.Load if your asset doesn't exist at compile time. And like the documentation says, Resources.Load needs the asset to be in the Resources folder.

https://docs.unity3d.com/ScriptReference/Resources.Load.html

0
votes

I never used Resources.Load() so you may try to achieve something different, but what I do to "spawn" objects is to make them into a prefab (just drag/drop your object to your assets). Then declare a public GameObject field on your script, drag/drop the prefab in it in the inspector and then Instantiate it like you did.

Hope it helped !