Button onClick doesn't work (Instantiated button)

Hi

So my problem is: if i instantiate my button (not a prefab) and then i add code to my instantiated game object by doing:

GameObject cloneTile = Instantiate(GreenTile, ClonesParent.transform);
cloneTile.AddComponent<TileOnClick>();
cloneTile.SetActive(true);

This is the code i added:

using UnityEngine;
using UnityEngine.UI;

public class TileOnClick : MonoBehaviour
{

    private Button tile;

    public void Start()
    {

        tile = GetComponent<Button>();
        tile.interactable = true;
        tile.onClick.AddListener(TilePressed);

    }

    public void TilePressed()
    {

        Debug.Log("It works");

        Game.score += 20;

        tile.interactable = false;

    }

}

But the problem is when i click on the button nothing happens.

Can please someone help me?

Maybe this is an easy solution but i don’t know how to solve it.

Have you actually added the function to OnClick on the button

How do you mean? I added it with this line of code: tile.onClick.AddListener(TilePressed);

If you go to the Hierarchy and click on the button and scroll down there will be a box which says OnClick as shown below
7154764--856414--upload_2021-5-19_19-7-44.png

Then you gotta click the plus function and you’ll get something like this
7154764--856417--upload_2021-5-19_19-8-24.png

Then the object which contains the script you drag it to the place where it says ‘None (Object)’ and then you add the function like this
7154764--856420--upload_2021-5-19_19-9-39.png

In you case you would find the script (TileOnClick) then add the function which would be TilePressed()
Easy as that

Yes i did that with other buttons and that works, but it is an instantiated button (a clone) so you don’t see it in the hierarchy. So that is not an option

One problem could be when you instantiate a button, it might loose it’s reference for any OnClick event which depends on it, that could be the problem but nothing else is hitting my mind right now, maybe wait for someone else with more knowledge who would be willing to help you.

Yeah i also thought about that but i don’t know how to get back the reference manualy, maybe you know it? And Thanks for helping me!

I would make your instantiated button a more complete prefab that you instantiate, which should already have the script and what it needs to functions as part of it. That way you can pre-setup the On-click functions rather than needing to subscribe.

If you have dynamic methods that needs to be called, I would use C# events or any other delegate system to handle that, and your onclick event just calls that event.

Let me know if you need a more detailed explanation of setting that up.

Hi thanks for your reaction, can you explain me how you can do that with the events?

in this case you probably do not want to use Start() since you are adding your component directly anyway, you could just call an initialization function manually right after that…

im honestly not sure if Start gets executed right after AddComponent when the object is disabled…, have you tried to look if your Start function gets executed using a Debug.Log()? because i dont think it gets called there

in either way you dont have to worry about assigning methods onclick in the inspector in the editor like other answers say here,
tile.onClick.AddListener does the same but is better practice
so in any way that is not the problem

maybe try calling your initialization method right after adding the component (herefor either define a new function that does what Start is currently doing or use Start as an initialization function)

GameObject cloneTile = Instantiate(GreenTile, ClonesParent.transform);
TileOnClick tileOnClick = cloneTile.AddComponent<TileOnClick>() as TileOnClick;
tileOnClick.Start(); //or tileOnClick.Initialize() if you define it as a function called Initialize() :)
cloneTile.SetActive(true);

or alternatively do cloneTile.SetActive(true); befor adding the component

Hi

I tested youre code and i added some Debug.Log() lines in my code. And i what is see is that everything works except the method Tilepressed. The start function works but if i do tile.onClick.Addlistener(Tilepressed); that doesn’t do anything, because if i click on the button nothing happens and i don’t get some feedback from the debugger. Maybe you know how it comes.

and other buttons in the same project work? because if they dont you simply need to add an eventmanager to the scene

alternatively, last things I can imagine:

  • are there any errors in the console?
  • does GreenTile actually have a button attached to it and is this (or rather its clone) really the button you are trying to press?

Yes, all my other buttons in my project work except my cloned buttons. And yes the GreenTile has a button attached to it, i checked it with the debug logger. And there are no errors in the console. So i really don’t know what is wrong. I hope you find a solution, because i already put so much time in it and i still do not have a solution.

Here you guys have a little update of my code so you guys can maybe understand it better.

GameObject cloneTile = Instantiate(GreenTile, ClonesParent.transform);
cloneTile.SetActive(true);
TileOnClick tileOnClick = cloneTile.AddComponent<TileOnClick>() as TileOnClick;
tileOnClick.Start();
using UnityEngine;
using UnityEngine.UI;

public class TileOnClick : MonoBehaviour
{

    private Button tile;

    public void Start()
    {

        Debug.Log("Start function is executed");

        tile = gameObject.GetComponent<Button>();
      
        Debug.Log(tile);
      
        tile.interactable = true;
        tile.onClick.AddListener(TilePressed);

    }

    public void TilePressed()
    {

        Debug.Log("It works");

        Game.score += 20;

        tile.interactable = false;

    }

}

Hi

Stil don’t know what the problem is :frowning:

I hope i can find a solution quickly

Hi guys

I just found out that if i add this single line of code:

Tile.onClick.Invoke();

in my start function then it works but it’s not exactly what i want. Because when my button spawns it executes the code already in my start function. What means you get score without pressing the button. And after that if i press my button it does nothing again.

Hi

I still didn’t find any solution for my problem.
My problem is: If i press on my instantiated button the onClick function does not work i guess.

using UnityEngine;
using UnityEngine.UI;

public class TileOnClick : MonoBehaviour
{

    private Button tile;

    public void Start()
    {
       
        Debug.Log("Start function is executed");

        tile = gameObject.GetComponent<Button>();

        Debug.Log(tile);

        tile.interactable = true;
        tile.onClick.AddListener(TilePressed);

    }

    public void TilePressed()
    {
       
        tile.interactable = false;

        Debug.Log("It works");

        Game.score += 20;

    }

}

The function TilePressed don’t get executed. And i checked with a debug logger if the button is the right one. So that is not the problem. That’s why i don’t understand what is wrong, why isn’t my code getting executed?

Hopefully you guys know an answer.

Kind regards
Owen

I wonder… when you hover with the mouse over the button in the game view, does the button change color like a normal button? (interactable ui objects usually have a color pallet they use depending on their state, like on default they get a bit darker when the mouse hovers over it)

if it does not change color your scripts are not the problem, but rather your UI setup in the scene

could it be that another transparent UI object is on top of the button and catching the UI clicks?
or could it be that the button itself has a zero size in the scene?

could you show how the instantiated button looks in game and show the inspector of it in the unity scene?

Hi

It does not change its color when i hover over the button.

There is also no other transparent UI object on top of it. I don’t think the button has a zero size in the scene because i can see the button.

I will show you my game scene in a minute. By the way it is a piano tiles game so the buttons are moving, maybe that is the problem?

Hi

Here you have a video of my project. (If i click on the button it doesn’t work if it would work there would be added score)