Unity中如何每隔X秒执行一次程序?立方体定时瞬移功能异常求助
Hey there! Let's figure out why your cube only teleports once, then fix it with a couple straightforward solutions.
What's Wrong With Your Current Code?
Your original code only runs the teleport logic once in the Start() method. The coroutine you wrote just waits 5 seconds but doesn't trigger another teleport or restart itself afterward. And putting the teleport in Update() makes it run every frame—way too fast!
Solution 1: Use a Looping Coroutine (Flexible & Powerful)
Coroutines are perfect for timed, repeated actions because you can control the flow easily. We'll wrap the teleport logic in a coroutine that loops infinitely, waiting the specified time between each teleport.
Here's the updated code:
public class Teleport_Cube : MonoBehaviour { public Transform cubepos; // Assign your cube in the Inspector public List<Transform> teleportTargets = new List<Transform>(); // Rename for clarity public float teleportInterval = 5f; // Adjust this in Inspector for different delays void Start() { // Start the repeating teleport coroutine when the game begins StartCoroutine(RepeatTeleport()); } IEnumerator RepeatTeleport() { // Loop forever until we explicitly stop the coroutine while (true) { // Make sure we have targets to teleport to (avoids errors) if (teleportTargets.Count > 0) { int randomIndex = Random.Range(0, teleportTargets.Count); cubepos.position = teleportTargets[randomIndex].position; } // Wait the specified number of seconds before the next teleport yield return new WaitForSeconds(teleportInterval); } } // Optional: Call this method if you need to stop teleporting later public void StopTeleporting() { StopCoroutine(RepeatTeleport()); } }
Key Changes:
- Renamed
transformstoteleportTargetsfor better readability - Added a public
teleportIntervalso you can adjust the delay without editing code - Added a check to ensure we have targets (prevents null reference errors)
- The coroutine uses a
while(true)loop to repeat the teleport/wait cycle indefinitely
Solution 2: Use InvokeRepeating (Simple & Clean)
If you want a more concise approach, Unity's InvokeRepeating method lets you schedule a method to run repeatedly with a set delay.
Here's how to implement it:
public class Teleport_Cube : MonoBehaviour { public Transform cubepos; public List<Transform> teleportTargets = new List<Transform>(); public float initialDelay = 0f; // Delay before the first teleport public float teleportInterval = 5f; void Start() { // Schedule the Teleport method to run repeatedly // Parameters: method name, initial delay, repeat interval InvokeRepeating(nameof(Teleport), initialDelay, teleportInterval); } void Teleport() { if (teleportTargets.Count > 0) { int randomIndex = Random.Range(0, teleportTargets.Count); cubepos.position = teleportTargets[randomIndex].position; } } // Optional: Stop the repeating teleport public void StopTeleporting() { CancelInvoke(nameof(Teleport)); } }
How This Works:
InvokeRepeatingautomatically calls theTeleportmethod afterinitialDelayseconds, then repeats it everyteleportIntervalseconds- Set
initialDelayto5fif you want the first teleport to wait 5 seconds instead of happening immediately
Quick Setup Tips
- Make sure you assign your cube to the
cubeposfield in the Inspector - Add at least one target Transform to the
teleportTargetslist (these are the positions your cube will jump to) - Adjust
teleportIntervalto control how often the cube teleports
内容的提问来源于stack exchange,提问作者MilkyMilk_07

