【发布时间】:2023-02-26 01:18:27
【问题描述】:
如何以随机时间间隔创建对象? 我用“Random.Range()”给了“spawnInterval”一个时间间隔,并将“spawnInterval”放在“InvokeRepeating”中并得到了一个错误。
这是我的代码的一部分......
private float startDelay = 2.0f;
private float spawnInterval = Random.Range(1.0f, 3.0f);
void Start()
{
InvokeRepeating("Spawn", startDelay, spawnInterval);
}
void Spawn(){}
【问题讨论】:
-
你能更具体地说明你得到的错误吗?
-
@Serlite 我得到了这个 -> UnityException: Range is not allowed to be called from a MonoBehaviour constructor (or instance field initializer),改为在 Awake 或 Start 中调用它。在游戏对象“Generator”上从 MonoBehaviour“Generator”调用。有关详细信息,请参阅 Unity 手册中的“脚本序列化”页面。 Generator..ctor ()(位于 Assets/Scripts/Generator.cs:14)
-
最好的方法是使用 100ns 的滴答。 Timespan 具有 TimeSpan.TicksPerSecond 和 TimeSpan.TicksPerMinute 等属性。因此,如果您想要 1 到 60 秒的随机时间跨度,您的下限是 TimeSpan.TicksPerSecond,上限是 60 * TimeSpan.TicksPerSecond
标签: c# unity3d random intervals