Unity 2D中如何避免生成对象引用问题及预制体Canvas绑定方案
Hey there! Let's tackle your two core problems with practical, game-ready solutions that fit right into your existing code.
1. Solving Reference Issues for Health Bars & Scoreboards
The problem here is you're trying to grab components like AnzeigePunktzahlPlayer2 or Spawner directly from your car prefab with GetComponent()—but those components live on separate objects, not the car itself. The cleanest way to fix this is using singletons (since your spawner and scoreboards are global, one-of-a-kind objects).
Step 1: Turn Spawner into a Singleton
Update your Spawner script to add a static instance, so any script can access it from anywhere:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public static Spawner Instance; // Singleton reference public GameObject carPrefab; public GameObject enemyCarPrefab; public GameObject kugel; public float respawnTime = 10.0f; public int counterPlayer1=0; public int counterPlayer2=0; public int counterEnergy=0; void Start () { Instance = this; // Initialize the singleton when the game starts StartCoroutine(carWave()); } // ... Rest of your Spawner code stays the same }
Step 2: Turn Scoreboards into Singletons
Do the same for your scoreboard scripts (like AnzeigePunktzahlPlayer2):
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class AnzeigePunktzahlPlayer2 : MonoBehaviour { public static AnzeigePunktzahlPlayer2 Instance; // Singleton reference public int counter; public TextMeshProUGUI textPlayer2; void Start() { Instance = this; textPlayer2 = GetComponent<TextMeshProUGUI>(); } void Update() { textPlayer2.SetText(counter.ToString()); } }
Step 3: Update EnemyCar to Use Singletons
Remove the old points and sp variables from EnemyCar, and replace any references to them with the singleton instances:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyCar : MonoBehaviour { public float speed = 3f; int zählerAuto1=0; private Vector2 screenBounds; public int maxHealth=100; public int currentHealth; public HealthBar healthbar; // Assign this in the prefab inspector later void Start () { screenBounds = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)); currentHealth = maxHealth; healthbar.SetMaxHealth(maxHealth); } void Update() { Vector2 pos = transform.position; if(pos.x > -855f){ pos.x -= speed * Time.deltaTime; transform.position = pos; zählerAuto1++; }else{ // Use the singleton to update score and spawn counter AnzeigePunktzahlPlayer2.Instance.counter++; Debug.Log(AnzeigePunktzahlPlayer2.Instance.counter); Spawner.Instance.counterPlayer2--; Debug.Log(Spawner.Instance.counterPlayer2); Destroy(this.gameObject); } } // ... Rest of your EnemyCar code stays the same }
2. Adding a Canvas to Your Car Prefab (With Linked Health Bar)
To make a health bar that spawns with your car and stays attached, you'll nest a World Space Canvas directly inside your car prefab. Here's how:
Step 1: Set Up the Canvas in the Prefab
- Open your
enemyCarPrefabin the editor. - Right-click the prefab root → UI → Canvas to create a child Canvas object.
- Select the new Canvas, then in the Inspector:
- Set Render Mode to
World Space. - Drag your main Camera into the Render Camera field (so the UI renders correctly).
- Adjust the Rect Transform:
- Set Position to
(0, 2, 0)(places the health bar above the car). - Set Width/Height to something like
200x50(adjust to fit your art). - Set Scale to
(0.01, 0.01, 0.01)(World Space uses world units, so we shrink it to fit 2D).
- Set Position to
- Set Render Mode to
Step 2: Add the Health Bar UI
- Inside the Canvas, create two Image objects:
HealthBarBackground: Use a solid gray image as the empty health bar.HealthBarFill: Use a colored image (like green) as the filled portion, set its anchor to the left so it shrinks/grows horizontally.
- Attach your
HealthBarscript to the Canvas or the fill object. Configure the script to reference the fill image (so it can update the fill amount).
Step 3: Link the Health Bar to the Car
In the enemyCarPrefab inspector, find the EnemyCar component. Drag the HealthBar component (from the Canvas child) into the healthbar field. Now every time you spawn a car, it will already have a reference to its own health bar.
Quick Notes to Avoid Headaches
- Make sure your singleton objects (Spawner, scoreboards) are placed in your scene before running the game (not spawned dynamically).
- For the World Space Canvas, tweak the position/scale until the health bar looks right next to your car during gameplay.
内容的提问来源于stack exchange,提问作者MAHAMA




