- Home /
How can i add a event onclick for a ui button that is child of canvas ?
On the left it's the button part in the hierarchy. In the middle the scene view. On the right the button inspector.
In the right side in the inspector i click on Add Component > New Script Gave the new script name GenerateObjectsButton.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateObjectsButton : MonoBehaviour
{
public void OnButton()
{
Debug.Log("Button was pressed!");
}
}
Then in the inspector after the script attached i click on the + When i clicked the + there is: None (Object) so i dragged to that the new created script: But as you can see in the image there is no name of the script i just dragged over there. And also when i click on No Function i have two options: No Function or MonoScript > string name
But i don't have Mono at all i'm using csharp only with visual studio.
And then when running the game the button click event is not working.
What am i missing here ? I want to make a event for the button in script.
Is this actually a clean way to set-up the buttons? Like one script for all buttons? Or should one handle each of the buttons with a separate script?
Answer by Oliver-Bogdan · May 24, 2017 at 02:13 PM
Hi Chocolade,
Underneath the "Runtime Only" where it says None(Object) you need to drag a Game Object that has the script you intend to use attached as a component, not the script itself.
So instead of dragging GenerateObjectsButton to that field, create a new GameObject in the Hierarchy, selecti it and click on Add Component. Search for GenerateObjectsButton and add it to this newly created Game Object. Then select your button in the Hierarchi and drag the newly cerated Game Object from the Hierarchy to the "None (Object)" field in the Inspector.
Tip: You can add the GenerateObjectsButton script to the Button itself and then drag himself from the hierarchy to the "None (Object)" field