简体   繁体   中英

Unity | C# How to make customized number keypad

Im going to make a custom number keypad in unity. I'm wondering how can i make it by simple way with much short and clean code. Below code is just for explaining my idea.

var str=""; //This is the result string that i have to send to host

var key0 = document.getElementById('key0').value;
var key1 = document.getElementById('key1').value;
var key2 = document.getElementById('key2').value;
var key3 = document.getElementById('key3').value;
... so on

key0.onclick= function() { //button click events
    str += "0";
}

key1.onclick= function() {
    str += "1";
}

key2.onclick= function() {
    str += "2";
}

key3.onclick= function() {
    str += "2";
}
... so on

function getStr() {
    return str;
}

I know this code is rubbish but i'm just thinking like this way; event process. But if i make the each buttons as gameobjects then, they all have the colliders right? and the colliders aware of when they touched. so i also thought in this way.

var array = [key0, key1, key2, key3, ...]; //The list consisted of the gameobjects

foreach (array as arr) {
    arr.collider.onTouched = function() { //Assign the events to each gameobject's collider
        str += arr.getNumber(); // custom function 'getNumber' to attach the number to string
    }
}

I'm just drawing the code. oh and the important thing is returning result string when i push the enter key. so i'm thinking how can i make the get;set function in C# code in unity. Do i manage this works in onUpdate function?

Please let me know what is the best idea to handle this process.Thank you.

IMHO the best way is to use the Canvas API with a layout manager to automatically size your buttons. And have all the buttons fire an event to the same receiver method and pass the key value. You should be able to get away with only a few lines of code.

I built on for VR, but the approach is identical:

http://talesfromtherift.com/vr-canvas-keyboard/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM