Consider the following Unity C# script attached to an empty GameObject in the scene. What will be printed in the console when the game starts?
using UnityEngine;
public class InstantiateTest : MonoBehaviour
{
public GameObject prefab;
void Start()
{
GameObject obj = Instantiate(prefab);
Debug.Log(obj.name);
}
}When you instantiate a prefab in Unity, the new object's name usually has a suffix added.
Unity adds "(Clone)" to the name of instantiated GameObjects to distinguish them from the original prefab asset.
In Unity C#, which method is used to create a copy of a GameObject during runtime?
Think about the method that duplicates objects in Unity scripts.
The Instantiate() method is the standard way to create copies of GameObjects or prefabs at runtime in Unity.
Examine the code below. What error will occur when running this script if the prefab variable is not assigned in the Inspector?
using UnityEngine;
public class SpawnObject : MonoBehaviour
{
public GameObject prefab;
void Start()
{
GameObject obj = Instantiate(prefab);
}
}What happens if you try to use a variable that has not been set?
If prefab is null, calling Instantiate(prefab) causes a NullReferenceException because you cannot instantiate a null object.
Choose the correct syntax to instantiate a prefab at position (0, 1, 0) with no rotation in Unity C#.
Remember how to create a Vector3 and use Quaternion for rotation.
Instantiate requires a Vector3 position and a Quaternion rotation. Vector3 must be created with new Vector3(x, y, z).
Given the following Unity C# code, how many GameObjects will exist in the scene after Start() finishes?
using UnityEngine; public class MultiInstantiate : MonoBehaviour { public GameObject prefab; void Start() { for (int i = 0; i < 3; i++) { Instantiate(prefab); } Instantiate(prefab); } }
Count how many times Instantiate is called in total.
The loop runs 3 times, each calling Instantiate once, plus one more Instantiate call after the loop, totaling 4 GameObjects created.