Unity3D C#实现玩家积7分时传送到指定GameObject位置的问题
Fixing the Teleport-on-7-Points Script
Hey there! Let's get this teleport functionality working smoothly. Your base script is already on the right track, but we need to add a few key pieces to avoid repeated teleports and properly reference the player. Here's the polished version:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FpsScoreScript : MonoBehaviour { public int points; public Transform Destination; // Assign your player object here in the Inspector (or skip if this script is on the player) public Transform player; // Prevent repeated teleportation since Update runs every frame private bool hasTeleported = false; void Start() { // Optional: Initialize points to 0 if you haven't set it in the Inspector points = 0; // If this script is attached to the player, we can auto-set the player reference if (player == null) { player = transform; } } void Update() { // Only trigger teleport if we hit 7 points AND haven't teleported yet if (points == 7 && !hasTeleported) { TeleportPlayer(); hasTeleported = true; } } // Call this method from your pickup item script when the player collects an item public void AddPoints(int amount) { points += amount; } private void TeleportPlayer() { // Make sure we have a destination set to avoid errors if (Destination != null && player != null) { player.position = Destination.position; // Optional: Match the destination's rotation too // player.rotation = Destination.rotation; } else { Debug.LogWarning("Player or Destination transform is not assigned!"); } } }
Key improvements explained:
hasTeleportedboolean: Stops the script from trying to teleport the player every single frame once they hit 7 points (which would cause weird jitter or repeated moves).- Player reference: Either assign your player in the Inspector, or let the script auto-detect if it's attached directly to the player.
AddPointsmethod: Gives you a clean way to increment points from your pickup item scripts (just callFindObjectOfType<FpsScoreScript>().AddPoints(1);in your pickup logic, or reference the script directly if possible).- Safety checks: Added null checks to prevent console errors if you forget to assign the Destination or Player in the Inspector.
- Optional rotation match: Uncomment the rotation line if you want the player to face the same direction as the Cube when they teleport.
Quick setup steps:
- Attach this script to either your player object or a manager object in your scene.
- Drag your Cube (destination) into the
Destinationfield in the Inspector. - If the script isn't on the player, drag your player object into the
Playerfield. - In your pickup item's script, call the
AddPointsmethod when the player collects the item.
内容的提问来源于stack exchange,提问作者FrostyEasy
相关产品推荐
相关产品推荐

