Hello. I’m making a small game for phone and trying to figure out how to create a button on canvas by scripting. For example: on my phone, I wait for about 3 seconds and a button pops up for me to press. Or, when I touch my phone, a button appears ony screen for me to touch. This goes on the canvas. Does anyone here know how to create a button on canvas by scripting?
Well, you can always look into creating gameObjects and calling AddComponent to them, to create buttons. However, I vastly prefer a different approach. Instead of trying to create your UI purely in code (you can do it…) have you considered creating the UI in the editor, storing the object/canvas as a prefab, and then simply instantiating the prefab when you want to show the button? The advantage is that you can lay out the UI exactly as you want, in the visual editor, rather than messing with everything purely in code.
Yes pretty much what you said right there, but how can that be done?
The general idea is that you add your Canvas to your scene, then add whatever UI components to the canvas (Buttons, Text, Images, etc), so that it looks the way you want. If you want things to be more dynamic, then you can create a script that you add to your Canvas which referenced the other components, and assign them in the inspector. For example, you might create a script like this and put it on your canvas:
public class MyDialog : MonoBehaviour {
public Text TheText;
public void SetText(string text) {
TheText.text = text;
}
}
Once your UI looks the way you want, you’d drag that whole object into your project hierarchy, into a folder called Resources. That turns it into a prefab that you can instantiate at runtime. In some other code, when you want to show the UI, you can do something like this:
var myObject = Object.Instantiate(Resources.Load("WhateverYouNamedTheObject"));
That will put the object into your scene at runtime. Use GameObject.Destroy to get rid of that object when you don’t want it to be shown anymore.
You can also look at this tutorial, where he does something similar to create a customizable modal dialog: