UnityException:不允许从 MonoBehaviour 构造函数调用 get_time

Tie*_*ung 1 c# unity-game-engine

我正在尝试制定一种方法来防止玩家发送垃圾邮件空格键。

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;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这是来自 Unity 的错误声明:我认为这不是逻辑错误

UnityExceptionget_time不允许从 MonoBehaviour 构造函数(或实例字段初始值设定项)调用,而是在 Awake 或 Start 中调用它。从游戏对象“Player”上的 MonoBehaviour“PlayerControllerX”调用。

小智 5

就像说你不能private float timer = Time.time;在声明上设置。你应该做这样的事情

private float timer = 0;

void Start(){
timer = Time.time;
}
Run Code Online (Sandbox Code Playgroud)