I'm new to Unity and C# script. I am facing a problem that I can't figure out so please anyone can guide what's going on in this scene.
So, the thing is that there's a HP bar (green bar) to show the health of pokemon in This one but when I enter the play mode , the bar becomes invisible and I'm not able to figure out what's causing this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPBar : MonoBehaviour
{
[SerializeField] GameObject health;
public void SetHP(float hpNormalized)
{
health.transform.localScale = new Vector3(hpNormalized, 1f);
}
}
Above is the script used for HP bar.
You are setting new Vector3 - a 3-dimensional vector but you only give it 2 values. What is likely happening is that new Vector3(hpNormalized, 1f) is translating into new Vector3(hpNormalized, 1f, 0f) and your game object has a scale of 0 in one dimension, and that results in weird behavior.
Try setting all 3 dimensions like this:
new Vector3(hpNormalized, 1f, 1f);
EDIT:
For the constructor of public Vector3(float x, float y) the documentation says
Creates a new vector with given x, y components and sets z to zero.
Source: https://docs.unity3d.com/ScriptReference/Vector3-ctor.html
So z dimension is set to zero in your case and I suspect that is the source of the health-bar disappearing.
Otherwise, I recommend using Debug.Log("Health set to"+hpNormalized+ " and scale of the object is"+health.transform.localScale); in the function to see what is going on.
We have no idea, nor you gave us about your project but it seems like you don't even know your values. You can call debug when calling methods and learn value of variables. Also if you want to move your health only between spesific values you can use Mathf.Clamp. This method clamp given variable to given range.
Also your approach is wrong at start. You shouldn't use transfrom.localscale for substract your healthbar. You can set health bar image type to Filled and if you want horizontal or vertical set it too in Unity Inspector. Then you call from code like this:
healthBarImage.fillAmount = hpNormalized; It is simple as that