Unity切换Character Controller后,玩家触标签物体无法瞬移的问题
Hey, I see exactly what's going on here! When you switch to using a CharacterController for player movement, directly setting transform.position won't work as expected—this component manages its own internal movement state and will override any direct position changes you try to make. Let's fix this up with two solid solutions:
Recommended Solution: Use CharacterController.Teleport()
Unity added the Teleport() method to CharacterController (available in 2019.3 and later) specifically for cases like this. It safely moves the character to a new position without breaking the controller's state. Here's your updated script:
using System.Collections; using System.Collections.Generic; using UnityEngine; // Important: Unity requires script filenames to match class names—rename this file to Found.cs public class Found : MonoBehaviour { private CharacterController _playerController; private void Start() { // Grab the CharacterController component attached to the player object _playerController = GetComponent<CharacterController>(); } private void OnTriggerEnter(Collider collider) { // Use CompareTag instead of direct tag comparison (better performance + warnings for typos) if (collider.gameObject.CompareTag("are you seen")) { Vector3 targetPosition = new Vector3(-15.38f, 1.93f, 62.1f); _playerController.Teleport(targetPosition); } } }
Fallback Solution (For Older Unity Versions)
If you're working with a Unity version before 2019.3 where Teleport() doesn't exist, you can temporarily disable the CharacterController, set the position, then re-enable it:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Found : MonoBehaviour { private CharacterController _playerController; private void Start() { _playerController = GetComponent<CharacterController>(); } private void OnTriggerEnter(Collider collider) { if (collider.gameObject.CompareTag("are you seen")) { // Disable the controller so position changes stick _playerController.enabled = false; transform.position = new Vector3(-15.38f, 1.93f, 62.1f); // Re-enable to resume normal movement _playerController.enabled = true; } } }
Quick Checks to Ensure It Works
- Rename your script: Make sure the file is named
Found.cs(matches the class name) to avoid Unity loading errors. - Trigger Collider Setup: The object with the "are you seen" tag must have a Collider component with the
Is Triggercheckbox enabled. - Collision Layers: Double-check that the player's layer and the trigger object's layer aren't set to ignore each other in Unity's Physics Settings.
内容的提问来源于stack exchange,提问作者Tucker kunkle

