Button to trigger progress bar?

I am trying to make it so when you click a button, it starts a progress bar that increments from 0% to 100% every second with a predefined value (5% per interval).

	public UnityEngine.UI.Slider barvalue ;
	private float maxslidervalue=100;
	public int jump;    	   	  
	
	//this makes the progress bar load in 1second intervals with a value of "jump"
	IEnumerator Start() {
		for(int val = 0; val <= maxslidervalue; val+=jump)
		{
			barvalue.value=val;
			print(barvalue.value);
			yield return new WaitForSeconds(1);

		}

	}

I am using a slider as the progress bar. I want it so when i click a button, the slider begins to increment until it hits 100%. I have figured out how to make it increment when the game starts, but i want to be able to have it not play until the button is clicked.

Hi there, you can use the new UI’s pointer click event to get your button to trigger the progress bar code.

Create a script that inherits the IPointerClickHandler interface, then create the OnPointerClick method to trigger the progress bar code. Then attach the script to the button element in your UI canvas.

Whenever you click your button, the OnPointerClick method will be called and will trigger your progress bar code.

Here’s a bit sample code to help explain.

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ButtonTriggerScript : MonoBehaviour, IPointerClickHandler
{
	public void OnPointerClick(PointerEventData eventData)
	{
		// Your code to trigger the progress bar code
	}
}

Hope that helps.

Edit the script to:

   public UnityEngine.UI.Slider barvalue ;
     private float maxslidervalue=100;
     public int jump;                 
     
     //this makes the progress bar load in 1second intervals with a value of "jump"
     IEnumerator IncreaseSliderValue()  //Instead of incrementing value in start function. Put your code into a coroutine.
{
         for(int val = 0; val <= maxslidervalue; val+=jump)
         {
             barvalue.value=val;
             print(barvalue.value);
             yield return new WaitForSeconds(1);
 
         }

//Creat a new method which will call above coroutine when the Button is clicked.
public void StartSLider()
{
  StartCoroutine(IncreaseSliderValue());
}
 
     }

Then follow the following steps to call the coroutine when the button is pressed.

  1. Click the ‘+’ icon on the “OnClick functions list” on the Button.
  2. Drag and drop the object on which script is attached to the" Object Field" in the Functions List.
  3. Then call the Function “StartSLider” from the functions list on the right side of the Object field.