Buttons are often used in Cocos Creator game development, especially in the case of a large number of buttons. At this time, it is more versatile to use an array to manage these buttons. I roughly walked through the official example, and it seems that I did not find this small content (or there is, but I did not find it), so I added this content as follows.
Typical problem preview
The interface shown in the figure below (the picture is a screenshot of a small example of mine, which is not yet mature, and will be released after I feel that I can share it later):
Notice that, in the hierarchy management, I used a The parent node controlRoot contains two button nodes (in reality, there may be many buttons).
Create an operation script component
The code (zxzLevelSelect.js) is as follows:
cc.Class({
extends: cc.Component,
properties: {
but: {
default: [],
type: [cc.Button], // type is also written as an array to improve code readability< br /> }
},
touchButton(event, customEventData){
var node = event.target;
switch(node.name){
case'btnStart':
{
cc.director.loadScene('zxzBallScene');
}
break;
case'btnBack':
{
cc.director.loadScene('zxzWelcome');
}
break;
}
// switch(customEventData) {
// // switch(button.name){
// case '0':
// {
// cc.director.loadScene('zxzBallScene') ;
// }
// break;
// case '1':
// {
// cc.director.loadScene('zxzWelcome');
// }
// break;
// }
}
});
Please pay attention to the following points in the code:
1, the function touchButton(event, customEventData) is the handler that we define the button Function;
2, in this function, we can at least use the two methods shown above to distinguish each button, the first method is event.target.name (event.target corresponds to the corresponding button component), and The name value is the name of the button we see in the hierarchy manager; the second way is with the help of the second parameter customEventData in the handler function. In the scene design, I set the customEventData value of the two buttons to 0 and 1 (Of course, you can set it to a more intuitive name such as a string according to your needs). Note that comments are used in the second half of the code, which is the second way to distinguish buttons.
Associate script components and set button handler functions
The above small scene file is named zxzLevelSelection.fire, and I associate the above script zxzLevelSelect.js on the top Canvas node of the hierarchy management. , And bind the above two button components, as shown below:
Then, select the two button components in turn, and associate the corresponding handler function with each, as shown in the following figure (only one is sufficient):
Please note: no matter how many buttons, they must be associated according to the above ideas Just work.
Summary
This article gives a supplement to the use of the button component array in Cocos Creator programming. Please remind you of the shortcomings, thank you very much.