Revamp the prompt system, the bootstrapper system, the starting cinematic

This commit is contained in:
Michal Pikulski
2025-10-16 19:43:19 +02:00
parent df604fbc03
commit 50448c5bd3
89 changed files with 3964 additions and 677 deletions

View File

@@ -0,0 +1,321 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
namespace PuzzleS.Editor
{
/// <summary>
/// Handles asset post-processing for puzzle step data.
/// Automatically builds level data from folder structure.
/// </summary>
public class PuzzleAssetProcessor : AssetPostprocessor
{
// Base path for puzzle data
private const string PuzzleDataBasePath = "Assets/Data/Puzzles";
/// <summary>
/// Called after assets have been imported, deleted, or moved.
/// </summary>
private static void OnPostprocessAllAssets(
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
bool puzzleAssetsChanged = false;
// Check for changes to puzzle step assets
foreach (string assetPath in importedAssets.Concat(movedAssets))
{
if (IsPuzzleAssetPath(assetPath) && Path.GetExtension(assetPath) == ".asset")
{
var asset = AssetDatabase.LoadAssetAtPath<ScriptableObject>(assetPath);
if (asset is PuzzleStepSO)
{
// Find which level this step belongs to
string assetDir = Path.GetDirectoryName(assetPath);
string levelFolderPath = FindLevelFolder(assetDir);
if (!string.IsNullOrEmpty(levelFolderPath))
{
ProcessPuzzleLevelFolder(levelFolderPath);
puzzleAssetsChanged = true;
}
}
}
}
// Check for changes to puzzle folder structure
foreach (string assetPath in deletedAssets.Concat(movedFromAssetPaths))
{
if (IsPuzzleAssetPath(assetPath))
{
// Extract parent folders for processing
string assetDir = Path.GetDirectoryName(assetPath);
string levelFolderPath = FindLevelFolder(assetDir);
if (!string.IsNullOrEmpty(levelFolderPath) && Directory.Exists(levelFolderPath))
{
ProcessPuzzleLevelFolder(levelFolderPath);
puzzleAssetsChanged = true;
}
}
}
if (puzzleAssetsChanged)
{
// Make sure changes are saved
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("[PuzzleProcessor] Puzzle data processing complete");
}
}
/// <summary>
/// Checks if an asset path is within the puzzle data folder structure
/// </summary>
private static bool IsPuzzleAssetPath(string assetPath)
{
// Unity's AssetDatabase always uses forward slashes, so we need to normalize for comparison
string normalizedPath = assetPath.Replace('\\', '/');
string normalizedBasePath = PuzzleDataBasePath;
return normalizedPath.StartsWith(normalizedBasePath) &&
!normalizedPath.Contains("/.") && // Skip hidden folders
!Path.GetExtension(normalizedPath).Equals(".meta");
}
/// <summary>
/// Find the level folder that contains this asset path
/// Assumes level folders are direct children of PuzzleDataBasePath
/// </summary>
private static string FindLevelFolder(string assetPath)
{
if (string.IsNullOrEmpty(assetPath)) return null;
// Unity's AssetDatabase always uses forward slashes
string normalizedPath = assetPath.Replace('\\', '/');
if (!normalizedPath.StartsWith(PuzzleDataBasePath))
return null;
// Get the relative path from the base path
string relativePath = normalizedPath.Substring(PuzzleDataBasePath.Length);
if (relativePath.StartsWith("/"))
relativePath = relativePath.Substring(1);
// Split into path components and get the first folder (level name)
string[] pathComponents = relativePath.Split('/');
// First component after PuzzleDataBasePath should be the level name
if (pathComponents.Length > 0)
{
// Use proper path joining with Unity's forward slash convention
return PuzzleDataBasePath + "/" + pathComponents[0];
}
return null;
}
/// <summary>
/// Process a level folder to build/update a PuzzleLevelDataSO with all puzzle steps
/// </summary>
private static void ProcessPuzzleLevelFolder(string folderPath)
{
if (!Directory.Exists(folderPath)) return;
// Get level name from folder name
string levelName = Path.GetFileName(folderPath);
if (string.IsNullOrEmpty(levelName)) return;
// Find all puzzle step assets in this level (including subfolders)
var stepAssets = FindAssetsOfTypeRecursive<PuzzleStepSO>(folderPath);
if (stepAssets.Count == 0) return;
// Get or create level data asset
var levelDataAsset = GetOrCreateLevelDataAsset(folderPath, levelName);
if (levelDataAsset == null) return;
// Update level data
levelDataAsset.levelId = levelName;
levelDataAsset.displayName = levelName; // Default display name matches folder name
levelDataAsset.allSteps = stepAssets;
// Pre-process initial steps (those with no dependencies)
levelDataAsset.initialSteps = FindInitialSteps(stepAssets);
// Pre-process dependencies (which steps are required by each step)
PrecomputeDependencies(levelDataAsset);
// Mark as dirty and save
EditorUtility.SetDirty(levelDataAsset);
// Setup addressables
SetupAddressableAsset(AssetDatabase.GetAssetPath(levelDataAsset), $"Puzzles/{levelName}");
Debug.Log($"[PuzzleProcessor] Processed level: {levelName} with {stepAssets.Count} steps");
}
/// <summary>
/// Find all assets of a specific type in a folder and its subfolders
/// </summary>
private static List<T> FindAssetsOfTypeRecursive<T>(string folderPath) where T : ScriptableObject
{
var result = new List<T>();
if (!Directory.Exists(folderPath)) return result;
var guids = AssetDatabase.FindAssets("t:" + typeof(T).Name, new[] { folderPath });
foreach (var guid in guids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
var asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
if (asset != null)
{
result.Add(asset);
}
}
return result;
}
/// <summary>
/// Get existing level data asset or create a new one
/// </summary>
private static PuzzleLevelDataSO GetOrCreateLevelDataAsset(string folderPath, string levelName)
{
// Check for existing level data asset
string levelDataAssetPath = $"{folderPath}/{levelName}.asset";
var levelDataAsset = AssetDatabase.LoadAssetAtPath<PuzzleLevelDataSO>(levelDataAssetPath);
if (levelDataAsset == null)
{
// Create new level data asset
levelDataAsset = ScriptableObject.CreateInstance<PuzzleLevelDataSO>();
AssetDatabase.CreateAsset(levelDataAsset, levelDataAssetPath);
Debug.Log($"[PuzzleProcessor] Created new level data asset: {levelDataAssetPath}");
}
return levelDataAsset;
}
/// <summary>
/// Find steps that have no dependencies (initial steps)
/// </summary>
private static List<PuzzleStepSO> FindInitialSteps(List<PuzzleStepSO> steps)
{
var initialSteps = new List<PuzzleStepSO>();
var dependentSteps = new HashSet<PuzzleStepSO>();
// Find all steps that are dependencies of other steps
foreach (var step in steps)
{
if (step == null) continue;
foreach (var unlockStep in step.unlocks)
{
if (unlockStep != null && steps.Contains(unlockStep))
{
dependentSteps.Add(unlockStep);
}
}
}
// Initial steps are those not depended on by any other step
foreach (var step in steps)
{
if (step != null && !dependentSteps.Contains(step))
{
initialSteps.Add(step);
}
}
return initialSteps;
}
/// <summary>
/// Pre-compute dependency information for a puzzle level
/// </summary>
private static void PrecomputeDependencies(PuzzleLevelDataSO levelDataAsset)
{
levelDataAsset.stepDependencies.Clear();
// Build reverse dependency map (which steps are required by each step)
var reverseDependencies = new Dictionary<string, List<string>>();
foreach (var step in levelDataAsset.allSteps)
{
if (step == null) continue;
foreach (var unlockStep in step.unlocks)
{
if (unlockStep == null) continue;
if (!reverseDependencies.ContainsKey(unlockStep.stepId))
{
reverseDependencies[unlockStep.stepId] = new List<string>();
}
reverseDependencies[unlockStep.stepId].Add(step.stepId);
}
}
// Convert to serialized form
foreach (var entry in reverseDependencies)
{
levelDataAsset.stepDependencies[entry.Key] = entry.Value.ToArray();
}
}
/// <summary>
/// Set up an asset as an Addressable with the specified address
/// </summary>
private static void SetupAddressableAsset(string assetPath, string address)
{
if (!File.Exists(assetPath)) return;
// Get Addressable settings
var settings = AddressableAssetSettingsDefaultObject.Settings;
if (settings == null)
{
Debug.LogWarning("[PuzzleProcessor] Addressable Asset Settings not found. Make sure Addressables is set up in your project.");
return;
}
// Get default group
var defaultGroup = settings.DefaultGroup;
if (defaultGroup == null)
{
Debug.LogWarning("[PuzzleProcessor] Default Addressable Asset Group not found.");
return;
}
// Get asset GUID
var guid = AssetDatabase.AssetPathToGUID(assetPath);
// Check if entry exists
var existingEntry = settings.FindAssetEntry(guid);
if (existingEntry != null)
{
// Update existing entry
existingEntry.SetAddress(address);
}
else
{
// Create new entry
settings.CreateOrMoveEntry(guid, defaultGroup);
var newEntry = settings.FindAssetEntry(guid);
if (newEntry != null)
{
newEntry.SetAddress(address);
}
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5097566c60d341dbb6f2bf5175b048cb
timeCreated: 1760532147

View File

@@ -1,116 +0,0 @@
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
public class PuzzleChainEditorWindow : EditorWindow
{
private List<PuzzleStepSO> puzzleSteps = new List<PuzzleStepSO>();
private Dictionary<PuzzleStepSO, List<PuzzleStepSO>> dependencyGraph;
private Vector2 scrollPos;
private const int INDENT_SIZE = 24;
[MenuItem("AppleHills/Puzzle Chain Editor")]
public static void ShowWindow()
{
var window = GetWindow<PuzzleChainEditorWindow>("Puzzle Chain Editor");
window.minSize = new Vector2(600, 400);
window.maxSize = new Vector2(1200, 800);
window.position = new Rect(100, 100, 700, 500); // Reasonable default size and position
}
private void OnEnable()
{
LoadPuzzleSteps();
ProcessPuzzleChains();
}
private void LoadPuzzleSteps()
{
puzzleSteps.Clear();
// Find all PuzzleStepSO assets in the project
string[] guids = AssetDatabase.FindAssets("t:PuzzleStepSO");
foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
// Only include those under Assets/Data/Puzzles (case-insensitive)
if (path.Replace('\\', '/').StartsWith("Assets/Data/Puzzles", System.StringComparison.OrdinalIgnoreCase))
{
var step = AssetDatabase.LoadAssetAtPath<PuzzleStepSO>(path);
if (step != null)
puzzleSteps.Add(step);
}
}
// Remove any nulls just in case
puzzleSteps.RemoveAll(s => s == null);
// Remove nulls from unlocks lists
foreach (var step in puzzleSteps)
{
if (step.unlocks != null)
step.unlocks.RemoveAll(u => u == null);
}
}
private void ProcessPuzzleChains()
{
// Defensive: ensure no nulls in puzzleSteps or unlocks
puzzleSteps.RemoveAll(s => s == null);
foreach (var step in puzzleSteps)
{
if (step.unlocks != null)
step.unlocks.RemoveAll(u => u == null);
}
dependencyGraph = PuzzleGraphUtility.BuildDependencyGraph(puzzleSteps);
}
private void OnGUI()
{
EditorGUILayout.LabelField("Puzzle Chain Visualization", EditorStyles.boldLabel);
if (puzzleSteps.Count == 0)
{
EditorGUILayout.HelpBox("No PuzzleStepSO assets found in Assets/Data/Puzzles.", MessageType.Warning);
return;
}
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
var initialSteps = dependencyGraph != null ? PuzzleGraphUtility.FindInitialSteps(dependencyGraph) : new List<PuzzleStepSO>();
foreach (var step in initialSteps)
{
if (step == null) continue; // Defensive
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField($"Step Path: {step.displayName} ({step.stepId})", EditorStyles.largeLabel);
GUILayout.Space(6);
DrawStepTree(step, 0);
EditorGUILayout.EndVertical();
GUILayout.Space(12); // Space between step paths
}
EditorGUILayout.EndScrollView();
}
private void DrawStepTree(PuzzleStepSO step, int indent)
{
if (step == null) {
EditorGUILayout.LabelField("[Missing Step]", EditorStyles.boldLabel);
return;
}
EditorGUILayout.BeginHorizontal();
GUILayout.Space(indent * INDENT_SIZE);
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField($"{step.displayName} ({step.stepId})", EditorStyles.boldLabel);
EditorGUILayout.LabelField(step.description ?? "", EditorStyles.wordWrappedLabel);
GUILayout.Space(4);
if (GUILayout.Button("Open in Inspector", GUILayout.Width(150)))
{
Selection.activeObject = step;
EditorGUIUtility.PingObject(step);
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
GUILayout.Space(6);
if (step.unlocks != null)
{
foreach (var unlock in step.unlocks)
{
DrawStepTree(unlock, indent + 1);
}
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: f7bfaa69d42e45adaa4a44dd143efc2f
timeCreated: 1756991142

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 453e2745b86c424da42227fbc38ed6d7
timeCreated: 1760539457

View File

@@ -0,0 +1,875 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using PuzzleS;
namespace AppleHills.Editor.PuzzleSystem
{
/// <summary>
/// Editor utility for managing puzzle steps and debugging puzzle state at runtime.
/// Provides tabs for both editing puzzle data and runtime debugging.
/// </summary>
public class PuzzleEditorWindow : EditorWindow
{
// Paths
private const string PuzzleDataBasePath = "Assets/Data";
private const string MenuPath = "AppleHills/Puzzle Editor";
// Editor state
private List<PuzzleStepSO> _allPuzzleSteps = new List<PuzzleStepSO>();
private Dictionary<string, List<PuzzleStepSO>> _puzzleStepsByFolder = new Dictionary<string, List<PuzzleStepSO>>();
private PuzzleStepSO _selectedStep;
private Dictionary<string, bool> _folderExpanded = new Dictionary<string, bool>();
private Vector2 _puzzleListScrollPosition;
private Vector2 _puzzleEditScrollPosition;
private string _searchQuery = "";
private bool _isDirty = false;
// Tab management
private int _selectedTab = 0;
private readonly string[] _tabNames = { "Edit", "Debug" };
// Runtime debug state
private Dictionary<string, bool> _stepUnlockState = new Dictionary<string, bool>();
private Dictionary<string, bool> _stepCompletedState = new Dictionary<string, bool>();
private Vector2 _debugScrollPosition;
private bool _isPlaying = false;
private bool _hasRuntimeData = false;
private PuzzleLevelDataSO _runtimeLevelData;
// New step creation
private string _newStepName = "New Step";
private string _selectedFolder = "";
private bool _showCreateNewStepDialog = false;
[MenuItem(MenuPath)]
public static void ShowWindow()
{
var window = GetWindow<PuzzleEditorWindow>("Puzzle Editor");
window.minSize = new Vector2(800, 600);
window.Show();
}
private void OnEnable()
{
// Load all puzzle steps
LoadAllPuzzleSteps();
// Register for undo/redo
Undo.undoRedoPerformed += OnUndoRedo;
// Set up update callbacks
EditorApplication.update += OnEditorUpdate;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
}
private void OnDisable()
{
// Unregister from undo/redo
Undo.undoRedoPerformed -= OnUndoRedo;
// Unregister from update
EditorApplication.update -= OnEditorUpdate;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
}
private void OnEditorUpdate()
{
// Check if we're in play mode
bool currentlyPlaying = EditorApplication.isPlaying && !EditorApplication.isPaused;
if (_isPlaying != currentlyPlaying)
{
_isPlaying = currentlyPlaying;
Repaint();
}
// In play mode, update runtime data periodically
if (_isPlaying)
{
UpdateRuntimeData();
Repaint();
}
}
private void OnUndoRedo()
{
_isDirty = true;
Repaint();
}
private void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (state == PlayModeStateChange.EnteredPlayMode)
{
_isPlaying = true;
_hasRuntimeData = false;
_stepUnlockState.Clear();
_stepCompletedState.Clear();
}
else if (state == PlayModeStateChange.ExitingPlayMode)
{
_isPlaying = false;
_hasRuntimeData = false;
_runtimeLevelData = null;
}
Repaint();
}
private void OnGUI()
{
DrawHeader();
_selectedTab = GUILayout.Toolbar(_selectedTab, _tabNames);
EditorGUILayout.Space();
switch (_selectedTab)
{
case 0: // Edit tab
DrawEditTab();
break;
case 1: // Debug tab
DrawDebugTab();
break;
}
// Apply any pending changes
if (_isDirty)
{
SaveChanges();
_isDirty = false;
}
}
#region Header UI
private void DrawHeader()
{
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, GUILayout.Width(60)))
{
LoadAllPuzzleSteps();
}
GUILayout.FlexibleSpace();
// Tab-specific toolbar options
if (_selectedTab == 0) // Edit tab
{
if (GUILayout.Button("Create New", EditorStyles.toolbarButton, GUILayout.Width(80)))
{
_showCreateNewStepDialog = true;
}
}
else if (_selectedTab == 1) // Debug tab
{
EditorGUILayout.LabelField(_isPlaying ? "Runtime Active" : "Editor Mode", EditorStyles.toolbarButton, GUILayout.Width(100));
}
EditorGUILayout.EndHorizontal();
}
#endregion
#region Edit Tab
private void DrawEditTab()
{
EditorGUILayout.BeginHorizontal();
// Left panel - puzzle step list
EditorGUILayout.BeginVertical(GUILayout.Width(250));
DrawStepListPanel();
EditorGUILayout.EndVertical();
// Separator
EditorGUILayout.Space();
// Right panel - puzzle step editor
EditorGUILayout.BeginVertical();
DrawStepEditorPanel();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
// Draw create new step dialog if needed
if (_showCreateNewStepDialog)
{
DrawCreateNewStepDialog();
}
}
private void DrawStepListPanel()
{
// Search field
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
_searchQuery = EditorGUILayout.TextField(_searchQuery, EditorStyles.toolbarSearchField);
if (GUILayout.Button("×", EditorStyles.toolbarButton, GUILayout.Width(20)) && !string.IsNullOrEmpty(_searchQuery))
{
_searchQuery = "";
GUI.FocusControl(null);
}
EditorGUILayout.EndHorizontal();
_puzzleListScrollPosition = EditorGUILayout.BeginScrollView(_puzzleListScrollPosition);
// If search query exists, show filtered results across all folders
if (!string.IsNullOrEmpty(_searchQuery))
{
var filteredSteps = _allPuzzleSteps.Where(step =>
step.displayName.ToLower().Contains(_searchQuery.ToLower()) ||
step.stepId.ToLower().Contains(_searchQuery.ToLower())).ToList();
if (filteredSteps.Any())
{
EditorGUILayout.LabelField($"Search Results ({filteredSteps.Count}):", EditorStyles.boldLabel);
foreach (var step in filteredSteps)
{
if (DrawStepListItem(step))
{
_selectedStep = step;
GUI.FocusControl(null);
}
}
}
else
{
EditorGUILayout.LabelField("No matching steps found");
}
}
// Otherwise show organized by folder
else
{
foreach (var folderEntry in _puzzleStepsByFolder)
{
string folderName = folderEntry.Key;
List<PuzzleStepSO> steps = folderEntry.Value;
if (!_folderExpanded.ContainsKey(folderName))
{
_folderExpanded[folderName] = true; // Default to expanded
}
// Folder header with toggle
EditorGUILayout.BeginHorizontal();
_folderExpanded[folderName] = EditorGUILayout.Foldout(_folderExpanded[folderName], folderName, true);
// Show step count
EditorGUILayout.LabelField($"({steps.Count})", GUILayout.Width(40));
EditorGUILayout.EndHorizontal();
// Draw steps in folder if expanded
if (_folderExpanded[folderName])
{
EditorGUI.indentLevel++;
foreach (var step in steps)
{
if (DrawStepListItem(step))
{
_selectedStep = step;
GUI.FocusControl(null);
}
}
EditorGUI.indentLevel--;
}
}
}
EditorGUILayout.EndScrollView();
}
private bool DrawStepListItem(PuzzleStepSO step)
{
if (step == null) return false;
bool isSelected = step == _selectedStep;
EditorGUILayout.BeginHorizontal(isSelected ? EditorStyles.selectionRect : EditorStyles.helpBox);
// Icon if available
if (step.icon != null)
{
GUILayout.Label(new GUIContent(step.icon.texture), GUILayout.Width(20), GUILayout.Height(20));
}
else
{
GUILayout.Space(24);
}
// Name and ID
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField(step.displayName, EditorStyles.boldLabel);
EditorGUILayout.LabelField(step.stepId, EditorStyles.miniLabel);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
// Check if this item was clicked
Rect itemRect = GUILayoutUtility.GetLastRect();
bool wasClicked = Event.current.type == EventType.MouseDown && Event.current.button == 0
&& itemRect.Contains(Event.current.mousePosition);
if (wasClicked)
{
Event.current.Use();
}
return wasClicked;
}
private void DrawStepEditorPanel()
{
if (_selectedStep == null)
{
EditorGUILayout.HelpBox("Select a puzzle step to edit", MessageType.Info);
return;
}
_puzzleEditScrollPosition = EditorGUILayout.BeginScrollView(_puzzleEditScrollPosition);
EditorGUI.BeginChangeCheck();
// Header with name and ID
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Editing:", EditorStyles.boldLabel, GUILayout.Width(60));
EditorGUILayout.LabelField(_selectedStep.displayName, EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
// Basic properties
EditorGUILayout.LabelField("Basic Properties", EditorStyles.boldLabel);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
// Step ID
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Step ID:", GUILayout.Width(100));
string newStepId = EditorGUILayout.TextField(_selectedStep.stepId);
if (newStepId != _selectedStep.stepId)
{
Undo.RecordObject(_selectedStep, "Change Step ID");
_selectedStep.stepId = newStepId;
_isDirty = true;
}
EditorGUILayout.EndHorizontal();
// Display Name
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Display Name:", GUILayout.Width(100));
string newDisplayName = EditorGUILayout.TextField(_selectedStep.displayName);
if (newDisplayName != _selectedStep.displayName)
{
Undo.RecordObject(_selectedStep, "Change Display Name");
_selectedStep.displayName = newDisplayName;
_isDirty = true;
}
EditorGUILayout.EndHorizontal();
// Description
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Description:", GUILayout.Width(100));
string newDescription = EditorGUILayout.TextArea(_selectedStep.description, GUILayout.Height(60));
if (newDescription != _selectedStep.description)
{
Undo.RecordObject(_selectedStep, "Change Description");
_selectedStep.description = newDescription;
_isDirty = true;
}
EditorGUILayout.EndHorizontal();
// Icon
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Icon:", GUILayout.Width(100));
Sprite newIcon = (Sprite)EditorGUILayout.ObjectField(_selectedStep.icon, typeof(Sprite), false);
if (newIcon != _selectedStep.icon)
{
Undo.RecordObject(_selectedStep, "Change Icon");
_selectedStep.icon = newIcon;
_isDirty = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
// Unlocks (dependencies)
EditorGUILayout.LabelField("Unlocks", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("Steps that will be unlocked when this step is completed", MessageType.Info);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
// Show unlocked steps list
if (_selectedStep.unlocks.Count > 0)
{
for (int i = 0; i < _selectedStep.unlocks.Count; i++)
{
EditorGUILayout.BeginHorizontal();
// Draw step selector
PuzzleStepSO newUnlockedStep = (PuzzleStepSO)EditorGUILayout.ObjectField(
_selectedStep.unlocks[i], typeof(PuzzleStepSO), false);
if (newUnlockedStep != _selectedStep.unlocks[i])
{
Undo.RecordObject(_selectedStep, "Change Unlocked Step");
_selectedStep.unlocks[i] = newUnlockedStep;
_isDirty = true;
}
// Remove button
if (GUILayout.Button("-", GUILayout.Width(20)))
{
Undo.RecordObject(_selectedStep, "Remove Unlocked Step");
_selectedStep.unlocks.RemoveAt(i);
_isDirty = true;
i--;
}
EditorGUILayout.EndHorizontal();
}
}
else
{
EditorGUILayout.LabelField("No steps will be unlocked");
}
// Add new dependency
if (GUILayout.Button("Add Unlocked Step"))
{
Undo.RecordObject(_selectedStep, "Add Unlocked Step");
_selectedStep.unlocks.Add(null);
_isDirty = true;
}
EditorGUILayout.EndVertical();
EditorGUILayout.Space();
// Asset path info
string assetPath = AssetDatabase.GetAssetPath(_selectedStep);
EditorGUILayout.LabelField("Asset Path:", EditorStyles.miniLabel);
EditorGUILayout.LabelField(assetPath, EditorStyles.miniLabel);
// Delete button
EditorGUILayout.Space();
if (GUILayout.Button("Delete Step", GUILayout.Width(100)))
{
if (EditorUtility.DisplayDialog("Delete Puzzle Step",
$"Are you sure you want to delete '{_selectedStep.displayName}'? This action cannot be undone.",
"Delete", "Cancel"))
{
DeletePuzzleStep(_selectedStep);
_selectedStep = null;
}
}
if (EditorGUI.EndChangeCheck())
{
EditorUtility.SetDirty(_selectedStep);
}
EditorGUILayout.EndScrollView();
}
private void DrawCreateNewStepDialog()
{
// Create a centered window
Rect windowRect = new Rect(
(position.width - 400) / 2,
(position.height - 200) / 2,
400, 200);
GUI.Box(windowRect, "Create New Puzzle Step", EditorStyles.helpBox);
GUILayout.BeginArea(new Rect(windowRect.x + 10, windowRect.y + 30, windowRect.width - 20, windowRect.height - 40));
// Name field
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Name:", GUILayout.Width(80));
_newStepName = EditorGUILayout.TextField(_newStepName);
EditorGUILayout.EndHorizontal();
// Folder selection
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Folder:", GUILayout.Width(80));
// Create folder dropdown
List<string> folderNames = _puzzleStepsByFolder.Keys.ToList();
int selectedFolderIndex = folderNames.IndexOf(_selectedFolder);
int newSelectedFolderIndex = EditorGUILayout.Popup(selectedFolderIndex >= 0 ? selectedFolderIndex : 0, folderNames.ToArray());
if (newSelectedFolderIndex >= 0 && newSelectedFolderIndex < folderNames.Count)
{
_selectedFolder = folderNames[newSelectedFolderIndex];
}
else if (folderNames.Count > 0)
{
_selectedFolder = folderNames[0];
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
// Buttons
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Cancel", GUILayout.Width(100)))
{
_showCreateNewStepDialog = false;
}
if (GUILayout.Button("Create", GUILayout.Width(100)))
{
if (!string.IsNullOrEmpty(_newStepName) && !string.IsNullOrEmpty(_selectedFolder))
{
CreateNewPuzzleStep(_newStepName, _selectedFolder);
_showCreateNewStepDialog = false;
_newStepName = "New Step";
}
}
EditorGUILayout.EndHorizontal();
GUILayout.EndArea();
}
#endregion
#region Debug Tab
private void DrawDebugTab()
{
if (!_isPlaying)
{
EditorGUILayout.HelpBox("Enter Play Mode to debug puzzles at runtime", MessageType.Info);
return;
}
if (!_hasRuntimeData || _runtimeLevelData == null)
{
EditorGUILayout.HelpBox("Waiting for puzzle data to be loaded...", MessageType.Info);
return;
}
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
EditorGUILayout.LabelField($"Current Level: {_runtimeLevelData.levelId}", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
_debugScrollPosition = EditorGUILayout.BeginScrollView(_debugScrollPosition);
// List all steps with their current state
EditorGUILayout.LabelField("Puzzle Steps", EditorStyles.boldLabel);
// Show steps directly from the level data in a flat list
foreach (var step in _runtimeLevelData.allSteps)
{
if (step == null) continue;
DrawRuntimeStepItem(step);
}
EditorGUILayout.EndScrollView();
}
private void DrawRuntimeStepItem(PuzzleStepSO step)
{
bool isUnlocked = _stepUnlockState.ContainsKey(step.stepId) && _stepUnlockState[step.stepId];
bool isCompleted = _stepCompletedState.ContainsKey(step.stepId) && _stepCompletedState[step.stepId];
// Set background color based on state
Color originalColor = GUI.backgroundColor;
if (isCompleted)
GUI.backgroundColor = new Color(0.5f, 1f, 0.5f); // Green for completed
else if (isUnlocked)
GUI.backgroundColor = new Color(1f, 1f, 0.5f); // Yellow for unlocked but not completed
else
GUI.backgroundColor = new Color(1f, 0.5f, 0.5f); // Red for locked
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
// Reset color
GUI.backgroundColor = originalColor;
EditorGUILayout.BeginHorizontal();
// Step info
EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true));
EditorGUILayout.LabelField(step.displayName, EditorStyles.boldLabel);
EditorGUILayout.LabelField(step.stepId, EditorStyles.miniLabel);
// Status text
string statusText = isCompleted ? "Completed" : (isUnlocked ? "Unlocked" : "Locked");
EditorGUILayout.LabelField($"Status: {statusText}", EditorStyles.miniLabel);
EditorGUILayout.EndVertical();
// Action buttons
EditorGUILayout.BeginVertical(GUILayout.Width(100));
EditorGUI.BeginDisabledGroup(isCompleted);
if (GUILayout.Button(isUnlocked ? "Lock" : "Unlock"))
{
ToggleStepUnlocked(step);
}
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(!isUnlocked || isCompleted);
if (GUILayout.Button("Complete"))
{
CompleteStep(step);
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
#endregion
#region Data Management
private void LoadAllPuzzleSteps()
{
_allPuzzleSteps.Clear();
_puzzleStepsByFolder.Clear();
// Find all PuzzleStepSO assets in the project
string[] guids = AssetDatabase.FindAssets("t:PuzzleStepSO");
foreach (string guid in guids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
// Only include assets from the Data folder
if (assetPath.StartsWith(PuzzleDataBasePath))
{
PuzzleStepSO step = AssetDatabase.LoadAssetAtPath<PuzzleStepSO>(assetPath);
if (step != null)
{
_allPuzzleSteps.Add(step);
// Add to folder dictionary for organization
string folder = Path.GetDirectoryName(assetPath)?.Replace("\\", "/");
if (folder != null)
{
if (!_puzzleStepsByFolder.ContainsKey(folder))
{
_puzzleStepsByFolder[folder] = new List<PuzzleStepSO>();
}
_puzzleStepsByFolder[folder].Add(step);
}
}
}
}
// Make sure each folder is sorted by name
foreach (var key in _puzzleStepsByFolder.Keys.ToList())
{
_puzzleStepsByFolder[key] = _puzzleStepsByFolder[key]
.OrderBy(step => step.displayName)
.ToList();
}
_isDirty = false;
}
private void SaveChanges()
{
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
private void CreateNewPuzzleStep(string stepName, string folderPath)
{
// Create a new PuzzleStepSO
PuzzleStepSO newStep = CreateInstance<PuzzleStepSO>();
newStep.stepId = GenerateUniqueStepId(stepName);
newStep.displayName = stepName;
// Create the path
string assetPath = Path.Combine(folderPath, $"{stepName}.asset").Replace("\\", "/");
// Make sure the directory exists
string directory = Path.GetDirectoryName(assetPath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// Create the asset
AssetDatabase.CreateAsset(newStep, assetPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
// Reload all steps and select the new one
LoadAllPuzzleSteps();
_selectedStep = newStep;
}
private void DeletePuzzleStep(PuzzleStepSO step)
{
if (step == null) return;
string assetPath = AssetDatabase.GetAssetPath(step);
if (!string.IsNullOrEmpty(assetPath))
{
// Also need to remove all references to this step from other steps' unlocks lists
foreach (var otherStep in _allPuzzleSteps)
{
if (otherStep != null && otherStep != step)
{
if (otherStep.unlocks.Contains(step))
{
Undo.RecordObject(otherStep, "Remove Deleted Step Reference");
otherStep.unlocks.Remove(step);
EditorUtility.SetDirty(otherStep);
}
}
}
AssetDatabase.DeleteAsset(assetPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
// Reload all steps
LoadAllPuzzleSteps();
}
}
private string GenerateUniqueStepId(string baseName)
{
// Convert to lowercase and replace spaces with underscores
string baseId = baseName.ToLower().Replace(" ", "_");
// Check if this ID already exists
bool idExists = _allPuzzleSteps.Any(step => step.stepId == baseId);
if (!idExists)
{
return baseId;
}
// Add a number suffix if ID already exists
int counter = 1;
while (_allPuzzleSteps.Any(step => step.stepId == $"{baseId}_{counter}"))
{
counter++;
}
return $"{baseId}_{counter}";
}
#endregion
#region Runtime Debug Helpers
private void UpdateRuntimeData()
{
if (!_isPlaying) return;
// Find PuzzleManager instance
PuzzleManager puzzleManager = Object.FindObjectOfType<PuzzleManager>();
if (puzzleManager == null)
{
_hasRuntimeData = false;
return;
}
// Get current level data
var levelData = puzzleManager.GetCurrentLevelData();
if (levelData == null)
{
_hasRuntimeData = false;
return;
}
_hasRuntimeData = true;
_runtimeLevelData = levelData;
// Update step states
foreach (var step in _runtimeLevelData.allSteps)
{
if (step != null)
{
_stepUnlockState[step.stepId] = puzzleManager.IsStepUnlocked(step);
_stepCompletedState[step.stepId] = puzzleManager.IsPuzzleStepCompleted(step.stepId);
}
}
}
private void ToggleStepUnlocked(PuzzleStepSO step)
{
if (!_isPlaying || step == null) return;
PuzzleManager puzzleManager = Object.FindObjectOfType<PuzzleManager>();
if (puzzleManager == null) return;
// Get current unlock state
bool isCurrentlyUnlocked = _stepUnlockState.ContainsKey(step.stepId) && _stepUnlockState[step.stepId];
// Call appropriate method using reflection since these might be private methods
System.Type managerType = puzzleManager.GetType();
if (isCurrentlyUnlocked)
{
// Find the LockStep method that takes a PuzzleStepSO parameter
System.Reflection.MethodInfo lockMethod = managerType.GetMethod("LockStep",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic);
if (lockMethod != null)
{
lockMethod.Invoke(puzzleManager, new object[] { step });
}
}
else
{
// Find the UnlockStep method that takes a PuzzleStepSO parameter
System.Reflection.MethodInfo unlockMethod = managerType.GetMethod("UnlockStep",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic);
if (unlockMethod != null)
{
unlockMethod.Invoke(puzzleManager, new object[] { step });
}
}
// Update state
UpdateRuntimeData();
}
private void CompleteStep(PuzzleStepSO step)
{
if (!_isPlaying || step == null) return;
PuzzleManager puzzleManager = Object.FindObjectOfType<PuzzleManager>();
if (puzzleManager == null) return;
// Complete the step
puzzleManager.MarkPuzzleStepCompleted(step);
// Update state
UpdateRuntimeData();
}
#endregion
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c733f3c6624e4e5486c07abfe4fab81e
timeCreated: 1760539457