Swift+ARKit应用:计数器达标后奖杯未生成的问题修复求助
Hey there! Let's figure out why your addTrophy() function isn't firing when the counter hits 20. Here are the most common issues and actionable fixes to check:
1. Double-check your counter update logic
First, make sure you're properly updating the counter variable and triggering the trophy check every time the plus button is tapped. Your plus button's IBAction should look something like this:
@IBAction func plusButtonTapped(_ sender: UIButton) { counter += 1 points.text = "\(counter)" // Sync the counter value to your UI label checkIfShouldAwardTrophy() // Run the check after every increment }
If you're not explicitly running a check after each counter update, the addTrophy() call will never get triggered—even if the counter hits 20.
2. Verify your condition statement is correct
It's easy to make a tiny syntax mistake here that breaks everything. Common issues include:
- Accidentally using assignment (
=) instead of equality check (==) - Setting the wrong condition (e.g.,
counter > 20instead ofcounter == 20) - Forgetting to initialize
counterto 0 (so it starts at 1 and hits 21 instead of 20)
Here's a solid implementation of the check function:
func checkIfShouldAwardTrophy() { if counter == 20 { print("Counter hit 20! Calling addTrophy()") // Add this to debug addTrophy() // Optional: Show your congratulation button congratulation.isHidden = false } }
The print statement will help you confirm if the condition is actually being triggered (check your Xcode console!).
3. Ensure addTrophy() works on its own
Sometimes the issue isn't the condition—it's the trophy function itself. Test if addTrophy() works by calling it manually (e.g., in viewDidLoad()). If you don't see a trophy, fix this function first:
func addTrophy() { // Example: Create a simple trophy node and add it to the AR scene let trophyGeometry = SCNPyramid(width: 0.2, height: 0.3, length: 0.2) trophyGeometry.firstMaterial?.diffuse.contents = UIColor.gold let trophyNode = SCNNode(geometry: trophyGeometry) trophyNode.position = SCNVector3(0, 0, -1) // Place it where the camera can see it sceneView.scene.rootNode.addChildNode(trophyNode) }
Make sure you're adding the trophy node to the AR scene's root node, and setting a position that's visible to the camera.
4. Check for UI thread issues
ARKit scene operations and UI updates must happen on the main thread. If your counter update is somehow running on a background thread, wrap the logic in a main dispatch call:
DispatchQueue.main.async { self.counter += 1 self.points.text = "\(self.counter)" self.checkIfShouldAwardTrophy() }
Start with the debug print statement to confirm if the condition is firing—once you know that works, you can narrow down whether the problem is in the counter logic or the trophy generation itself.
内容的提问来源于stack exchange,提问作者Concon23b

