[英]UnityException: get_time is not allowed to be called from MonoBehaviour constructor
I'm trying to make a method that prevents player from spamming Space key.我正在尝试制作一种方法来防止玩家向Space键发送垃圾邮件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControllerX : MonoBehaviour
{
public GameObject dogPrefab;
private float setTime = 2.0f;
private float timer = Time.time;
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer >= setTime)
{
SpawnDog();
}
}
void SpawnDog()
{
// On spacebar press, send dog
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(dogPrefab, transform.position, dogPrefab.transform.rotation);
timer = 0;
}
}
}
And this is an error statement from Unity: I think it was not a logic error这是来自 Unity 的错误声明:我认为这不是逻辑错误
UnityException: get_time is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. UnityException: get_time 不允许从 MonoBehaviour 构造函数(或实例字段初始值设定项)调用,而是在 Awake 或 Start 中调用。 Called from MonoBehaviour 'PlayerControllerX' on game object 'Player'.从游戏 object 'Player' 上的 MonoBehaviour 'PlayerControllerX' 调用。
Like say there you cannot set private float timer = Time.time;
就像说那里你不能设置private float timer = Time.time;
on the declaration.声明上。 You should do something like this你应该做这样的事情
private float timer = 0;
void Start(){
timer = Time.time;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.