You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何每隔X秒执行一次程序?立方体定时瞬移功能异常求助

Fixing Your Cube's Repeating Teleport Issue

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 transforms to teleportTargets for better readability
  • Added a public teleportInterval so 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:

  • InvokeRepeating automatically calls the Teleport method after initialDelay seconds, then repeats it every teleportInterval seconds
  • Set initialDelay to 5f if you want the first teleport to wait 5 seconds instead of happening immediately

Quick Setup Tips

  1. Make sure you assign your cube to the cubepos field in the Inspector
  2. Add at least one target Transform to the teleportTargets list (these are the positions your cube will jump to)
  3. Adjust teleportInterval to control how often the cube teleports

内容的提问来源于stack exchange,提问作者MilkyMilk_07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:32:31