Unity3D with C# - Using Input field to answer question [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm creating a unity quiz game using input fields.
How can I use text from an input field to match with an answer in a c# script?

hijinxbassist's example is good, however, i made an example that includes the other parts as well, like adding event listeners and declaring the fields.
Checking for single correct answer:
public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string a1_right_answer = "foo"; // make it public and edit the answer in editor if you like
private void Awake()
{
// add event listener when button for submitting answer is clicked
submitAnswerBtn.onClick.AddListener(() => {
// validate the answer
if(answerInput.text.ToLower() == a1_right_answer) {
// success
Debug.Log("Correct");
} else {
Debug.Error("Wrong");
}
});
Checking for multiple correct answers:
public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string[] a1_right_answers = { "foo", "bar", "foo1", "bar1" }; // multiple right answers
private bool is_right_answer = false; // default value
private void Awake()
{
// add event listener when button for submitting answer is clicked
submitAnswerBtn.onClick.AddListener(() => {
// loop through all the right answers
for (int i = 0; i < a1_right_answers.Length; i++)
{
// validate the answer
if(answerInput.text.ToLower() == a1_right_answers[i]) {
// success
is_right_answer = true;
break;
}
}
// check if the user got the right or wrong answer
if(is_right_answer) {
Debug.Log("Correct");
is_right_answer = false; // reset for next guess
}
else {
Debug.Log("Wrong");
// no need to reset 'is_right_answer' since its value is already default
}
});

I am not sure which part of this problem you are stuck on, but I will attempt to answer.
I think the most important thing when comparing an input field with a stored answer is to make sure the comparison is case insensitive. You can do this by converting both texts to either lowercase or uppercase.
var usersAnswer = answerInputField.text.ToLower();
var actualAnswer = "Some Answer".ToLower();
if (usersAnswer == actualAnswer)
{
Debug.Log("You got it right!");
}

Related

Cannot store value in inputfield to check if it is correct. unity

Hey guys (sorry to ask a question again so soon).
I was trying to create an input field, and whenever the player types in something correct it would register as being correct. My tactic for this was to create a string (for the text that displays a question or dialogue), and then create another string with the answers. If the specific answer 'point' (in the range e.g. '1', '2', '3' and the user wrote '3' when it was the 3rd point) was correct, as in the example, then it would go green and move on.
Like with using buttons, I planned on making an int variable and having that reset when something went in. Upon trying this though I found many problems. If I tried to make it with another string attached to another object and verified if the two were equal, the second I wrote the answer (without pressing enter), it would register instead of afterwards. I presume this is because the console is not registering it after the click.
So I tried experimenting with another text box. The textbox would have the answer as well, and if the text that the user wrote in the inputfield matched that it would go on. The problem with this is that apparently you cannot refer to an inputfield and a text in the same statement. So this is where, 4 hours later, I come to you guys. Is there a way in which I can store the value of the inputfield and check it with the text of something else to see if it was correct?
my code: hello and by were the two text UIs I tried to use in order to help with the verification process, although I presume that if you did this properly there is a better way to do it. This is the controller, that is connected to an empty game object with the inputfield connected to the inputfield (within the object).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
List<string> answers = new List<string>() { "1", "1", "1", "1", "1" };
public static string answer;
public Text hello;
public Text by;
// Allows you to attach the inputfield to the game controller, saving code
[SerializeField]
// declare variable input
private InputField input;
void Start()
{
hello = GameObject.Find("Hi").GetComponent<Text>();
by = GameObject.Find("Bye").GetComponent<Text>();
}
// registers what the user writes
public void getInput(string guess)
{
// Declares the value in the console
input.text = "";
Debug.Log("Hi");
}
This is the code for the main text with the dialogue:
public class inputTextControl : MonoBehaviour {
List<string> questions = new List<string>() { "This is the first question", "second", "third", "fourth", "fifth" };
public static string input = "n";
public static int randInput = -1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (randInput == -1)
{
// The range of questions that can be asked (all the strings need to match this range for the questions in order to be functional without an exception error
randInput = Random.Range(0, 5);
}
if (randInput > -1)
{
GetComponent<Text>().text = questions[randInput];
}
}
}
I apologise if I am not being that clear..it's just really hard for me to explain the whole situation, apart from the fact that instead of the inputfield working like a 'type in the right answer' and if you are wrong you lose, it is just not working at all.
Have a good weekend!
}
First of all, GetComponent<>() is an expensive operation and you shouldn't ever need to call it in Update() function. Declare it in the Start() function (same way as 'hello' or 'by')
Second, I suggest you to drag all public variables in editor so you won't even need to use GetComponent in the start function (it will make your scripts more clean).
Thirdly, you don't need to explicitly get Text component to get the value of the input field. inputF.text does the job. See example at the end for more information.
Finally, your question is:
Q:Is there a way in which I can store the value of the inputfield and check it with the text of something else to see if it was correct?
A: Yes. Here is a quick example.
public InputField input;
void Start(){
// Following line can be dismissed if we drag our input field in editor
input = GameObject.Find("AnswerInputFieldName").GetComponent<InputField>();
}
void CheckAnswer(){
string correct = "correctAnswer";
string userAnswer = input.text;
if(correct.compare(userAnswer) == 0)
Debug.Log("That's correct!");
}
Call CheckAnswer() function whenever you feel you need it.
P.S. If you want to instantly check if answer is correct you don't need to do call CheckAnswer() in Update because it is called each frame for no reason. You need to call it whenever input field value has changed. Google more about event listeners.

