Making code change text on button click?

It changes the text, how can I make it only run when a button is clicked?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MoneyBtn : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        var cash = 0;
        cash = cash + 1;
        GameObject.FindWithTag("MoneyTxt").GetComponent<Text>().text = "Hello";
    }
}
  • Make it a public method
  • Rename it something else
  • In te inspector go to the buttons OnClick event
  • Click the plus
  • Drag in the GameObject with this script on it
  • Choose your method from the dropdown menu

Let me know if you have any issues with this approach.

1 Like

1.Public method Check
2.Renamed
3.
Went to onclick
4.(Script was already attached)
5.Script is attached to object already, should I move it?
6. Method doesn’t pop up…
Current Script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MoneyBtnScript : MonoBehaviour
{
    // Use this for initialization
    public void Start()
    {
        var cash = 0;
       
       
    }
    public void Click()
    {
        GameObject.FindWithTag("MoneyTxt").GetComponent<Text>().text = "Hello";
    
    }
}

The script needs to be attacfhed to your button OnClick event in the inspector then you select the click method there.

@WarmedxMints_1
The Click function isn’t showing up…

Have you saved the above script?

@WarmedxMints_1
Yup I saved.
Click function doesn’t show up…

You do need to attach the script to a gameobject and drag that gameobject into the buttons onclick event, then you can select the script and function.

If you are still stuck, pm me and I can help you over teamviwer if you like as I can’t sleep tonight anyway.

GOT IT TO WORK THANK YOU… THANKS SO MUCH!

1 Like

For clarification you need to drag and drop the GameObject into the OnClick event. Even if it’s on the same GameObject.

But sounds like you figured that out.