Search Unity

  1. We are migrating the Unity Forums to Unity Discussions by the end of July. Read our announcement for more information and let us know if you have any questions.
    Dismiss Notice
  2. Dismiss Notice

Bug Hi I'm new to Unity I'm coding a stamina bar for my game but I keep getting error

Discussion in 'Scripting' started by CoderBoy101, Apr 27, 2024.

  1. CoderBoy101

    CoderBoy101

    Joined:
    Dec 28, 2020
    Posts:
    1
    "UnityException: get_deltaTime is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'StaminaBar' on game object 'Stamina'."

    Here's my code:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;

    public class StaminaBar : MonoBehaviour
    {
    public Slider slider;
    public static float MaxStamina = 100.0f;
    public static float CurrentStamina = 100.0f;

    void Start()
    {
    slider.maxValue = MaxStamina;
    slider.value = MaxStamina;
    }

    void Update()
    {
    slider.value = CurrentStamina;
    CurrentStamina -= Time.deltaTime * 10 * Input.GetAxis("Fire3");


    }
    }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    39,432
    The error is not in the unformatted code above.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.


    For future reference, if you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/