Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

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

UnityException: get_time is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour ‘PlayerControllerX’ on game object ‘Player’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Like say there you cannot set private float timer = Time.time; on the declaration.
You should do something like this

private float timer = 0;

void Start(){
timer = Time.time;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading