I am working on a riddle puzzle game for my games design course in college and I am trying to figure out how to set up the primary mechanic; inputting an answer into a text bar which then opens the door to the next room.
I have created the text and script but now I want to know how to allow the player to type the answer.
I also can’t seem to be able to drag the UI objects from the hierarchy into the script fields.
RiddleUI Inspector. When I drag the appropriate object to the UI Settings fields, they won’t connect.
When I click the mouse on the black answer text button, the mouse disappears and I can’t type an answer.
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RiddleMechanic : MonoBehaviour
{
[Header(“Riddle Settings”)]
public string riddleText = “What has keys but can’t open locks?”; // The riddle
public string correctAnswer = “piano”; // The correct answer (case insensitive)
[Header("UI Elements")]
public Text riddleDisplay; // UI Text to display the riddle
public InputField answerInput; // Input field for player input
public Text feedbackDisplay; // UI Text to show feedback
void Start()
{
// Display the riddle at the start
if (riddleDisplay != null)
{
riddleDisplay.text = riddleText;
}
// Clear feedback and input
if (feedbackDisplay != null)
{
feedbackDisplay.text = "";
}
if (answerInput != null)
{
answerInput.text = "";
}
}
public void CheckAnswer()
{
// Get the player's input
string playerAnswer = answerInput.text.ToLower().Trim();
// Compare with the correct answer (case insensitive)
if (playerAnswer == correctAnswer.ToLower())
{
feedbackDisplay.text = "Correct! Well done!";
feedbackDisplay.color = Color.green;
// Trigger any further logic (e.g., open door, reward player)
OnCorrectAnswer();
}
else
{
feedbackDisplay.text = "Incorrect. Try again!";
feedbackDisplay.color = Color.red;
}
}
void OnCorrectAnswer()
{
// Placeholder for additional logic, like opening a door or progressing the story
Debug.Log("The player answered correctly!");
}
}