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'.
CodePudding user response:
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;
}