How to use ZK4500 Fingerprint Scanner SDK in C# Project [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am developing a project in C#, for which I want to login/authenticate a user using their fingerprint.
I bought a ZK4500 Fingerprint scanner and got its SDK from http://www.zkteco.com/product/ZK4500_238.html. The SDK is in C++.
So How can I integrate this SDK with my C# project to perform the desired functionality?
You need to add reference to ZKFPEngXControl that will appear under COM Type Libraries. After that you can use the ZKFPEngX Class to do whatever you require.
using ZKFPEngXControl;
and then
ZKFPEngX fp = new ZKFPEngX();
fp.SensorIndex = 0;
fp.InitEngine(); // Do validation as well as it returns an integer (0 for success, else error code 1-3)
//subscribe to event for getting when user places his/her finger
fp.OnImageReceived += new IZKFPEngXEvents_OnImageReceivedEventHandler(fp_OnImageReceived);
You can write your own method fp_OnImageReceived to handle the event. for example you can write this in that method;
object imgdata = new object();
bool b = fp.GetFingerImage(ref imgdata);
Where imgdata is an array of bytes.You can also use other methods in ZKFPEngX, to achieve your goals. Remember to close the engine when form closes.
fp.EndEngine();
You can store a fingerprint under OnEnroll(bool ActionResult, object ATemplate) Event.This event will be called when BeginEnroll() has been executed.
//Add an event handler on OnEnroll Event
ZKFPEngX x = new ZKFPEngX();
x.OnEnroll += X_OnEnroll;
private void X_OnEnroll(bool ActionResult, object ATemplate)
{
if (ActionResult)
{
if (x.LastQuality >= 80) //to ensure the fingerprint quality
{
string regTemplate = x.GetTemplateAsStringEx("9");
File.WriteAllText(Application.StartupPath + "\\fingerprint.txt", regTemplate);
}
else
{
//Quality is too low
}
}
else
{
//Register Failed
}
}
You can try to verify the fingerprints under OnCapture(bool ActionResult, object ATemplate)event. This event will be called when a finger is put on the scanner.
Add an event handler on OnCapture Event:
x.OnCapture += X_OnCapture;
Verify the fingerprints when the event has been called (a finger is put on the scanner):
private void X_OnCapture(bool ActionResult, object ATemplate)
{
if (ActionResult) //if fingerprint is captured successfully
{
bool ARegFeatureChanged = true;
string regTemplate = File.ReadAllText(Application.StartupPath + "\\fingerprint.txt");
string verTemplate = x.GetTemplateAsString();
bool result = x.VerFingerFromStr(regTemplate , verTemplate, false, ARegFeatureChanged);
if (result)
{
//matched
}
else
{
//not matched
}
}
else
{
//failed to capture a valid fingerprint
}
}

