Can I set the max of [Range(0, max)] to a seperate variable?

I’m making my own health system.

I want to have it so that I can set the value of maxHealth in the Inspector, and then have a currentHealth variable use a slider to set that too, with the maximum amount being equal to maxHealth.

Is this possible?

I’ll include some code to hopefully get across what I mean:

[SerializeField] private float maxHealth = 0f; // The default health value for object
[SerializeField, Range(1, maxHealth)] private float currentHealth; // The current health value, used in play

OnValidate is very useful to program any such custom logic without need for custom editor attributes etc.

[SerializeField] float maxHealth = 0f;
[SerializeField] float currentHealth;

#if UNITY_EDITOR
void OnValidate ()
{
    currentHealth = Mathf.Clamp( currentHealth , 1f , maxHealth );
}
#endif

Hi,

One way you could set this up is by creating two public variables that you can edit in the inspector, the Slider and the MaxHP.

Then, in the script, set both the hpSlider.maxValue and the hpSlider.value equal to the maxHP. Here is a code example to better explain what I mean.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BattleHUD : MonoBehaviour
{
    public Slider hpSlider;
    public int maxHp;

    void Start() 
    {
        SetHUD();
    }

    //Set HUD elements
    public void SetHUD()
    {
        hpSlider.maxValue = maxHp;
        hpSlider.value = maxHp;
    }
}

Next you should make a public method to update the health slider so it can be called outside of the class whenever you need to update the health.

    public void UpdateHP(int hp)
    {
        hpSlider.value = hp;
    }

This method will take in a new value and set the hpSlider.value to the new value that you passed to it, but still keep the hpSlider.maxValue the same.

I hope this info was somewhat helpful.

Side note

As a side note, when I did this for one of my projects I created another script called Stats that stored the object’s stats as separate integers and passed them into the SetHUD method which is why I made it public. That code looked something like this.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BattleHUD : MonoBehaviour
{
    public Slider hpSlider;

    //Set HUD elements
    public void SetHUD(Stats enemy)
    {
        hpSlider.maxValue = enemy.MaxHp;
        hpSlider.value = enemy.currHp;
    }

    //update HP Slider
    public void UpdateHP(int hp)
    {
        hpSlider.value = hp;
    }
}

This was helpful for when I wanted to create enemies that could have random or different health from each other.