In this lesson, you will learn how to synchronize your game settings with UI text fields so that data flows seamlessly between the user’s keyboard and your internal game logic.
The Concept of Two-Way Binding
Two-way data binding means that if the user changes an input field, the game state updates automatically; conversely, if the game logic modifies a value (like resetting a high score or correcting a typo), the UI field updates to reflect that change instantly.
We achieve this by decoupling the data source from the UI through a validator. When a user types in a TextField, we capture the ChangeEvent<string>, process it through a validation method, and update the underlying data model.
Practical Implementation
To implement this, ensure your logic listens for input events. By using the RegisterValueChangedCallback, you create a bridge that validates input as it happens:
public class SettingsController : MonoBehaviour {
private string playerName = "Player";
public TextField nameInput;
void Start() {
// Initialize the UI with existing game data
nameInput.value = playerName;
// Register the two-way bind
nameInput.RegisterValueChangedCallback(evt => {
string newValue = evt.newValue;
// Validate: Only allow names shorter than 15 characters
if (newValue.Length <= 15) {
playerName = newValue;
} else {
// If invalid, revert the UI to the last known good state
nameInput.value = playerName;
}
});
}
}
Why Validation Matters
If you simply linked the UI to the data, a user might enter text into a field meant for numbers, potentially crashing your game logic. By placing your validation logic inside the RegisterValueChangedCallback, you act as a gatekeeper. You ensure that only "sanitized" data makes it into your game settings. If the input fails your rules (e.g., a negative number for health or an empty string for a username), the code simply refuses to update the variable and can even force the nameInput.value back to the last valid string. This creates a robust, responsive system that feels professional and prevents unexpected errors.
Key Takeaway: Two-way binding uses callback functions to bridge UI inputs and game data, ensuring the data source stays accurate while providing immediate feedback to the player.