Home > Software design >  Function not showing up in OnClick() for unity
Function not showing up in OnClick() for unity

Time:07-06

I've been trying to get a function to return a number to change the text in a button. However, I can not use the functions I wrote with OnClick(). I won't show up.

Here is the script I've been working with.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class DiceRollerBehavior : MonoBehaviour
{
    public int setRandom;
    // Start is called before the first frame update
    void Start()
    {
        setRandom = 0;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public int roll()
    {
        setRandom = Random.Range(1, 10);
        Debug.Log("Your new number is:"   setRandom.ToString());
        return setRandom;
    }



   
}

The OnClick() should put the roll function in this list but doesn't.

enter image description here

I just need to be able to trigger a function in this script using the OnClick() feature for unity.

CodePudding user response:

To be able to set a callback here it must be public void, not public int.

Also, your code will not change any text. To be able to do this, you need to assign the text label you want to change to a class field. So, it will look like this:

public class DiceRollerBehavior : MonoBehaviour
{
    [SerializeField] 
    private Text _text; // assign this field in the inspector

    public int setRandom;

    void Start()
    {
        setRandom = 0;
    }

    public void OnBtnClick()
    {
        int rollValue = roll();
        _text.text = @"{rollValue}";
    }

    int roll()
    {
        setRandom = Random.Range(1, 10);
        Debug.Log("Your new number is:"   setRandom.ToString());
        return setRandom;
    }
}

CodePudding user response:

Yes, what @Morion said, you can't return something so it must be void.

  • Related