Consider the following Unity C# script snippet that instantiates a prefab multiple times:
public GameObject enemyPrefab;
void Start() {
for (int i = 0; i < 3; i++) {
GameObject enemy = Instantiate(enemyPrefab);
enemy.name = "Enemy_" + i;
Debug.Log(enemy.name);
}
}What will be printed in the Unity console?
public GameObject enemyPrefab;
void Start() {
for (int i = 0; i < 3; i++) {
GameObject enemy = Instantiate(enemyPrefab);
enemy.name = "Enemy_" + i;
Debug.Log(enemy.name);
}
}Look at how the loop index i is used to name each instantiated object.
The loop runs 3 times with i values 0, 1, and 2. Each instantiated prefab is renamed to "Enemy_" plus the current i. So the console logs "Enemy_0", "Enemy_1", and "Enemy_2" in order.
In Unity, when you create an instance of a prefab in the scene, which of the following is correct?
Think about how prefab assets and instances relate in Unity.
Prefab instances are linked to the prefab asset. When you modify the prefab asset, all instances update automatically. However, changes to an instance do not affect the prefab asset or other instances unless you apply those changes explicitly.
Examine the following Unity C# code snippet:
public GameObject bulletPrefab;
void Shoot() {
GameObject bullet = Instantiate(bulletPrefab);
bullet.GetComponent().AddForce(transform.forward * 500);
} When running, it throws a NullReferenceException at the GetComponent line. What is the most likely cause?
Check if the prefab variable is assigned before instantiating.
If bulletPrefab is null (not assigned in the Inspector), then Instantiate returns null, so calling GetComponent on null causes the exception.
You want to instantiate a prefab and make the new object a child of a specific GameObject called container. Which code snippet is correct?
Look for the overload of Instantiate that accepts a parent transform and a boolean for world position.
Option A uses the correct Instantiate overload that sets the parent transform and specifies whether to keep world position. This is the recommended way to instantiate and parent in one step.
Given the following code snippet in Unity:
public GameObject enemyPrefab;
void SpawnEnemies() {
GameObject[] enemies = new GameObject[5];
for (int i = 0; i < 5; i++) {
enemies[i] = Instantiate(enemyPrefab);
}
enemies[2] = enemies[0];
}After SpawnEnemies() finishes, how many unique GameObjects exist in the enemies array?
Consider what happens when you assign enemies[2] = enemies[0].
The loop creates 5 unique instances. But then enemies[2] is set to reference the same object as enemies[0], so the array holds 4 unique GameObjects and one duplicate reference.