基于Vuforia与Unity 3D的图像识别文本切换C#代码需求
Hey there! Let's fix that unstable text update issue with Vuforia in Unity. The problem with your original code is that polling in Update() isn't the most reliable way to track Vuforia's target state changes—we should hook directly into Vuforia's built-in tracking events instead. This will make your text updates instant and stable, plus we'll clean up redundant code and handle target loss properly.
What Was Wrong With the Original Approach?
- Polling in
Update()can lead to frame delays or missed state changes, especially if targets switch quickly. - No handling for when all targets are lost (your text would never revert to "SCAN QRCODE").
- Redundant
else ifblocks for targets that share the same text, making the code hard to maintain.
Improved Solution
We'll create a custom trackable handler to emit events when targets are found/lost, then have our controller listen to those events to update the UI.
Step 1: Custom Trackable Event Handler
Replace Vuforia's default handler with this one to send state change events:
using UnityEngine; using Vuforia; public class CustomTrackableEventHandler : DefaultTrackableEventHandler { // Events to notify other scripts when targets are found/lost public static event System.Action<string> OnTargetFound; public static event System.Action OnTargetLost; protected override void OnTrackingFound() { base.OnTrackingFound(); // Send the found target's name to subscribers OnTargetFound?.Invoke(TrackableBehaviour.TrackableName); } protected override void OnTrackingLost() { base.OnTrackingLost(); // Notify subscribers the target was lost OnTargetLost?.Invoke(); } }
Step 2: Updated Data Controller
This controller listens to the events and manages UI updates cleanly:
using UnityEngine; using UnityEngine.UI; using Vuforia; public class DataControllerCS002 : MonoBehaviour { public Text winText; public GameObject EndPanel; // Map target names to their display text (easy to edit/maintain) private readonly System.Collections.Generic.Dictionary<string, string> _targetTextMap = new() { {"qr1", "Walk Straight"}, {"qr1left2", "Walk Straight"}, {"left1", "Walk Straight"}, {"qrright1", "Walk Straight"}, {"qrright2", "Walk Straight"}, {"qrcenter", "Walk Left"} }; void Start() { winText.text = "SCAN QRCODE"; EndPanel.SetActive(false); // Subscribe to tracking events CustomTrackableEventHandler.OnTargetFound += HandleTargetFound; CustomTrackableEventHandler.OnTargetLost += HandleTargetLost; } // Clean up subscriptions to avoid memory leaks void OnDestroy() { CustomTrackableEventHandler.OnTargetFound -= HandleTargetFound; CustomTrackableEventHandler.OnTargetLost -= HandleTargetLost; } private void HandleTargetFound(string targetName) { EndPanel.SetActive(true); // Get the corresponding text for the target, or use a fallback if (_targetTextMap.TryGetValue(targetName, out var displayText)) { winText.text = displayText; } else { winText.text = "Unknown Target"; } } private void HandleTargetLost() { // Only revert to initial state if no targets are active var trackableManager = TrackerManager.Instance.GetStateManager(); var activeTrackables = trackableManager.GetActiveTrackableBehaviours(); if (activeTrackables.Count == 0) { winText.text = "SCAN QRCODE"; EndPanel.SetActive(false); } } }
How to Use
- On all your Vuforia Image Targets, replace the
DefaultTrackableEventHandlercomponent withCustomTrackableEventHandler. - Attach
DataControllerCS002to a persistent object in your scene (like a UI Manager). - Assign your
winTextandEndPanelreferences in the Inspector.
Key Benefits
- Event-driven updates: No more frame-by-frame polling—UI updates only happen when a target's state actually changes.
- Maintainable structure: Add/modify target-text pairs in the dictionary without touching logic code.
- Proper target loss handling: The UI reverts to its initial state when no targets are detected.
- Works for all targets: No dependency on a single trackable reference.
内容的提问来源于stack exchange,提问作者Bibin Hashley

