-2
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;

public class SecurityKeypadKeys : MonoBehaviour
{
    public TextMesh text;

    private int counter = 0;

    private void Start()
    {
        
    }

    private void OnMouseDown()
    {
        string[] digits = Regex.Split(transform.name, @"\D+");
        foreach (string value in digits)
        {
            int number;
            if (int.TryParse(value, out number))
            {
                counter++;
                if (counter < 8)
                {
                    text.text += number.ToString();
                }
            }
        }
    }
}

I used a break point and found that if I press on a button of number 1 and press on it 8 times then it will stop writing the next number 1 to the text but then if I click on the number 2 it will write to the text another 8 times of the 2 number.

but I want that the player will be able to type only 8 numbers no matter if it's 12345678 or 88888888 or 0000000 or 56498611 and then if the player keep typing it will not add anymore numbers to the text.

The problem is that the script is attached to 10 cubes act like buttons. so each time I click on another cube(button) it's reseting the counter to 0.

user1196715
  • 583
  • 2
  • 6
  • 14
  • 4
    You're using an instance field when you probably mean to use a static one. Make `counter` a `static` field by changing it to `private static int counter = 0;`. See here for more information: [What does \`static\` mean in c#?](https://stackoverflow.com/q/9410688/1092820) – Ruzihm Sep 23 '20 at 21:10

1 Answers1

1

Based on your question, I'm assuming you have a different instance of SecurityKeypadKeys for each button. Each instance will have its own counter, initialized at 0, but write out to the same text.text. This means each number will be enabled to be pressed 8 times.

To correct this, you have two options:

  1. Add static keyword to counter declaration. private static int counter = 0; This will enable only 8 numbers to be entered, ever, unless you add another method to your class to reset counter.
  2. Share the same instance of your class between all buttons rather than creating a new instance for each button. var keypad = new SecurityKeypadKeys(); This method enables you to create a new instance each time you need 8 numbers without requiring a reset method.

On another note, I would recommend moving the counter increment into the if statement. Otherwise, if the function is called enough times, the int could overload back to -2147483648, re-enabling more numbers to be added.

if (counter < 8)
{
    counter++;
    text.text += number.ToString();
}
Adam
  • 562
  • 2
  • 15