Unity FPS开发问题:原GameObject销毁后Spawner无法克隆的解决方法
Hey there! As someone who’s stumbled through this exact Unity newbie pitfall before, let’s break down why your spawner stops working after the original Orc gets destroyed—this is a super common issue, and we can fix it quickly.
The #1 Culprit: You’re Using a Scene Object Instead of a Prefab
The most likely reason your spawner breaks is that it’s referencing the actual Orc in your scene, not a reusable prefab. When you destroy that scene Orc, the spawner’s reference turns to null, so it can’t create new copies anymore.
Step-by-Step Fixes
1. Create & Use an Orc Prefab
- In your Hierarchy, drag the original Orc into the Project window—this turns it into a prefab (you’ll see it turn blue in the Project panel).
- Delete the original Orc from the scene (or keep it, but make sure your spawner doesn’t reference it anymore).
- Open your Spawner script, and make sure you have a public variable for the prefab, like:
public GameObject orcPrefab; - In the Inspector for your Spawner, drag the new Orc prefab from the Project window into the
orcPrefabslot.
2. Fix Your Spawner Code
Double-check that your spawn logic uses the prefab reference, not a scene object. Here’s a correct example:
public Transform spawnPoint; // Assign this in the Inspector public GameObject orcPrefab; void SpawnOrc() { // Always check for null to avoid errors if (orcPrefab == null) { Debug.LogError("Orc Prefab is not assigned to the Spawner!"); return; } // Create a new Orc from the prefab Instantiate(orcPrefab, spawnPoint.position, spawnPoint.rotation); }
If your old code referenced a scene Orc instance instead of a prefab, that’s exactly why it broke after destruction.
3. Check for Accidental "One-Time Spawn" Logic
Sometimes spawners have unintended restrictions, like a private bool hasSpawned = false; that gets set to true after the first spawn and never resets. If you find this, either remove the restriction or reset the bool when an Orc is destroyed.
4. Check the Console for Errors
Open the Console window (Window > General > Console) while running the game. If you see a NullReferenceException, it’ll point directly to the line where the spawner is trying to use a destroyed/empty reference—this is your biggest clue.
5. Verify Orc Destruction Logic
Make sure your Orc’s death script only destroys itself, not the spawner or critical components. The correct way to destroy the Orc is:
// In your Orc's health/death script void Die() { Destroy(gameObject); // Only destroys this specific Orc instance }
Quick Test
After setting up the prefab and fixing the code, hit play. The spawner should generate a new Orc right away (or whenever your spawn trigger fires), and when you kill it, the spawner should keep creating new ones without issues.
内容的提问来源于stack exchange,提问作者Jon Bergeron

