Question by
architarorag · Jun 23, 2019 at 12:47 PM ·
c#prefabbuttonunity 2d
Button.OnClick() not working
I attached a button prefab reference to the another prefab of type sprite. And i am unable to call the onClick. Below is my Code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Dot : MonoBehaviour
{
public bool canBePressed;
public float speed;
[SerializeField] Button button;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
button.onClick.AddListener(Print);
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Perfect")
{
canBePressed = true;
//Debug.Log(canBePressed);
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Perfect")
{
canBePressed = false;
//Debug.Log(canBePressed);
}
}
void Print()
{
Debug.Log("Pressed");
}
}
Comment
Answer by tinylord202 · Jul 05, 2019 at 07:24 PM
I do not know exactly which function you are trying to call, however all the functions in this code are private, meaning that they can only be accessed by this script. If you want to call one of these functions from a different script, such as the button script, you would want to give it the public
tag. That would look like this: public void Print(){}