- Home /
Multiple button name in a row?
I need to make a key code from my Debug.Log The main problem is that its works correctly with simple gameobjects (Shows 1234 together and in a row), but not the buttons, you can see that i tried to call EventSystem and its just not work and shows Debug.Log(Object) in the Console. Maybe some another way may help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
public class CodePanel : MonoBehaviour {
public static string correctCode = "796";
public static string playerCode = "";
void Start()
{
}
void FixedUpdate () {
Debug.Log (playerCode);
}
void OnMouseUp()
{
playerCode += EventSystem.current.currentSelectedGameObject.name;
}
}
Answer by lassade · Jan 23, 2018 at 03:05 AM
Hey Rambo instead of using OnMouseUp try using OnPointerClick it is a function from the IPointerClickHandler interface, Here is an example of how to use it. Since you have this script added in every single button of your keypad you can just do playerCode += name;
this will get the name of the button the player just clicked in.
I just notice in the image that you have this code added in every button (I'm right?) you will be better by creating a single script without any static variables like so:
using UnityEngine.UI;
// Place this in the Canvas or other object once
public class CodePanel : MonoBehaviour {
public string correctCode = "796";
public string playerCode = "";
// Drag every number key to this array in the editor (does not need to be in order)
public Button[] numberButtons;
void Start()
{
foreach (var button in numberButtons)
{
// For each one of my buttons add a event for when it's pressed so I can add the right button
button.onClick.AddListener(() => WhenNumberKeyGetsClicked(button.name));
}
}
void WhenNumberKeyGetsClicked(string number)
{
playerCode += number;
Debug.Log (playerCode);
}
}
The main reason for doing this way is that you now can have multiple keypads across your game that can have different correctCode(s) that you can edit very easily.