C# TextBox that allows a maximum of one dot [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I make a TextBox in C# to allow a maximum of one . (dot)?
Thus, abcdef and abc.def would be valid inputs whereas ab.cd.ef wouldn't.
By allow I mean that the user should not be able to enter a dot if there is already one in the text field.
Java has DocumentFilters for that purpose, is there something similar in C#?
I guess this is for validating user inputs. You should create a button and tell the user when he is done, press it so that you can check whether there is only one . in the string.
Assumptions:
Let your text box be called tb. Let your button's Click event handler be BtnOnClick.
Now we can start to write code. First create the handler:
private void BtnOnClick (object sender, EventArgs e) {
}
In the handler, you need to loop through the string and check each character. You can use a foreach for this:
int dotCount = 0;
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
//code to handle invalid input
return;
if (s.EndsWith(".")) //ends with .
//code to handle invalid input
return;
foreach (char c in s) {
if (c == '.') {
dotCount++;
}
if (dotCount >= 2) { //more than two .
//code to handle invalid input
return;
}
}
// if input is valid, this will execute
Alternatively, you can use a query expression. But I think you are unlikely to know what that is.
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
//code to handle invalid input
return;
if (s.EndsWith(".")) //ends with .
//code to handle invalid input
return;
var query = from character in s
where character == '.'
select character;
if (query.Count() > 1) {
//code to handle invalid input
return;
}
// if input is valid, this will execute

Matching brackets and indentation in RichTextBox using C#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to make a Code Editing control that can format text somewhat like Visual Studio,till now i have implemented syntax highlighting and autocompletion but i want to format text in nested curly braces.For example:Consider a for loop,
for(int i=0;i<=10;i++)
{
Function_One(); //This should be a tab away from first brace
Function_Two(); //So with this
if(a==b) //So with this
{ //This should be four tabs away from first brace
MessageBox.Show("Some text");//This should be six tabs away from first brace
} //This should be four tabs away from first brace
}
now what i want is that this should look something like this,
for(int i=0;i<=10;i++)
{
Function_One();
Function_Two();
if(a==b)
{
MessageBox.Show("Some text");
}
}
I have already tried Regular Expressions but at some point they fail to match,so i tried to match it with code but code cannot match very deeply nested code or is very hard to implement
,so is there any way to achieve this,and one more thing i am doing all this in Winforms control RichTextBox using C#.
This is by no means a simple feat, I am unaware of any tools or plugins that you would be able to take advantage of, my only recommendation is to research Monodevelop's implementation of this.
See MonoDevelop's github for details.
I think the best way to implement this would be to create some global variables for your form:
private int _nestedBracketCount = 0;
private const string TabString = " ";
private const int TabSpaces = 4;
And then handle all of it in a KeyPressed event handler for the rich text box:
private void richTextBox1_OnKeyPress(object sender, KeyPressEventArgs e) {
var currentLength = richTextBox1.Text.Length;
if (e.KeyChar == '{') {
// need to increment bracket counter
_nestedBracketCount++;
} else if (e.KeyChar == '}') {
// remove last #(TabSpaces) characters from the richtextbox
richTextBox1.Text.Remove(currentLength - TabSpaces);
_nestedBracketCount--;
richTextBox1.AppendText("}");
e.Handled = true;
} else if (e.KeyChar == (char)13) {
// append newline and correct number of tabs.
var formattedSpaces = string.Empty;
for (var i = 0; i < _nestedBracketCount; i++)
formattedSpaces += TabString;
richTextBox1.AppendText("\n" + formattedSpaces);
e.Handled = true;
}
}
I think this should provide you with a halfway decent starting point.

Updating ListBox with new list values through using a method

I am trying to prompt a method to start upon a button click. The problem is that they are over two different classes and it is difficult to share all the relevant values over both the form and the class. I was wondering if it was possible to change a listbox's values through pressing a button on a form. At the moment mine is just staying on the first list.
My first class is the form. This is holding the physical changing of the data.
if (teach.Alphabet == "B")
{
lbl1.Text = "What is the english word for White?";
lstNum.Items.AddRange(number1);
txtQuestion.Text = String.Join(Environment.NewLine, english1);
}
It calls the method teach.CallRandomQuestion() to get the alphabet letter (it is a way it chooses which question to put onto the system). This is done by the following code:
public void CallRandomQuestion()
{
if (score == 1)
{
Alphabet = "A";
Answer = "1";
}
if (score == 2)
{
Alphabet = "B";
Answer = "3";
}
}
Finally I have a public int score which starts at 1 and adds one every time the correct answer is given. So if the correct answer is given, the second question B should show in the listbox, but doesn't.
public void Showinlistbox()
{
// Add a listBox named listBox1
// Add Score
score++;
CallRandomQuestion();
//if you want mutual-exclusion lock add lock (listBox1)
listBox1.Items.Add(Alphabet);
}

Categories

Resources