Image.fill amount not working as I want.

Hey guys,
trying to make a power bar that increases fill amount as I hold down a button. I can get the bar to when i set it to one but it does not want to update from the variable on the other script. Here is a sample of what I am doing.

This is my scripts that holds the image and controls the fillamount that is set by the amount of power applies.

using UnityEngine.UI;
using UnityEngine;

public class PowerBar : MonoBehaviour
{
    public Image powerbar;
    public BallLaunch ballLaunch;
   

 

    void Update()
    {
        powerbarcheck();

    }

    void powerbarcheck()
    {
        powerbar.fillAmount = ballLaunch.power/1500f;
    }
}

This scripts is responsible for launching the ball and increasing and decreasing power depending on how much is gained or lost.

    public float power = 0f;
    private float increase = 500f;
    public bool maxPower = false;
    public bool minPower = true;


void Update()
    {
        Launch();
        PowerCheck();

    }

    void Launch()
    {


        if (Input.GetButton("Fire1") && ballInPlay == false && minPower == true)
        {
            power += increase * Time.deltaTime;
         

        }

        if (Input.GetButton("Fire1") && ballInPlay == false && maxPower == true)
        {
            power -= increase * Time.deltaTime;
         

   void PowerCheck()
    {

        if (power <= 0)
        {
            maxPower = false;
            minPower = true;
        }
        if (power >= 1500f)
        {
            maxPower = true;
            minPower = false;
        }
    }

I think that everything relevant…Thanks in advance!

if you Debug.Log the value of ballLaunch.power in the first script, is it giving you the right number?

Instead of using 2 separate “if” statements, use an else if:

if (Input.GetButton("Fire1") && ballInPlay == false && minPower == true)
{
    power += increase * Time.deltaTime;
}
else if (Input.GetButton("Fire1") && ballInPlay == false && maxPower == true)
{
    power -= increase * Time.deltaTime;
}

EDIT: Ignore this.

1 Like

I used a debug.log and found that it was not giving me the right number, it is just returning as 0. I think I need to get the variable from another script using something like

void Start()
    {
        thepower = GameObject.FindWithTag("Ball").GetComponent<BallLaunch>().power;
    }

but that did not work for me, possibly because the BallLaunch script I am trying to access is on an instantiated object?

I ended up finding a work around and made power static but I’ve read this is usually not the best way to do things. Let me know if there is a better way. Thanks!

Well, static may have worked if you didn’t have a proper reference to the script (and by extension its variable).
There’s nothing wrong with static variables, but in your case it would maybe be good to know/learn why what you did didn’t work the first time, and how it could have worked.