Update readme docs for our systems

This commit is contained in:
Michal Adam Pikulski
2025-10-21 12:37:53 +02:00
parent 2fb77e1040
commit 7096dffb54
4 changed files with 637 additions and 659 deletions

View File

@@ -1,398 +1,186 @@
# Apple Hills Settings System
![Settings System Overview](media/settings_system_overview.png)
Centralized, designer-friendly configuration using `ScriptableObject` assets, with runtime access via `SettingsProvider` (Addressables-backed) and editor/live-preview access via `SettingsAccess`. This page follows the style of other updated docs (TOC, inline code, code-first usage, case studies).
## Overview
## Table of Contents
- [What This Solves](#what-this-solves)
- [Architecture at a Glance](#architecture-at-a-glance)
- [Quick Start (Code-First)](#quick-start-code-first)
- [Get Settings at Runtime](#get-settings-at-runtime)
- [Use Editor-Time Values via `SettingsAccess`](#use-editor-time-values-via-settingsaccess)
- [Access Example Fields](#access-example-fields)
- [Authoring in the Editor](#authoring-in-the-editor)
- [Creating/Editing Settings Assets](#creatingediting-settings-assets)
- [Addressables Keys & Loading](#addressables-keys--loading)
- [Available Settings Types](#available-settings-types)
- [Case Studies](#case-studies)
- [Tune Interaction Distances](#tune-interaction-distances)
- [Follower Handling & Movement](#follower-handling--movement)
- [Diving Minigame Tuning](#diving-minigame-tuning)
- [Troubleshooting / FAQ](#troubleshooting--faq)
- [Paths & Namespaces](#paths--namespaces)
- [Change Log](#change-log)
The Apple Hills settings system consists of two main categories:
- **Game Settings**: Designed for gameplay parameters and configuration values that affect the player experience
- **Developer Settings**: Technical settings used for development, debugging, and behind-the-scenes functionality that we don't want Angry Argentinians to accidentaly overwrite
## What This Solves
- Consistent, centralized configuration across gameplay systems.
- Safe, designer-editable `ScriptableObject` assets with validation (`OnValidate`).
- Simple, Addressables-based runtime loading and caching via `SettingsProvider`.
- Editor-time overrides and scene gizmo feedback via `SettingsAccess` helpers.
The settings framework uses ScriptableObjects to store configuration data, making it easy to modify values in the editor and reference them in code. Settings are organized into logical groups and can be accessed through custom editor windows or directly in code.
## Architecture at a Glance
- Base: `BaseSettings` (`ScriptableObject`) — common parent for all settings. Implements optional `OnValidate()`.
- Access (runtime): `SettingsProvider` (singleton `MonoBehaviour`) — loads assets synchronously via Addressables at keys `Settings/<TypeName>` and caches them.
- Access (editor/dev): `SettingsAccess` (static) — editor-friendly shim for reading selected values even when not in Play Mode, falling back to `GameManager` at runtime.
- Contracts: `SettingsInterfaces` (`IPlayerFollowerSettings`, `IInteractionSettings`, `IDivingMinigameSettings`) used by systems to remain decoupled from concrete assets.
- Editor tooling: `AppleHills/Settings Editor` — finds/creates assets under `Assets/Settings` and provides a tabbed UI.
Benefits of this approach include:
- Central location for all configuration values
- Type-safe access to settings in code
- Custom inspector support for better editing experience
- Settings validation through the OnValidate method
- Support for both runtime and development-time settings
## Quick Start
### How to Access and Edit Settings in Editor
#### Game Settings
1. Open the Game Settings Editor window through the menu: **AppleHills → Game Settings Editor**
2. Navigate through the tabs to find the settings group you want to edit
3. Modify values directly in the inspector
4. Click "Save All" to apply changes
![Game Settings Editor](media/game_settings_editor.png)
#### Developer Settings
1. Open the Developer Settings Editor window through the menu: **AppleHills → Developer Settings Editor**
2. Select the appropriate tab (Diving, Debug, etc.)
3. Modify values directly in the inspector
4. Click "Save All" to apply changes
![Developer Settings Editor](media/developer_settings_editor.png)
### How to Access Settings from Code
#### Game Settings
## Quick Start (Code-First)
### Get Settings at Runtime
```csharp
// Get player follower settings
var playerSettings = SettingsProvider.Instance.GetSettings<PlayerFollowerSettings>();
float moveSpeed = playerSettings.MoveSpeed;
// Get interaction settings
var interactionSettings = SettingsProvider.Instance.GetSettings<InteractionSettings>();
float stopDistance = interactionSettings.PlayerStopDistance;
```
#### Developer Settings
```csharp
// Get diving developer settings
var divingDevSettings = DeveloperSettingsProvider.Instance.GetSettings<DivingDeveloperSettings>();
bool useObjectPooling = divingDevSettings.BubbleUseObjectPooling;
// Get debug settings
var debugSettings = DeveloperSettingsProvider.Instance.GetSettings<DebugSettings>();
if (debugSettings.GodMode) {
// Apply god mode functionality
}
```
### Creating Your Own Settings
#### 1. Create the Settings Class
```csharp
// For gameplay settings
[CreateAssetMenu(fileName = "MyGameplaySettings", menuName = "AppleHills/Settings/My Gameplay Settings", order = 1)]
public class MyGameplaySettings : BaseSettings
{
[Header("Movement")]
[Tooltip("Base movement speed")]
[SerializeField] private float baseSpeed = 5f;
public float BaseSpeed => baseSpeed;
public override void OnValidate()
{
// Validation logic here
}
}
// For developer settings
[CreateAssetMenu(fileName = "MyDeveloperSettings", menuName = "AppleHills/Developer Settings/My Feature", order = 3)]
public class MyDeveloperSettings : BaseDeveloperSettings
{
[Header("Configuration")]
[Tooltip("Enable advanced features")]
[SerializeField] private bool enableAdvancedFeatures = false;
public bool EnableAdvancedFeatures => enableAdvancedFeatures;
}
```
#### 2. Create the Settings Asset
- Right-click in the Project window
- Select Create → AppleHills → Settings → My Gameplay Settings (or Developer Settings → My Feature)
- Save the asset in the appropriate location (Assets/Settings or Assets/Settings/Developer)
![Create Settings Asset](media/create_settings_asset.png)
#### 3. Register in the Editor Window (for custom tabs)
See the detailed workflow section for a complete guide.
## Architecture Breakdown
The settings system consists of several key components:
### Base Classes
- **BaseSettings**: The root class for all game settings ScriptableObjects
- **BaseDeveloperSettings**: The root class for all developer settings ScriptableObjects
![Settings Class Hierarchy](media/settings_class_hierarchy.png)
### Provider Classes
- **SettingsProvider**: Singleton for accessing game settings
- **DeveloperSettingsProvider**: Singleton for accessing developer settings
Both providers handle loading settings from Addressables or Resources, caching them for efficient access, and providing type-safe retrieval methods.
### Editor Windows
- **GameSettingsEditorWindow**: Custom editor window for editing game settings
- **DeveloperSettingsEditorWindow**: Custom editor window for editing developer settings
These windows provide a clean interface for browsing and modifying settings, organized into tabs by category.
### Settings Storage
Settings assets are stored in:
- **Assets/Settings**: For game settings
- **Assets/Settings/Developer**: For developer settings
These assets are loaded via Addressables during runtime, with a fallback to Resources if needed.
## Detailed Workflows
### Creating a New Settings Class
1. **Determine the Type of Settings**
- Game settings: Inherit from `BaseSettings`
- Developer settings: Inherit from `BaseDeveloperSettings`
2. **Create the Class File**
- Create a new script in the `Assets/Scripts/Core/Settings` folder
- Name it appropriately, e.g., `MyFeatureSettings.cs` or `MyFeatureDeveloperSettings.cs`
3. **Implement the Settings Class**
Here's an example of how to implement a settings class with proper structure:
```csharp
using UnityEngine;
using AppleHills.Core.Settings;
namespace AppleHills.Core.Settings
{
[CreateAssetMenu(fileName = "MyFeatureSettings", menuName = "AppleHills/Settings/My Feature", order = 1)]
public class MyFeatureSettings : BaseSettings
{
[Header("Main Configuration")]
[Tooltip("Description of this setting")]
[SerializeField] private float mainValue = 10f;
[Tooltip("Another important setting")]
[Range(0, 100)]
[SerializeField] private int secondaryValue = 50;
[Header("Advanced Settings")]
[Tooltip("Enable special features")]
[SerializeField] private bool enableSpecialFeatures = false;
// Public property accessors (follow this pattern)
public float MainValue => mainValue;
public int SecondaryValue => secondaryValue;
public bool EnableSpecialFeatures => enableSpecialFeatures;
// Optional validation
public override void OnValidate()
{
// Ensure values are within acceptable ranges
mainValue = Mathf.Max(0, mainValue);
}
}
}
var playerFollower = SettingsProvider.Instance.GetSettings<PlayerFollowerSettings>();
float speed = playerFollower.MoveSpeed;
```
The key elements to include are:
- Proper attribute decorations (`Header`, `Tooltip`, `Range`, etc.)
- Serialized private fields with default values
- Public property accessors using the expression-bodied syntax
- Validation in the OnValidate method when needed
### Creating Settings Assets
1. **Create the Asset**
- Right-click in the Project window
- Navigate to Create → AppleHills → Settings → My Feature (or Developer Settings → My Feature)
- A new settings asset will be created
2. **Configure the Asset**
- Set the default values for your settings
- Organize the asset in the correct folder:
- Game settings: `Assets/Settings/`
- Developer settings: `Assets/Settings/Developer/`
3. **Add to Addressables**
- Open the Addressables Groups window (Window → Asset Management → Addressables → Groups)
- Drag your settings asset to the Settings group
- For game settings, ensure the addressable address is `Settings/YourSettingsClassName`
- For developer settings, ensure the addressable address is `Settings/Developer/YourSettingsClassName`
![Addressables Configuration](media/addressables_configuration.png)
### Adding to the Settings Editor Window
For game settings:
1. Open the `GameSettingsEditorWindow.cs` file in `Assets/Editor`
2. Update the tab names array to include your new settings category
3. Add a case to the switch statement in the `OnGUI` method to draw your settings
4. Add your settings type to the `LoadAllSettings` method's `CreateSettingsIfMissing` calls
Here's an example of the code changes needed:
Or fetch interaction settings once and reuse:
```csharp
// 1. Update tab names array
private string[] tabNames = new string[] { "Player", "Interaction", "My Feature" }; // Add your tab
using AppleHills.Core.Settings;
// 2. Add to switch statement in OnGUI
switch (selectedTab)
private IInteractionSettings _interaction;
void Awake()
{
case 0: // Player
DrawSettingsEditor<PlayerFollowerSettings>();
break;
case 1: // Interaction
DrawSettingsEditor<InteractionSettings>();
break;
case 2: // My Feature
DrawSettingsEditor<MyFeatureSettings>(); // Add your case
break;
_interaction = SettingsProvider.Instance.GetSettings<InteractionSettings>();
}
// 3. Add to LoadAllSettings method
private void LoadAllSettings()
void UseIt()
{
// ... existing code ...
// Add your settings type
CreateSettingsIfMissing<MyFeatureSettings>("MyFeatureSettings");
float stopDist = _interaction.PlayerStopDistance;
}
```
For developer settings:
1. Open the `DeveloperSettingsEditorWindow.cs` file in `Assets/Editor`
2. Update the tab names array to include your new settings category
3. Add a case to the switch statement in the `OnGUI` method to draw your settings
4. Add your settings type to the `LoadAllSettings` method's `CreateSettingsIfMissing` calls
As seen in your current implementation for the Debug tab:
### Use Editor-Time Values via `SettingsAccess`
For scene tools, gizmos, or editors that should reflect current settings outside Play Mode:
```csharp
// 1. Tab names include the Debug category
private string[] tabNames = new string[] { "Diving", "Debug", "Other Systems" };
// 2. Switch statement handles the Debug tab
switch (selectedTab)
{
case 0: // Diving
DrawSettingsEditor<DivingDeveloperSettings>();
break;
case 1: // Debug
DrawSettingsEditor<DebugSettings>();
break;
case 2: // Other Systems
// ... existing code ...
break;
}
// 3. LoadAllSettings includes DebugSettings
private void LoadAllSettings()
{
// ... existing code ...
CreateSettingsIfMissing<DivingDeveloperSettings>("DivingDeveloperSettings");
CreateSettingsIfMissing<DebugSettings>("DebugSettings");
}
// Returns editor-sourced values in Edit Mode; GameManager-backed in Play Mode
float stopDist = AppleHills.SettingsAccess.GetPlayerStopDistance();
float directStop = AppleHills.SettingsAccess.GetPlayerStopDistanceDirectInteraction();
float puzzleRange = AppleHills.SettingsAccess.GetPuzzlePromptRange();
```
### Using Settings in Game Code
1. **Access game settings**:
### Access Example Fields
```csharp
public class MyGameplaySystem : MonoBehaviour
{
private MyFeatureSettings settings;
private void Awake()
{
// Get settings from provider
settings = SettingsProvider.Instance.GetSettings<MyFeatureSettings>();
if (settings == null)
{
Debug.LogError("Failed to load MyFeatureSettings!");
return;
}
// Use the settings
float value = settings.MainValue;
bool specialEnabled = settings.EnableSpecialFeatures;
// Configure components based on settings
// ...
}
}
using AppleHills.Core.Settings;
var pf = SettingsProvider.Instance.GetSettings<PlayerFollowerSettings>();
// Player
float moveSpeed = pf.MoveSpeed;
float accel = pf.MaxAcceleration;
bool useRb = pf.UseRigidbody;
// Follower
float followDist = pf.FollowDistance;
float near = pf.ThresholdNear;
var inter = SettingsProvider.Instance.GetSettings<InteractionSettings>();
LayerMask interactMask = inter.InteractableLayerMask;
GameObject pickupPrefab = inter.BasePickupPrefab;
float promptRange = inter.DefaultPuzzlePromptRange;
```
2. **Access developer settings**:
## Authoring in the Editor
### Creating/Editing Settings Assets
- Open via menu: `AppleHills/Settings Editor`.
- The window discovers all assets of type `BaseSettings` and provides tabbed editing for:
- `PlayerFollowerSettings`
- `InteractionSettings`
- `DivingMinigameSettings`
- If an asset is missing, the tool auto-creates it under `Assets/Settings/`:
- `Assets/Settings/PlayerFollowerSettings.asset`
- `Assets/Settings/InteractionSettings.asset`
- `Assets/Settings/DivingMinigameSettings.asset`
- Click “Save All” to persist and refresh editor providers/gizmos.
### Addressables Keys & Loading
At runtime, `SettingsProvider` synchronously loads settings via Addressables with keys:
- `Settings/PlayerFollowerSettings`
- `Settings/InteractionSettings`
- `Settings/DivingMinigameSettings`
Ensure these assets are marked as Addressables with the exact keys above. The provider caches objects, so subsequent `GetSettings<T>()` calls are fast.
## Available Settings Types
- `PlayerFollowerSettings` (`IPlayerFollowerSettings`)
- Player: `MoveSpeed`, `MaxAcceleration`, `StopDistance`, `UseRigidbody`, `DefaultHoldMovementMode`.
- Follower: `FollowDistance`, `ManualMoveSmooth`, `ThresholdFar`, `ThresholdNear`, `StopThreshold`.
- Backend: `FollowUpdateInterval`, `FollowerSpeedMultiplier`, `HeldIconDisplayHeight`.
- `InteractionSettings` (`IInteractionSettings`)
- Interactions: `PlayerStopDistance`, `PlayerStopDistanceDirectInteraction`, `FollowerPickupDelay`.
- Input/Layering: `InteractableLayerMask`.
- Prefabs: `BasePickupPrefab`, `LevelSwitchMenuPrefab`, `DefaultPuzzleIndicatorPrefab`.
- Puzzle/UI: `DefaultPuzzlePromptRange`.
- Items: `CombinationRules`, `SlotItemConfigs` plus helpers `GetCombinationRule(...)`, `GetSlotItemConfig(...)`.
- `DivingMinigameSettings` (`IDivingMinigameSettings`)
- Movement, spawning, scoring, surfacing, normalized movement, tile generation, obstacles, camera viewfinder settings, photo input mode (`PhotoInputModes`).
## Case Studies
### Tune Interaction Distances
```csharp
public class MyDevelopmentTool : MonoBehaviour
using AppleHills.Core.Settings;
public class InteractDistanceExample
{
private MyFeatureDeveloperSettings devSettings;
private void Awake()
{
// Get developer settings
devSettings = DeveloperSettingsProvider.Instance.GetSettings<MyFeatureDeveloperSettings>();
if (devSettings == null)
{
Debug.LogError("Failed to load MyFeatureDeveloperSettings!");
return;
}
// Use the settings
bool advancedEnabled = devSettings.EnableAdvancedFeatures;
// Configure development tools based on settings
// ...
}
private readonly IInteractionSettings _s = SettingsProvider.Instance.GetSettings<InteractionSettings>();
public bool IsInRange(float dist) => dist <= _s.PlayerStopDistance;
}
```
### Best Practices
### Follower Handling & Movement
```csharp
using AppleHills.Core.Settings;
1. **Organization**
- Group related settings into a single settings class
- Use `[Header]` attributes to create logical sections
- Use `[Tooltip]` attributes to document settings
public class FollowerMover
{
private readonly IPlayerFollowerSettings _pf = SettingsProvider.Instance.GetSettings<PlayerFollowerSettings>();
public float TargetSpeed(float error) => Mathf.Clamp(error * _pf.FollowerSpeedMultiplier, 0f, _pf.MoveSpeed);
}
```
2. **Validation**
- Implement `OnValidate()` to ensure values are within acceptable ranges
- Consider dependencies between settings
### Diving Minigame Tuning
```csharp
using AppleHills.Core.Settings;
3. **Naming**
- Use descriptive names for settings properties
- Follow a consistent naming pattern
public class SpawnController
{
private readonly IDivingMinigameSettings _m = SettingsProvider.Instance.GetSettings<DivingMinigameSettings>();
public float NextCooldown(float baseCooldown) => Mathf.Clamp(baseCooldown + Random.Range(-_m.ObstacleSpawnIntervalVariation, _m.ObstacleSpawnIntervalVariation), 0.1f, 99);
}
```
4. **Performance**
- Cache settings references rather than calling `GetSettings<T>()` repeatedly
- Only access settings when needed
## Troubleshooting / FAQ
- Settings return null at runtime:
- Ensure assets are Addressable with keys `Settings/<TypeName>` and Addressables are initialized before first access.
- Editor changes dont reflect in scene gizmos:
- Click “Save All” in `AppleHills/Settings Editor`; the editor provider refresh call updates views.
- Which API to use: `SettingsProvider` vs `SettingsAccess`?
- Use `SettingsProvider` in runtime code. Use `SettingsAccess` in editor tools/gizmos or shared code that runs both in Edit and Play Modes.
5. **Defaults**
- Provide sensible default values for all settings
- Document the expected ranges for numeric values
## Paths & Namespaces
- Scripts: `Assets/Scripts/Core/Settings/`
- `BaseSettings.cs`
- `SettingsInterfaces.cs`
- `SettingsProvider.cs`
- `PlayerFollowerSettings.cs`
- `InteractionSettings.cs`
- `DivingMinigameSettings.cs`
- Editor tooling: `Assets/Editor/SettingsEditorWindow.cs`
- Editor-time facade: `Assets/Scripts/Core/SettingsAccess.cs`
- Namespaces:
- Runtime: `AppleHills.Core.Settings`
- Editor window: `AppleHills.Core.Settings.Editor`
- Facade: `AppleHills`
## Required Screenshots
To complete this documentation, you'll need to take the following screenshots:
1. **settings_system_overview.png**
- Screenshot of both settings editor windows side by side to show the full system
2. **game_settings_editor.png**
- Screenshot of the Game Settings Editor window with the PlayerFollowerSettings tab selected
3. **developer_settings_editor.png**
- Screenshot of the Developer Settings Editor window with the Debug tab selected
4. **create_settings_asset.png**
- Screenshot of the right-click Create menu showing the AppleHills/Settings and AppleHills/Developer Settings options
5. **settings_class_hierarchy.png**
- Screenshot of the Project window showing the folder structure with expanded Settings folder highlighting the base classes
6. **addressables_configuration.png**
- Screenshot of the Addressables Groups window showing settings assets properly configured
## Change Log
- v1.1: New page with TOC, code-first usage, authoring workflow, Addressables keys, case studies, troubleshooting, and paths.