ui button function and onclick event
how can i give this ui button an onclick event as well as a keyboard return key ,i think i am not being clear enough ,i want my game to have the same function when i click return and when i click the button on screen ,i for keyboard return one for screen button ,basically how can i give 2 key for same function` public Transform eggpoint;
%|-1560315035_1|%
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("space") || Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
}
if(Input.GetKeyDown(KeyCode.Return))
{
Instantiate(Egg, eggpoint.position, eggpoint.rotation);
%|657980421_16|%
%|69678579_17|% %|1246395602_18|% }`
as you can see i have instantiate function above and now i have the return key from keyboard to execute this fucntion i want my ui button to have the same function how can i achieve this.
Answer by Mmmpies · Jun 09, 2016 at 08:51 AM
Just create a public function that does the same...
public void LayEgg()
{
Instantiate(Egg, eggpoint.position, eggpoint.rotation);
}
Then on the button click + in the OnClick, drag the object that your script is on to the slot that appears and select YourScriptName -> LayEgg from the drop down.
It makes sense to call that function from you key input as well so any changes you make only need to be made i one location.
but the problem is as you can i have to function over there getmousebuttondown which make my player jump and now when i press the lay egg button its laying an egg and jumping togather how can i fix this
$$anonymous$$ixing Get$$anonymous$$ousebuttonDown and UI input with the mouse is going to cause issues. You'd be better of creating a public void Jump() function and have a button take up the rest of the screen in the UI that calls that function via OnClick as above.
You don't have to have an image or text on your button so it can be completely transparent. Or you can put a CanvasGroup on it and set the Alpha to zero (again it makes it invisible).
Then if your space key is pressed or that OnClick on the big invisible button happens call Jump() and that adds your force.
0 Answer by haam · 1 sec ago thank you soo much ,you have been very help full