You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity新手求助:实例化对象为空,如何无IF随机生成预制体

Fixing the Null Reference Error in Your Unity Spawn Script

Hey there! Let's break down why you're hitting that "Object you want to instantiate is null" error and fix it properly, while keeping your "no if statements" goal intact.

What's Going Wrong

Your core issues stem from how you're trying to access and use your prefabs:

  • GameObject.Find() only searches for active objects already placed in your scene—it can't locate prefabs stored in your Project panel. That's why it's returning null every time you call it.
  • Even if your prefabs were in the scene, you're using variable names (like "cub") in your string array, not the actual object names in the scene. These might not match, leading to more lookup failures.
  • Your Spawn() coroutine never gets started! The Start() method only runs a single instantiation, but the loop you wrote to spawn every second never executes.
  • A small bug: Random.Range(0, 3) only returns values 0, 1, 2—but your string array has 4 elements (indices 0-3). You'd never spawn the fourth prefab ("sfera") with that range.

The Fix: Use a GameObject Array Instead of Strings

The cleanest way to avoid if statements and fix the null error is to store your prefabs directly in a GameObject array. This lets you skip GameObject.Find() entirely and just pick a random element from the array.

Here's the revised code:

using System.Collections;
using UnityEngine;

public class Spawnnoif : MonoBehaviour {
    // Drag your 4 prefabs into this array in the Inspector
    public GameObject[] spawnPrefabs;

    void Start() {
        // Start the coroutine so your spawn loop runs
        StartCoroutine(SpawnLoop());
    }

    IEnumerator SpawnLoop() {
        while (true) {
            // Generate a random spawn position
            Vector3 spawnPosition = new Vector3(
                Random.Range(-1.88f, 2.1f), 
                1f, 
                Random.Range(-7.81f, -3.1f)
            );

            // Pick a random prefab from the array (works for any number of prefabs!)
            int randomPrefabIndex = Random.Range(0, spawnPrefabs.Length);
            GameObject selectedPrefab = spawnPrefabs[randomPrefabIndex];

            // Instantiate the selected prefab
            Instantiate(selectedPrefab, spawnPosition, Quaternion.identity);

            // Wait 1 second before spawning again
            yield return new WaitForSeconds(1.0f);
        }
    }
}

Step-by-Step Setup

  1. In the Unity Editor, select the GameObject that has this script attached.
  2. In the Inspector, expand the Spawn Prefabs array, then set its size to 4.
  3. Drag each of your four prefabs (cub, capsula, cilindru, sfera) from the Project panel into the four slots in the array.
  4. Hit play—you'll see a random prefab spawn every second, no null errors!

Why This Works

  • Directly referencing prefabs is the standard Unity workflow—it's faster, more reliable, and avoids the pitfalls of string-based lookup.
  • Using spawnPrefabs.Length in Random.Range() ensures you'll always pick a valid index, even if you add or remove prefabs later (no need to update the range manually).
  • Starting the coroutine in Start() ensures your spawn loop actually runs, so you get that "spawn every second" behavior you want.

内容的提问来源于stack exchange,提问作者Morar Mihai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:52:37