transform.LocalScale dynamically, please help :(

Hey guys, bit of an issue I’m struggling to understand, I have this script, it’s just controlling the scale along the X axis, depending on the health of something. Here’s the code

public float currentHealth = 0.5f;

    void Update(){
        healthBar.transform.localScale = new Vector3(currentHealth, 1f, 1f);

    }

It works if I just input 0.5f instead of currentHealth, but I want it to dynamically scale down depending on the currentHealth, can you just now use a variable like that in a Vector3?, is there a quick workaround?.

thanks in advance!

The code seems to do what. Do you mean “animate”?

The easiest way would be to use Mathf.SmoothDamp ( https://docs.unity3d.com/ScriptReference/Mathf.SmoothDamp.html ) that has currentHealth as target, always.

I assumed that healthBar.transform.localScale = new Vector3(currentHealth, 1f, 1f); would be exactly the same as healthBar.transform.localScale = new Vector3(0.5f, 1f, 1f);, since currentHealth is equal to 0.5f, and as that changes, it’ll update the scale of the the healthBar. but that doesn’t work, it is fundamentally impossible to do it this way or have I just messed something up that I’m not seeing? first time I’m using LocalScale, and I’m not too knowledgeable in c#.

Never seen Mathf.SmoothDamp either, but I will look into that, so thanks!

That should work. Do you maybe have the mesh as static?

What happens when you change the currentHealth value? Nothing?

public class TankController : MonoBehaviour
{
  
    public GameObject healthBar;
    public GameObject[] nodes;


    public float maxHealth = 1f;
    public float minHealth = 0f;
    public float currentHealth = 0.5f;

    void Update(){
        healthBar.transform.localScale = new Vector3(currentHealth, 1f, 1f);

    }
}

Here’s more of the code for you to see, it’s not much.

when I use 0.5f instead of currentHealth, the health bar shrinks by 50% indicating half health, as expected, when I use currentHealth instead of 0.5f, it seems to disappear, not sure if it’s scaling down far too much and becoming invisible, or something else is going on, I should have also added that it’s an Image I’m scaling, but I think treating that as a gameObject is fine? But yeah, the only thing that happens when I use currentHealth is that the bar disappears completely instead of shrinking by 50%. regardless of what currentHealth is set to, it will disappear. as seen here https://i.gyazo.com/0490c7ad70c64aae13918f3246bd337e.mp4

EDIT: Alright I feel like an idiot… turns out while I was messing with it all in Visual Studio, I had forgotten to set the values in the inspector, and currentHealth was set to 0 in the inspector… I’ll see myself out

Sorry to waste your time, but I appreciate you trying to help :slight_smile:

2 Likes

It’s all good, I do things like that all the time and I’m an old Unity user. Glad you figured it out!

2 Likes