简体   繁体   English

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

[英]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.

相关问题 UnityException:不允许从 MonoBehaviour 构造函数调用 GetActiveScene - UnityException: GetActiveScene is not allowed to be called from a MonoBehaviour constructor C# - 不允许从 MonoBehaviour 构造函数调用 RandomRangeInt - C# - RandomRangeInt is not allowed to be called from a MonoBehaviour constructor “不允许从 MonoBehaviour 构造函数调用加载”在不从 MonoBehaviour 继承的脚本上 - "Load is not allowed to be called from MonoBehaviour constructor" On script that does not inherit from MonoBehaviour 不允许从 Monobehaviour 调用 persistentDatapath - persistentDatapath is not allowed called from Monobehaviour UnityException:不允许调用此函数 - UnityException: Not allowed to call this function 统一错误(脚本检查器3):不允许从ScriptableObject构造函数调用GetBool - Error in unity(Script Inspector 3): GetBool is not allowed to be called from a ScriptableObject constructor 错误帮助-UnityException:声明变量时不允许调用此函数 - Error Help - UnityException: You are not allowed to call this function when declaring a variable 为什么在非MonoBehaviour类中进行多个构造函数调用? - Why multiple constructor calls in a non MonoBehaviour class? 实例化从MonoBehaviour派生的类 - Instantiate a class that derives from MonoBehaviour 我可以从非单一行为脚本中访问单一行为脚本吗? - Can i access a monobehaviour script from within a non monobehaviour script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM