Confusion on Instantiating Game Objects

I’m relatively new to Unity/C# so I’m having trouble understanding the code snippets I find online regarding Instantiating Objects. Typically I see something like,

public GameObject prefab;
// more code

// in a function
Instantiate(prefab, position, quaternion);

How is this valid code? “prefab” never gets initialized or assigned. When I attempted to do this knowing it doesn’t make any sense, I get an “UnassignedReferenceException” like you would expect. Here are links to the examples in question:

For my purposes, I simply want to spawn something that does NOT already exist in the scene in the scene using a script, but I can’t find anything that can do that.

Thanks.

Use the script reference rather.
You posted pseudo code, which is just a summary of the method and not an actual snippet.

It is a reference type. It’s usually assigned in the inspector which makes it valid.

If you don’t assign anything to that field in the inspector then yes, it will be null, and you will get a NullReferenceException when you try to use it.

Thanks for the clarification!

Is there any way to get a reference to a prefab without creating a public variable and setting it in the inspector? What if you had 30 different prefabs that the script might instantiate. Do you need to create 30 public variables? I suppose you could create a public array or list so that multiple prefabs could be assigned to the script.

Ideally you don’t want to be required to find the prefab manually, in the project assets, in your code. You can, but it is very unlikely to be the best way to handle the situation.

In the event that you are trying to find a prefab you are already looking for something that is static and if something is static then you don’t need to guess what or where it is. In that case you’ll want to be using a database of some kind to keep track of the target prefabs. This is usually in the form of a ScriptableObject with a List that you can drag prefabs into. At that point you only have to query one static database item in your project to reach any prefab you want, plus you’re able to manage how the lookups are done, what kind of identifiers are required, it’s always going to be cheaper than scrubbing through the entire project Resources/AssetDatabase for something you need and it’s less risky since you can control the whole process.

1 Like

Something Like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class test : MonoBehaviour
{

    //You can make this public if you need to access it from another script using static, instance or getComponent.
//ie GameObjectThatHasScript.GetComponent<test>().prefabList;

    Public Dictionary<string, GameObject> prefabList = new Dictionary<string, GameObject>();

    void Start()
    {
        //Create Prefab
        //And Add it to a Dictionary, I've used a String Key, but you can use an int etc
        //You could also use a simpler List or even a fixed Array if you want; ie. GameObject[]
        //The idea is that we need to store the prefabs to access them later.

        for (int i = 0; i < 10; i++)
        {
            GameObject prefab = Instantiate(Resources.Load("somePrefab", typeof(GameObject))) as GameObject;
            prefabList[i.ToString()] = prefab;
            //You can give prefab information here if you wish, or rename it i.e.; prefab.name = "prefab_" + i.ToString();
        }

        //Verbose Prefab List
        //You can Do whatever is needed with this set of Prefabs that you have created in the scene
       //If you used a fixed array you can do a simple for loop to grab the data or reference the prefab by key or index etc.
      //ie GameObject thisPrefab = GameObjectThatHasScript.GetComponent<test>().prefabList[key];

        foreach (string key in prefabList.Keys)
        {
            Debug.Log(prefabList[key]);
        }

    }


}