Import assets from store

This commit is contained in:
Sahik committed 2026-09-23 09:30:04 +08:00
1 parent a05f2e47a2
commit 376e52e323
875 files changed
+128037

No files matched your search

@@ -0,0 +1,246 @@
using System;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace CharacterMovement.Editor
{
// Auto-opens on first import so buyers always have a clear entry point,
// then hands off to the Setup Wizard. Editor-only, self-contained.
[InitializeOnLoad]
internal static class CharacterControllerStartup
{
private const string AutoShowKey = "MotionCore.GettingStarted.AutoShow";
static CharacterControllerStartup()
{
EditorApplication.delayCall += TryAutoShow;
}
private static void TryAutoShow()
{
if (!EditorPrefs.GetBool(AutoShowKey, true))
return;
// Show once per project (keyed by product GUID), not on every recompile.
string shownKey = "MotionCore.GettingStarted.Shown." + PlayerSettings.productGUID;
if (EditorPrefs.GetBool(shownKey, false))
return;
EditorPrefs.SetBool(shownKey, true);
CharacterControllerGettingStarted.Open();
}
internal static bool AutoShow
{
get => EditorPrefs.GetBool(AutoShowKey, true);
set => EditorPrefs.SetBool(AutoShowKey, value);
}
}
public sealed class CharacterControllerGettingStarted : EditorWindow
{
private const string Root = "Assets/Character Controller";
private const string CoreDemoScene = Root + "/Core/Scenes/DemoScene.unity";
private const string FpsDemoScene = Root + "/FPSFirstPerson/Scenes/FPSDemoScene.unity";
private const string PrintableManual = Root + "/Core/Documentation/Character Controller Manual (Printable).html";
private const string Manual = Root + "/MANUAL.md";
private const string DocumentationFolder = Root + "/Core/Documentation";
private Vector2 _scroll;
private GUIStyle _h1;
private GUIStyle _step;
private GUIStyle _body;
[MenuItem("Tools/Character Controller/Getting Started", false, -100)]
public static void Open()
{
CharacterControllerGettingStarted window = GetWindow<CharacterControllerGettingStarted>(true, "Character Controller");
window.minSize = new Vector2(460f, 620f);
window.Show();
}
private void BuildStyles()
{
if (_h1 != null)
return;
_h1 = new GUIStyle(EditorStyles.boldLabel) { fontSize = 17 };
_step = new GUIStyle(EditorStyles.boldLabel) { fontSize = 13 };
_body = new GUIStyle(EditorStyles.label) { wordWrap = true };
}
private void OnGUI()
{
BuildStyles();
_scroll = EditorGUILayout.BeginScrollView(_scroll);
EditorGUILayout.Space(6f);
EditorGUILayout.LabelField("Motion Core Character Controller", _h1);
EditorGUILayout.LabelField("Welcome! Follow the three steps below to get a controller running in a couple of minutes.", _body);
EditorGUILayout.Space(8f);
DrawEnvironmentCheck();
DrawStepTryDemo();
DrawStepBuildYourOwn();
DrawDocs();
DrawFooter();
EditorGUILayout.EndScrollView();
}
// ---- Step 0: Environment health check -------------------------------
private void DrawEnvironmentCheck()
{
EditorGUILayout.LabelField("1. Check your project is ready", _step);
#if ENABLE_INPUT_SYSTEM
EditorGUILayout.HelpBox("Input System backend is active. Your project is ready.", MessageType.Info);
#else
EditorGUILayout.HelpBox(
"This package needs the Input System backend. Set Edit > Project Settings > Player > " +
"Active Input Handling to \"Input System Package\" or \"Both\", then let Unity restart. " +
"Until then the controller will not receive input.",
MessageType.Error);
if (GUILayout.Button("Open Player Settings"))
SettingsService.OpenProjectSettings("Project/Player");
#endif
EditorGUILayout.Space(10f);
}
// ---- Step 1: Try a ready-made demo ----------------------------------
private void DrawStepTryDemo()
{
EditorGUILayout.LabelField("2. Try a ready-made demo scene", _step);
EditorGUILayout.LabelField("Open a demo and press Play. Move with WASD, jump with Space, press F1 to toggle the on-screen help.", _body);
EditorGUILayout.Space(4f);
using (new EditorGUI.DisabledScope(!SceneExists(CoreDemoScene)))
{
if (GUILayout.Button("Open Core Demo Scene", GUILayout.Height(30f)))
OpenScene(CoreDemoScene);
}
bool hasFps = SceneExists(FpsDemoScene);
using (new EditorGUI.DisabledScope(!hasFps))
{
if (GUILayout.Button(hasFps ? "Open FPS Demo Scene" : "Open FPS Demo Scene (add-on not imported)", GUILayout.Height(30f)))
OpenScene(FpsDemoScene);
}
EditorGUILayout.Space(10f);
}
// ---- Step 2: Build your own controller ------------------------------
private void DrawStepBuildYourOwn()
{
EditorGUILayout.LabelField("3. Add a controller to your own scene", _step);
EditorGUILayout.LabelField("The Setup Wizard creates a fully wired player (components, input, camera, presets) in one click. Run Validate afterwards to catch setup mistakes.", _body);
EditorGUILayout.Space(4f);
if (GUILayout.Button("Open Setup Wizard", GUILayout.Height(34f)))
EditorApplication.ExecuteMenuItem("Tools/Character Controller/Setup Wizard");
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Validate a Player"))
EditorApplication.ExecuteMenuItem("Tools/Character Controller/Validation Window");
}
EditorGUILayout.Space(10f);
}
// ---- Docs -----------------------------------------------------------
private void DrawDocs()
{
EditorGUILayout.LabelField("Documentation", _step);
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Open Printable Manual (PDF-ready)"))
OpenExternal(PrintableManual, Manual);
if (GUILayout.Button("Open Manual (text)"))
PingAsset(Manual);
}
if (GUILayout.Button("Show Documentation Folder"))
PingAsset(DocumentationFolder);
EditorGUILayout.Space(10f);
}
private void DrawFooter()
{
EditorGUILayout.Space(6f);
using (new EditorGUILayout.HorizontalScope())
{
bool auto = EditorGUILayout.ToggleLeft("Show this window on project startup", CharacterControllerStartup.AutoShow);
if (auto != CharacterControllerStartup.AutoShow)
CharacterControllerStartup.AutoShow = auto;
}
EditorGUILayout.LabelField("You can reopen this any time from Tools > Character Controller > Getting Started.", EditorStyles.miniLabel);
}
// ---- Helpers --------------------------------------------------------
private static bool SceneExists(string assetPath)
{
return !string.IsNullOrEmpty(AssetDatabase.AssetPathToGUID(assetPath));
}
private static void OpenScene(string assetPath)
{
if (!SceneExists(assetPath))
{
EditorUtility.DisplayDialog("Character Controller", "Demo scene not found:\n" + assetPath, "OK");
return;
}
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
return;
EditorSceneManager.OpenScene(assetPath, OpenSceneMode.Single);
}
// Opens an external file (e.g. the printable HTML) in the OS default app,
// falling back to pinging a second asset if the first is missing.
private static void OpenExternal(string primaryAssetPath, string fallbackAssetPath)
{
string full = ToAbsolute(primaryAssetPath);
if (File.Exists(full))
{
Application.OpenURL(new Uri(full).AbsoluteUri);
return;
}
PingAsset(fallbackAssetPath);
}
private static void PingAsset(string assetPath)
{
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath);
if (obj == null)
{
EditorUtility.DisplayDialog("Character Controller", "Not found:\n" + assetPath, "OK");
return;
}
EditorGUIUtility.PingObject(obj);
Selection.activeObject = obj;
}
private static string ToAbsolute(string assetPath)
{
// Application.dataPath ends with "/Assets"; asset paths start with "Assets/".
string projectRoot = Directory.GetParent(Application.dataPath).FullName;
return Path.GetFullPath(Path.Combine(projectRoot, assetPath));
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 2c8870ff91414ce4e9d7ccab9745f9a7
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CharacterControllerGettingStarted.cs
uploadId: 997018
@@ -0,0 +1,454 @@
using CharacterMovement;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.InputSystem;
namespace CharacterMovement.Editor
{
public sealed class CharacterControllerSetupWizard : EditorWindow
{
private const string CoreInputPath = "Assets/Character Controller/Core/Scripts/Input/Controls.inputactions";
private const string ParkourLiteMotorSettingsPath = "Assets/Character Controller/Core/Data/ParkourLiteMotorSettings.asset";
private const string TacticalMotorSettingsPath = "Assets/Character Controller/Core/Data/TacticalFPSMotorSettings.asset";
private const string FpsInputPath = "Assets/Character Controller/FPSFirstPerson/Input/FPSControls.inputactions";
private const string FpsCameraConfigPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoFpsCamera.asset";
private const string FpsAdsSettingsPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoAdsSettings.asset";
private const string FpsParkourSettingsPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoParkourSettings.asset";
private const string FpsRecoilProfilePath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoRifleRecoil.asset";
private const string FpsSwayProfilePath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoWeaponSway.asset";
private const string FpsRifleDefinitionPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoRifle.asset";
private const string FpsHitmarkerSettingsPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoHitmarkerSettings.asset";
private static readonly string[] FpsComponentTypeNames =
{
"CharacterMovement.FPS.FPSInputHandler",
"CharacterMovement.FPS.FpsCommandBus",
"CharacterMovement.FPS.FpsLocalInputCommandSource",
"CharacterMovement.FPS.FpsStateReplicationController",
"CharacterMovement.FPS.FpsCameraController",
"CharacterMovement.FPS.FPSViewMotion",
"CharacterMovement.FPS.AdsController",
"CharacterMovement.FPS.WeaponSwayController",
"CharacterMovement.FPS.RecoilController",
"CharacterMovement.FPS.WeaponManager",
"CharacterMovement.FPS.FpsInteractor",
"CharacterMovement.FPS.FpsInventory",
"CharacterMovement.FPS.InventoryWeaponLoadoutBinder",
"CharacterMovement.FPS.SurfaceDetector",
"CharacterMovement.FPS.FootstepController",
"CharacterMovement.FPS.HitmarkerFeedbackController",
"CharacterMovement.FPS.ProjectileImpactEffectSpawner",
"CharacterMovement.FPS.FpsParkourController",
"CharacterMovement.FPS.FPSModule"
};
[SerializeField] private SetupMode setupMode = SetupMode.FPS;
[SerializeField] private GameObject targetPlayer;
[SerializeField] private bool createNewPlayer = true;
[SerializeField] private bool createCameraRig = true;
[SerializeField] private bool assignDemoFpsWeapon = true;
[SerializeField] private LayerMask groundLayerMask = 1;
[SerializeField] private LayerMask stairsLayerMask = 1;
private Vector2 _scroll;
private string _lastResult;
private enum SetupMode
{
Core,
FPS
}
[MenuItem("Tools/Character Controller/Setup Wizard", false, -20)]
public static void Open()
{
CharacterControllerSetupWizard window = GetWindow<CharacterControllerSetupWizard>("CC Setup Wizard");
window.minSize = new Vector2(440f, 500f);
}
private void OnEnable()
{
if (!targetPlayer && Selection.activeGameObject)
targetPlayer = Selection.activeGameObject.GetComponentInParent<PlayerController>()?.gameObject ?? Selection.activeGameObject;
}
private void OnGUI()
{
_scroll = EditorGUILayout.BeginScrollView(_scroll);
EditorGUILayout.LabelField("Motion Core Setup Wizard", EditorStyles.boldLabel);
EditorGUILayout.HelpBox(
"Use this wizard when you do not want to manually pick scripts from the package. It creates or configures a player with the expected components, input assets, presets, camera references, and FPS add-on wiring.",
MessageType.Info);
DrawSetupOptions();
DrawActions();
DrawResult();
EditorGUILayout.Space(10f);
EditorGUILayout.LabelField("What It Creates", EditorStyles.boldLabel);
DrawModeDescription();
EditorGUILayout.EndScrollView();
}
private void DrawSetupOptions()
{
EditorGUILayout.Space(8f);
setupMode = (SetupMode)EditorGUILayout.EnumPopup("Controller Type", setupMode);
if (setupMode == SetupMode.FPS && !CharacterControllerSetupWizardUtility.HasFpsAddOn())
{
EditorGUILayout.HelpBox(
"The FPS add-on is not available in this project. Import FPSFirstPerson or switch Controller Type to Core.",
MessageType.Warning);
}
createNewPlayer = EditorGUILayout.Toggle("Create New Player", createNewPlayer);
using (new EditorGUI.DisabledScope(createNewPlayer))
targetPlayer = (GameObject)EditorGUILayout.ObjectField("Target Player", targetPlayer, typeof(GameObject), true);
createCameraRig = EditorGUILayout.Toggle(setupMode == SetupMode.FPS ? "Create FPS Camera Rig" : "Create CameraFollow Rig", createCameraRig);
if (setupMode == SetupMode.FPS)
assignDemoFpsWeapon = EditorGUILayout.Toggle("Assign Demo Rifle", assignDemoFpsWeapon);
groundLayerMask = CharacterControllerSetupWizardUtility.LayerMaskField("Ground Layers", groundLayerMask);
stairsLayerMask = CharacterControllerSetupWizardUtility.LayerMaskField("Stairs Layers", stairsLayerMask);
}
private void DrawActions()
{
EditorGUILayout.Space(10f);
using (new EditorGUILayout.HorizontalScope())
{
using (new EditorGUI.DisabledScope(setupMode == SetupMode.FPS && !CharacterControllerSetupWizardUtility.HasFpsAddOn()))
{
if (GUILayout.Button(createNewPlayer ? "Create Controller" : "Configure Selected", GUILayout.Height(34f)))
RunSetup();
}
if (GUILayout.Button("Validate", GUILayout.Height(34f)))
OpenValidatorForTarget();
}
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Build Core Demo"))
EditorApplication.ExecuteMenuItem("Tools/Character Controller/Build Demo Scene");
using (new EditorGUI.DisabledScope(!CharacterControllerSetupWizardUtility.HasFpsAddOn()))
{
if (GUILayout.Button("Build FPS Demo"))
EditorApplication.ExecuteMenuItem("Tools/Character Controller/Build FPS Demo Scene");
}
}
}
private void DrawResult()
{
if (string.IsNullOrEmpty(_lastResult))
return;
EditorGUILayout.Space(8f);
EditorGUILayout.HelpBox(_lastResult, MessageType.Info);
}
private void DrawModeDescription()
{
if (setupMode == SetupMode.Core)
{
EditorGUILayout.HelpBox(
"Core setup adds Rigidbody, CapsuleCollider, InputHandler, PlayerController, the core input asset, a movement preset, walkable layer masks, and an optional third-person CameraFollow rig.",
MessageType.None);
return;
}
EditorGUILayout.HelpBox(
"FPS setup includes the Core setup plus FPS input, command bus, first-person camera, view motion, ADS, recoil, weapon sway, weapon manager, interaction, inventory, footsteps, hitmarker feedback, parkour, and FPSModule. Demo weapon data is optional.",
MessageType.None);
}
private void RunSetup()
{
if (setupMode == SetupMode.FPS && !CharacterControllerSetupWizardUtility.HasFpsAddOn())
{
EditorUtility.DisplayDialog("Setup Wizard", "The FPS add-on is not imported. Switch to Core setup or import FPSFirstPerson.", "OK");
return;
}
GameObject player = ResolvePlayer();
if (!player)
return;
Undo.SetCurrentGroupName("Character Controller Setup Wizard");
int undoGroup = Undo.GetCurrentGroup();
PlayerController controller = ConfigureCore(player);
if (setupMode == SetupMode.FPS)
ConfigureFps(player);
Selection.activeGameObject = player;
EditorGUIUtility.PingObject(player);
EditorSceneManager.MarkSceneDirty(player.scene);
Undo.CollapseUndoOperations(undoGroup);
_lastResult = $"{setupMode} controller configured on '{player.name}'. Run Validate to review project-specific layer, input, and reference warnings.";
Repaint();
if (controller)
OpenValidatorForTarget();
}
private GameObject ResolvePlayer()
{
if (createNewPlayer)
{
GameObject player = new GameObject(setupMode == SetupMode.FPS ? "FPS Player" : "Motion Core Player");
Undo.RegisterCreatedObjectUndo(player, "Create Character Controller Player");
player.tag = CharacterControllerSetupWizardUtility.EnsureTag("Player") ? "Player" : player.tag;
player.transform.position = Vector3.zero;
targetPlayer = player;
return player;
}
if (targetPlayer)
return targetPlayer;
EditorUtility.DisplayDialog("Setup Wizard", "Assign a Target Player or enable Create New Player.", "OK");
return null;
}
private PlayerController ConfigureCore(GameObject player)
{
Rigidbody body = GetOrAddComponent<Rigidbody>(player);
CapsuleCollider capsule = GetOrAddComponent<CapsuleCollider>(player);
InputHandler inputHandler = GetOrAddComponent<InputHandler>(player);
PlayerController controller = GetOrAddComponent<PlayerController>(player);
ConfigureRigidbody(body);
ConfigureCapsule(capsule);
ConfigureInputHandler(inputHandler, setupMode == SetupMode.FPS);
ConfigurePlayerController(controller, body, inputHandler, capsule);
if (createCameraRig && setupMode == SetupMode.Core)
ConfigureThirdPersonCamera(player.transform);
return controller;
}
private void ConfigureRigidbody(Rigidbody body)
{
Undo.RecordObject(body, "Configure Character Rigidbody");
body.isKinematic = false;
body.useGravity = true;
body.freezeRotation = true;
body.interpolation = RigidbodyInterpolation.Interpolate;
body.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
EditorUtility.SetDirty(body);
}
private void ConfigureCapsule(CapsuleCollider capsule)
{
Undo.RecordObject(capsule, "Configure Character Capsule");
capsule.radius = 0.32f;
capsule.height = 1.8f;
capsule.center = new Vector3(0f, 0.9f, 0f);
capsule.direction = 1;
EditorUtility.SetDirty(capsule);
}
private void ConfigureInputHandler(InputHandler inputHandler, bool includeFpsInput)
{
SerializedObject serializedInput = new SerializedObject(inputHandler);
serializedInput.FindProperty("movementActionMapName").stringValue = "Control";
serializedInput.FindProperty("movementActionsAsset").objectReferenceValue = AssetDatabase.LoadAssetAtPath<InputActionAsset>(CoreInputPath);
SerializedProperty extensionAssets = serializedInput.FindProperty("extensionActionAssets");
if (includeFpsInput)
{
InputActionAsset fpsInput = AssetDatabase.LoadAssetAtPath<InputActionAsset>(FpsInputPath);
extensionAssets.arraySize = fpsInput ? 1 : 0;
if (fpsInput)
extensionAssets.GetArrayElementAtIndex(0).objectReferenceValue = fpsInput;
}
else
{
extensionAssets.arraySize = 0;
}
serializedInput.ApplyModifiedProperties();
EditorUtility.SetDirty(inputHandler);
}
private void ConfigurePlayerController(PlayerController controller, Rigidbody body, InputHandler inputHandler, CapsuleCollider capsule)
{
SerializedObject serializedController = new SerializedObject(controller);
serializedController.FindProperty("<RigidBody>k__BackingField").objectReferenceValue = body;
serializedController.FindProperty("<InputHandler>k__BackingField").objectReferenceValue = inputHandler;
serializedController.FindProperty("<CapsuleCollider>k__BackingField").objectReferenceValue = capsule;
serializedController.FindProperty("<MotorSettings>k__BackingField").objectReferenceValue =
AssetDatabase.LoadAssetAtPath<CharacterMotorSettings>(setupMode == SetupMode.FPS ? TacticalMotorSettingsPath : ParkourLiteMotorSettingsPath);
serializedController.FindProperty("<GroundLayerMask>k__BackingField").intValue = groundLayerMask.value != 0 ? groundLayerMask.value : LayerMask.GetMask("Default");
serializedController.FindProperty("<StairsLayerMask>k__BackingField").intValue = stairsLayerMask.value != 0 ? stairsLayerMask.value : LayerMask.GetMask("Default");
serializedController.FindProperty("<AlignToSlopeNormal>k__BackingField").boolValue = setupMode != SetupMode.FPS;
serializedController.ApplyModifiedProperties();
EditorUtility.SetDirty(controller);
}
private void ConfigureThirdPersonCamera(Transform player)
{
Camera camera = Camera.main;
if (!camera)
{
GameObject cameraObject = new GameObject("Character Camera");
Undo.RegisterCreatedObjectUndo(cameraObject, "Create Character Camera");
cameraObject.tag = "MainCamera";
cameraObject.transform.position = player.position + new Vector3(0f, 2.3f, -5f);
cameraObject.transform.rotation = Quaternion.Euler(18f, 0f, 0f);
camera = Undo.AddComponent<Camera>(cameraObject);
Undo.AddComponent<AudioListener>(cameraObject);
}
CameraFollow follow = camera.GetComponent<CameraFollow>() ?? Undo.AddComponent<CameraFollow>(camera.gameObject);
SerializedObject serializedFollow = new SerializedObject(follow);
serializedFollow.FindProperty("target").objectReferenceValue = player;
serializedFollow.FindProperty("autoFindTargetInScene").boolValue = false;
serializedFollow.ApplyModifiedProperties();
EditorUtility.SetDirty(follow);
}
private void ConfigureFps(GameObject player)
{
for (int i = 0; i < FpsComponentTypeNames.Length; i++)
CharacterControllerSetupWizardUtility.EnsureComponentByTypeName(player, FpsComponentTypeNames[i]);
Transform cameraRoot = createCameraRig ? EnsureChild(player.transform, "FPS Camera Root", new Vector3(0f, 1.55f, 0f)) : player.transform.Find("FPS Camera Root");
Camera camera = null;
if (createCameraRig && cameraRoot)
camera = EnsureFpsCamera(cameraRoot);
Transform weaponRoot = cameraRoot ? EnsureChild(cameraRoot, "FPS Weapon Root", new Vector3(0.2f, -0.22f, 0.55f)) : null;
AssignFpsObjectReference(player, "CharacterMovement.FPS.FpsCameraController", "cameraRoot", cameraRoot);
AssignFpsObjectReference(player, "CharacterMovement.FPS.FpsCameraController", "playerCamera", camera);
AssignFpsAssetReference(player, "CharacterMovement.FPS.FpsCameraController", "configuration", FpsCameraConfigPath);
AssignFpsObjectReference(player, "CharacterMovement.FPS.FPSViewMotion", "weaponRoot", weaponRoot);
AssignFpsAssetReference(player, "CharacterMovement.FPS.AdsController", "settings", FpsAdsSettingsPath);
AssignFpsAssetReference(player, "CharacterMovement.FPS.WeaponSwayController", "profile", FpsSwayProfilePath);
AssignFpsAssetReference(player, "CharacterMovement.FPS.RecoilController", "fallbackProfile", FpsRecoilProfilePath);
AssignFpsAssetReference(player, "CharacterMovement.FPS.FpsParkourController", "settings", FpsParkourSettingsPath);
AssignFpsAssetReference(player, "CharacterMovement.FPS.HitmarkerFeedbackController", "settings", FpsHitmarkerSettingsPath);
AssignFpsObjectReference(player, "CharacterMovement.FPS.WeaponManager", "weaponRoot", weaponRoot);
if (assignDemoFpsWeapon)
AssignFpsStartingWeapon(player);
}
private Camera EnsureFpsCamera(Transform cameraRoot)
{
Transform cameraTransform = cameraRoot.Find("FPS Camera");
GameObject cameraObject = cameraTransform ? cameraTransform.gameObject : new GameObject("FPS Camera");
if (!cameraTransform)
{
Undo.RegisterCreatedObjectUndo(cameraObject, "Create FPS Camera");
cameraObject.transform.SetParent(cameraRoot);
cameraObject.transform.localPosition = Vector3.zero;
cameraObject.transform.localRotation = Quaternion.identity;
}
cameraObject.tag = CharacterControllerSetupWizardUtility.EnsureTag("MainCamera") ? "MainCamera" : cameraObject.tag;
Camera camera = cameraObject.GetComponent<Camera>() ?? Undo.AddComponent<Camera>(cameraObject);
camera.fieldOfView = 72f;
camera.nearClipPlane = 0.03f;
if (!cameraObject.GetComponent<AudioListener>())
Undo.AddComponent<AudioListener>(cameraObject);
return camera;
}
private void AssignFpsStartingWeapon(GameObject player)
{
Component manager = CharacterControllerSetupWizardUtility.FindComponentByTypeName(player, "CharacterMovement.FPS.WeaponManager");
if (!manager)
return;
UnityEngine.Object rifle = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(FpsRifleDefinitionPath);
if (!rifle)
return;
SerializedObject serializedManager = new SerializedObject(manager);
SerializedProperty startingWeapons = serializedManager.FindProperty("startingWeapons");
if (startingWeapons == null || !startingWeapons.isArray)
return;
startingWeapons.arraySize = 1;
startingWeapons.GetArrayElementAtIndex(0).objectReferenceValue = rifle;
serializedManager.ApplyModifiedProperties();
EditorUtility.SetDirty(manager);
}
private void AssignFpsObjectReference(GameObject player, string typeName, string propertyName, UnityEngine.Object value)
{
if (!value)
return;
Component component = CharacterControllerSetupWizardUtility.FindComponentByTypeName(player, typeName);
if (!component)
return;
SerializedObject serializedObject = new SerializedObject(component);
SerializedProperty property = serializedObject.FindProperty(propertyName);
if (property == null)
return;
property.objectReferenceValue = value;
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(component);
}
private void AssignFpsAssetReference(GameObject player, string typeName, string propertyName, string assetPath)
{
UnityEngine.Object asset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath);
AssignFpsObjectReference(player, typeName, propertyName, asset);
}
private Transform EnsureChild(Transform parent, string childName, Vector3 localPosition)
{
Transform child = parent.Find(childName);
if (!child)
{
GameObject childObject = new GameObject(childName);
Undo.RegisterCreatedObjectUndo(childObject, "Create " + childName);
child = childObject.transform;
child.SetParent(parent);
}
child.localPosition = localPosition;
child.localRotation = Quaternion.identity;
child.localScale = Vector3.one;
return child;
}
private T GetOrAddComponent<T>(GameObject gameObject) where T : Component
{
T component = gameObject.GetComponent<T>();
return component ? component : Undo.AddComponent<T>(gameObject);
}
private void OpenValidatorForTarget()
{
if (targetPlayer)
Selection.activeGameObject = targetPlayer;
PlayerController controller = targetPlayer ? targetPlayer.GetComponentInParent<PlayerController>() : null;
if (controller)
CharacterControllerValidationWindow.OpenFor(controller);
else
CharacterControllerValidationWindow.Open();
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 0a19fa3bd51d41a3a8246d0c0df24f19
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CharacterControllerSetupWizard.cs
uploadId: 997018
@@ -0,0 +1,80 @@
using System;
using UnityEditor;
using UnityEngine;
namespace CharacterMovement.Editor
{
internal static class CharacterControllerSetupWizardUtility
{
public static bool HasFpsAddOn()
{
return AssetDatabase.IsValidFolder("Assets/Character Controller/FPSFirstPerson")
&& FindType("CharacterMovement.FPS.FPSModule") != null;
}
public static Component EnsureComponentByTypeName(GameObject gameObject, string typeName)
{
Type type = FindType(typeName);
if (type == null || !typeof(Component).IsAssignableFrom(type))
{
Debug.LogWarning($"[Motion Core Setup Wizard] Could not find component type '{typeName}'. Is the FPS add-on imported?");
return null;
}
Component existing = gameObject.GetComponent(type);
return existing ? existing : Undo.AddComponent(gameObject, type);
}
public static Component FindComponentByTypeName(GameObject gameObject, string typeName)
{
Type type = FindType(typeName);
return type != null ? gameObject.GetComponent(type) : null;
}
public static bool EnsureTag(string tag)
{
try
{
GameObject.FindGameObjectsWithTag(tag);
return true;
}
catch (UnityException)
{
return false;
}
}
public static LayerMask LayerMaskField(string label, LayerMask selected)
{
string[] layerNames = new string[32];
for (int i = 0; i < layerNames.Length; i++)
{
string layerName = LayerMask.LayerToName(i);
layerNames[i] = string.IsNullOrEmpty(layerName) ? $"Layer {i}" : layerName;
}
selected.value = EditorGUILayout.MaskField(label, selected.value, layerNames);
return selected;
}
private static Type FindType(string typeName)
{
Type type = Type.GetType(typeName + ", CharacterMovement.FPS");
if (type != null)
return type;
type = Type.GetType(typeName + ", CharacterMovement.Core");
if (type != null)
return type;
foreach (System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
type = assembly.GetType(typeName);
if (type != null)
return type;
}
return null;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 3dc95b4e0a5345cb8fc4c20d7db6859d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CharacterControllerSetupWizardUtility.cs
uploadId: 997018
@@ -0,0 +1,394 @@
using System;
using CharacterMovement;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
namespace CharacterMovement.Editor
{
public sealed partial class CharacterControllerValidationWindow
{
private const string FpsInputPath = "Assets/Character Controller/FPSFirstPerson/Input/FPSControls.inputactions";
private const string FpsCameraConfigPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoFpsCamera.asset";
private const string FpsAdsSettingsPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoAdsSettings.asset";
private const string FpsParkourSettingsPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoParkourSettings.asset";
private const string FpsRecoilProfilePath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoRifleRecoil.asset";
private const string FpsSwayProfilePath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoWeaponSway.asset";
private const string FpsRifleDefinitionPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoRifle.asset";
private const string FpsHitmarkerSettingsPath = "Assets/Character Controller/FPSFirstPerson/Examples/Data/DemoHitmarkerSettings.asset";
private const string FpsAnimationsFolder = "Assets/Character Controller/FPSFirstPerson/Examples/Animations";
private const string FpsAnimatorControllerPath = FpsAnimationsFolder + "/DemoLocomotion.controller";
private static readonly string[] RequiredFpsAnimationPaths =
{
FpsAnimatorControllerPath,
FpsAnimationsFolder + "/DemoBody_Idle.anim",
FpsAnimationsFolder + "/DemoBody_Crouch.anim",
FpsAnimationsFolder + "/DemoBody_Prone.anim",
FpsAnimationsFolder + "/DemoBody_GroundSlide.anim"
};
private static readonly string[] RequiredFpsActions =
{
"Look",
"Fire",
"Aim",
"Reload",
"Melee",
"Use",
"Weapon1",
"Weapon2",
"Weapon3",
"Weapon4"
};
private void ValidateFpsInput()
{
InputHandler inputHandler = targetController.GetComponent<InputHandler>();
if (!inputHandler || !HasFpsAddOnComponents(targetController.gameObject))
return;
SerializedObject input = new SerializedObject(inputHandler);
SerializedProperty extensionAssets = input.FindProperty("extensionActionAssets");
InputActionAsset fpsAsset = FindActionAssetWithMap(extensionAssets, "FPS");
if (fpsAsset)
{
ValidateActionMap(fpsAsset, "FPS", RequiredFpsActions, "FPS input");
return;
}
AddFix(
"FPS extension input asset is missing",
"The FPS add-on is present, but InputHandler does not reference an input asset with the FPS action map.",
() => AppendExtensionInputAsset(inputHandler, AssetDatabase.LoadAssetAtPath<InputActionAsset>(FpsInputPath)));
}
private void ValidateFpsDemoAssets()
{
if (!HasFpsAddOnComponents(targetController.gameObject) && !AssetDatabase.IsValidFolder("Assets/Character Controller/FPSFirstPerson"))
return;
for (int i = 0; i < RequiredFpsAnimationPaths.Length; i++)
{
if (!AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(RequiredFpsAnimationPaths[i]))
{
AddFix(
"FPS demo animation assets are missing",
"The FPS demo expects generated locomotion sample clips and an animator controller. Generate them before shipping or before opening the FPS demo scene.",
CreateFpsDemoAnimationAssets);
return;
}
}
}
private void ValidateFpsCamera()
{
Component cameraController = FindComponentByTypeName(targetController.gameObject, "FpsCameraController");
if (!cameraController)
return;
SerializedObject camera = new SerializedObject(cameraController);
SerializedProperty rootProperty = camera.FindProperty("cameraRoot");
SerializedProperty configProperty = camera.FindProperty("configuration");
if (configProperty != null && !configProperty.objectReferenceValue)
{
AddFix(
"FPS camera configuration is missing",
"FpsCameraController will create a runtime fallback config. Assign a camera config asset so the camera starts at the intended eye height.",
() => AssignSerializedObjectReference(cameraController, "configuration", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(FpsCameraConfigPath)));
}
Transform cameraRoot = rootProperty?.objectReferenceValue as Transform;
if (cameraRoot && cameraRoot.localPosition.y < 1.2f)
{
AddFix(
"FPS camera root is too low",
"The FPS camera root is below eye height and will feel like the camera starts near the player's feet.",
() =>
{
Undo.RecordObject(cameraRoot, "Fix FPS Camera Height");
Vector3 position = cameraRoot.localPosition;
position.y = 1.55f;
if (Mathf.Abs(position.z) < 0.001f)
position.z = 0.02f;
cameraRoot.localPosition = position;
EditorUtility.SetDirty(cameraRoot);
MarkSceneDirty();
});
}
UnityEngine.Object config = configProperty?.objectReferenceValue;
if (config)
ValidateFpsCameraConfigHeight(config);
}
private void ValidateFpsCameraConfigHeight(UnityEngine.Object config)
{
SerializedObject serializedConfig = new SerializedObject(config);
SerializedProperty cameraLocalPosition = serializedConfig.FindProperty("cameraLocalPosition");
if (cameraLocalPosition == null || cameraLocalPosition.vector3Value.y >= 1.2f)
return;
AddFix(
"FPS camera config eye height is too low",
"FpsCameraConfig.CameraLocalPosition is below a normal standing eye height for the included controller capsule.",
() =>
{
serializedConfig.Update();
SerializedProperty freshPosition = serializedConfig.FindProperty("cameraLocalPosition");
Vector3 position = freshPosition.vector3Value;
position.y = 1.55f;
if (Mathf.Abs(position.z) < 0.001f)
position.z = 0.02f;
freshPosition.vector3Value = position;
serializedConfig.ApplyModifiedProperties();
EditorUtility.SetDirty(config);
});
}
private void ValidateFpsDemoReferences()
{
if (!HasFpsAddOnComponents(targetController.gameObject))
return;
ValidateComponentObjectReference(
"AdsController",
"settings",
FpsAdsSettingsPath,
"FPS ADS settings are missing",
"AdsController will use runtime fallback values. Assign an ADS settings asset for predictable demo and project behavior.");
ValidateComponentObjectReference(
"FpsParkourController",
"settings",
FpsParkourSettingsPath,
"FPS parkour settings are missing",
"FpsParkourController will use runtime fallback values. Assign parkour settings so wall-run, mantle, vault, and ledge tuning are explicit.");
ValidateComponentObjectReference(
"RecoilController",
"fallbackProfile",
FpsRecoilProfilePath,
"FPS recoil profile is missing",
"RecoilController needs a fallback profile for weapons that do not override recoil.");
ValidateComponentObjectReference(
"WeaponSwayController",
"profile",
FpsSwayProfilePath,
"FPS weapon sway profile is missing",
"WeaponSwayController will use runtime fallback values. Assign a sway profile for predictable weapon presentation.");
ValidateComponentObjectReference(
"HitmarkerFeedbackController",
"settings",
FpsHitmarkerSettingsPath,
"FPS hitmarker settings are missing",
"HitmarkerFeedbackController will dispatch events, but visual/audio receivers need a settings asset for predictable feedback timing and colors.");
ValidateWeaponManagerLoadout();
}
private void ValidateFpsParkourSettings()
{
Component parkourController = FindComponentByTypeName(targetController.gameObject, "FpsParkourController");
if (!parkourController)
return;
SerializedObject serializedController = new SerializedObject(parkourController);
SerializedProperty settingsProperty = serializedController.FindProperty("settings");
UnityEngine.Object settings = settingsProperty?.objectReferenceValue;
if (!settings)
return;
SerializedObject serializedSettings = new SerializedObject(settings);
SerializedProperty parkourLayers = serializedSettings.FindProperty("parkourLayers");
if (parkourLayers != null && parkourLayers.intValue == 0)
{
AddFix(
"FPS parkour layer mask is empty",
"FpsParkourSettings.ParkourLayers is empty, so mantle, vault, ledge, and wall-run detection cannot find world geometry.",
() =>
{
SerializedObject freshSettings = new SerializedObject(settings);
SerializedProperty freshMask = freshSettings.FindProperty("parkourLayers");
if (freshMask != null)
{
int fallbackMask = targetController.GroundLayerMask.value != 0 ? targetController.GroundLayerMask.value : LayerMask.GetMask("Default");
freshMask.intValue = fallbackMask;
freshSettings.ApplyModifiedProperties();
EditorUtility.SetDirty(settings);
}
});
}
SerializedProperty controlledDownwardSpeed = serializedSettings.FindProperty("wallRunControlledDownwardSpeed");
SerializedProperty maximumDownwardSpeed = serializedSettings.FindProperty("maximumWallRunDownwardSpeed");
if (controlledDownwardSpeed != null
&& maximumDownwardSpeed != null
&& maximumDownwardSpeed.floatValue < controlledDownwardSpeed.floatValue)
{
AddFix(
"FPS wall-run downward speed limits conflict",
"MaximumWallRunDownwardSpeed must be greater than or equal to WallRunControlledDownwardSpeed, otherwise valid wall-runs can fail or end inconsistently.",
() => SetFloatProperty(settings, "maximumWallRunDownwardSpeed", Mathf.Max(0f, GetFloatProperty(settings, "wallRunControlledDownwardSpeed"))));
}
SerializedProperty startHeight = serializedSettings.FindProperty("minimumWallRunStartHeight");
SerializedProperty exitDistance = serializedSettings.FindProperty("wallRunGroundExitDistance");
if (startHeight != null
&& exitDistance != null
&& startHeight.floatValue < exitDistance.floatValue + 0.05f)
{
AddFix(
"FPS wall-run ground clearance values conflict",
"MinimumWallRunStartHeight should stay above WallRunGroundExitDistance so ground-level wall contact cannot become wall-walking.",
() => SetFloatProperty(settings, "minimumWallRunStartHeight", GetFloatProperty(settings, "wallRunGroundExitDistance") + 0.05f));
}
SerializedProperty minimumWallNormalY = serializedSettings.FindProperty("minimumWallNormalY");
SerializedProperty maximumWallNormalY = serializedSettings.FindProperty("maximumWallNormalY");
if (minimumWallNormalY != null
&& maximumWallNormalY != null
&& maximumWallNormalY.floatValue < minimumWallNormalY.floatValue)
{
AddFix(
"FPS wall-run normal range is invalid",
"MaximumWallNormalY must be greater than or equal to MinimumWallNormalY, otherwise no wall can satisfy the configured normal range.",
() => SetFloatProperty(settings, "maximumWallNormalY", GetFloatProperty(settings, "minimumWallNormalY")));
}
}
private void ValidateComponentObjectReference(string componentTypeName, string propertyName, string assetPath, string title, string description)
{
Component component = FindComponentByTypeName(targetController.gameObject, componentTypeName);
if (!component)
return;
SerializedObject serializedObject = new SerializedObject(component);
SerializedProperty property = serializedObject.FindProperty(propertyName);
if (property == null || property.objectReferenceValue)
return;
AddFix(title, description, () => AssignSerializedObjectReference(component, propertyName, AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath)));
}
private void ValidateWeaponManagerLoadout()
{
Component weaponManager = FindComponentByTypeName(targetController.gameObject, "WeaponManager");
if (!weaponManager)
return;
SerializedObject serializedObject = new SerializedObject(weaponManager);
SerializedProperty startingWeapons = serializedObject.FindProperty("startingWeapons");
bool missingFirstWeapon = startingWeapons == null
|| !startingWeapons.isArray
|| startingWeapons.arraySize == 0
|| !startingWeapons.GetArrayElementAtIndex(0).objectReferenceValue;
if (!missingFirstWeapon)
return;
AddFix(
"FPS starting weapon is missing",
"WeaponManager has no starting weapon, so the FPS demo starts unarmed.",
() => AssignFirstArrayObjectReference(weaponManager, "startingWeapons", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(FpsRifleDefinitionPath)));
}
private void AppendExtensionInputAsset(InputHandler inputHandler, InputActionAsset asset)
{
if (!asset)
{
Debug.LogWarning("[MotionCore Validator] FPS input asset was not found at " + FpsInputPath);
return;
}
SerializedObject input = new SerializedObject(inputHandler);
input.Update();
SerializedProperty array = input.FindProperty("extensionActionAssets");
if (array == null || !array.isArray)
return;
for (int i = 0; i < array.arraySize; i++)
{
if (array.GetArrayElementAtIndex(i).objectReferenceValue == asset)
return;
}
array.InsertArrayElementAtIndex(array.arraySize);
array.GetArrayElementAtIndex(array.arraySize - 1).objectReferenceValue = asset;
input.ApplyModifiedProperties();
EditorUtility.SetDirty(inputHandler);
MarkSceneDirty();
}
private void AssignFirstArrayObjectReference(UnityEngine.Object target, string propertyName, UnityEngine.Object value)
{
if (!value)
{
Debug.LogWarning("[MotionCore Validator] Asset was not found for array property '" + propertyName + "'.");
return;
}
SerializedObject serializedObject = new SerializedObject(target);
serializedObject.Update();
SerializedProperty property = serializedObject.FindProperty(propertyName);
if (property != null && property.isArray)
{
if (property.arraySize == 0)
property.arraySize = 1;
property.GetArrayElementAtIndex(0).objectReferenceValue = value;
}
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
MarkSceneDirty();
}
private static float GetFloatProperty(UnityEngine.Object target, string propertyName)
{
SerializedObject serializedObject = new SerializedObject(target);
SerializedProperty property = serializedObject.FindProperty(propertyName);
return property != null ? property.floatValue : 0f;
}
private static void SetFloatProperty(UnityEngine.Object target, string propertyName, float value)
{
SerializedObject serializedObject = new SerializedObject(target);
serializedObject.Update();
SerializedProperty property = serializedObject.FindProperty(propertyName);
if (property != null)
property.floatValue = value;
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
}
private static bool HasFpsAddOnComponents(GameObject gameObject)
{
Component[] components = gameObject.GetComponentsInChildren<Component>(true);
foreach (Component component in components)
{
if (!component)
continue;
Type componentType = component.GetType();
string namespaceName = componentType.Namespace ?? string.Empty;
if (namespaceName.StartsWith("CharacterMovement.FPS", StringComparison.Ordinal))
return true;
}
return false;
}
private void CreateFpsDemoAnimationAssets()
{
bool executed = EditorApplication.ExecuteMenuItem("Tools/Character Controller/Create FPS Demo Animation Assets");
if (!executed)
Debug.LogWarning("[MotionCore Validator] FPS demo animation generator menu item was not found.");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 0b431f80d0754d179e0529d966067c97
timeCreated: 1781733450
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CharacterControllerValidationWindow.Fps.cs
uploadId: 997018
@@ -0,0 +1,534 @@
using System;
using System.Collections.Generic;
using CharacterMovement;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.InputSystem;
namespace CharacterMovement.Editor
{
public sealed partial class CharacterControllerValidationWindow : EditorWindow
{
private const string CoreInputPath = "Assets/Character Controller/Core/Scripts/Input/Controls.inputactions";
private const string AnimatorParametersPath = "Assets/Character Controller/Core/Data/DefaultCharacterAnimatorParameters.asset";
private static readonly string[] RequiredCoreActions = { "Move", "Jump", "Crouch", "Prone", "Dash", "Walk", "Sprint" };
[SerializeField] private PlayerController targetController;
private readonly List<ValidationIssue> _issues = new List<ValidationIssue>();
private Vector2 _scroll;
[MenuItem("Tools/Character Controller/Validation Window")]
public static void Open()
{
GetWindow<CharacterControllerValidationWindow>("CC Validator");
}
public static void OpenFor(PlayerController controller)
{
CharacterControllerValidationWindow window = GetWindow<CharacterControllerValidationWindow>("CC Validator");
window.targetController = controller;
window.RebuildIssues();
window.Repaint();
}
private void OnEnable()
{
if (!targetController)
targetController = Selection.activeGameObject ? Selection.activeGameObject.GetComponentInParent<PlayerController>() : null;
RebuildIssues();
}
private void OnSelectionChange()
{
if (!targetController && Selection.activeGameObject)
{
targetController = Selection.activeGameObject.GetComponentInParent<PlayerController>();
RebuildIssues();
Repaint();
}
}
private void OnGUI()
{
EditorGUILayout.LabelField("Motion Core Character Controller Validation", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("Checks the selected controller for common setup errors. Fix buttons only apply deterministic, reversible scene or prefab edits.", MessageType.Info);
using (new EditorGUILayout.HorizontalScope())
{
EditorGUI.BeginChangeCheck();
targetController = (PlayerController)EditorGUILayout.ObjectField("Player Controller", targetController, typeof(PlayerController), true);
if (EditorGUI.EndChangeCheck())
RebuildIssues();
if (GUILayout.Button("Use Selection", GUILayout.Width(110f)))
{
targetController = Selection.activeGameObject ? Selection.activeGameObject.GetComponentInParent<PlayerController>() : null;
RebuildIssues();
}
}
using (new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button("Scan"))
RebuildIssues();
using (new EditorGUI.DisabledScope(!HasFixableIssues()))
{
if (GUILayout.Button("Apply Safe Fixes"))
{
ApplySafeFixes();
RebuildIssues();
}
}
if (GUILayout.Button("Copy Report"))
CopyValidationReport();
}
EditorGUILayout.Space(8f);
DrawIssues();
}
private void DrawIssues()
{
_scroll = EditorGUILayout.BeginScrollView(_scroll);
if (_issues.Count == 0)
{
EditorGUILayout.HelpBox("No issues found for the selected controller.", MessageType.Info);
EditorGUILayout.EndScrollView();
return;
}
foreach (ValidationIssue issue in _issues)
{
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
EditorGUILayout.LabelField(issue.Title, EditorStyles.boldLabel);
EditorGUILayout.LabelField(issue.Description, EditorStyles.wordWrappedLabel);
if (issue.Fix != null && GUILayout.Button(issue.FixLabel))
{
issue.Fix();
RebuildIssues();
GUIUtility.ExitGUI();
}
}
}
EditorGUILayout.EndScrollView();
}
private void RebuildIssues()
{
_issues.Clear();
if (!targetController)
{
_issues.Add(new ValidationIssue(
"No PlayerController selected",
"Select a GameObject with PlayerController, or press Use Selection after selecting the player root.",
null));
return;
}
ValidateRequiredComponents();
ValidateRigidbody();
ValidateCapsule();
ValidateLayerMasks();
ValidateCoreInput();
ValidateFpsInput();
ValidateFpsCamera();
ValidateCinemachineAdapters();
ValidateAnimatorBridge();
ValidateFpsDemoReferences();
ValidateFpsParkourSettings();
ValidateFpsDemoAssets();
}
private void ValidateRequiredComponents()
{
GameObject gameObject = targetController.gameObject;
SerializedObject controller = new SerializedObject(targetController);
if (!targetController.GetComponent<Rigidbody>())
AddFix("Missing Rigidbody", "PlayerController needs a Rigidbody on the same GameObject.", () => AddComponentAndAssign<Rigidbody>(gameObject, controller, "<RigidBody>k__BackingField"));
if (!targetController.GetComponent<CapsuleCollider>())
AddFix("Missing CapsuleCollider", "PlayerController needs a CapsuleCollider on the same GameObject.", () => AddComponentAndAssign<CapsuleCollider>(gameObject, controller, "<CapsuleCollider>k__BackingField"));
if (!targetController.GetComponent<InputHandler>())
AddFix("Missing InputHandler", "PlayerController needs an InputHandler on the same GameObject.", () => AddComponentAndAssign<InputHandler>(gameObject, controller, "<InputHandler>k__BackingField"));
AssignMissingReference<Rigidbody>(controller, "<RigidBody>k__BackingField", targetController.GetComponent<Rigidbody>(), "Rigidbody reference is not assigned.");
AssignMissingReference<CapsuleCollider>(controller, "<CapsuleCollider>k__BackingField", targetController.GetComponent<CapsuleCollider>(), "CapsuleCollider reference is not assigned.");
AssignMissingReference<InputHandler>(controller, "<InputHandler>k__BackingField", targetController.GetComponent<InputHandler>(), "InputHandler reference is not assigned.");
}
private void ValidateRigidbody()
{
Rigidbody body = targetController.GetComponent<Rigidbody>();
if (!body)
return;
if (!body.useGravity || body.isKinematic || !body.freezeRotation || body.interpolation == RigidbodyInterpolation.None)
{
AddFix(
"Rigidbody settings are not production-safe",
"Recommended settings: non-kinematic, Use Gravity on, Freeze Rotation on, Interpolate enabled.",
() =>
{
Undo.RecordObject(body, "Fix Rigidbody Settings");
body.isKinematic = false;
body.useGravity = true;
body.freezeRotation = true;
body.interpolation = RigidbodyInterpolation.Interpolate;
EditorUtility.SetDirty(body);
});
}
if (body.collisionDetectionMode == CollisionDetectionMode.Discrete)
{
AddFix(
"Rigidbody uses Discrete collision detection",
"Fast FPS controllers are less stable with Discrete collision detection. Continuous Dynamic is a safer default.",
() =>
{
Undo.RecordObject(body, "Set Continuous Collision Detection");
body.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
EditorUtility.SetDirty(body);
});
}
}
private void ValidateCapsule()
{
CapsuleCollider capsule = targetController.GetComponent<CapsuleCollider>();
if (!capsule)
return;
if (capsule.radius <= 0f || capsule.height <= 0f || capsule.height < capsule.radius * 2f)
{
AddFix(
"Capsule dimensions are invalid",
"Capsule height must be at least twice the radius, and both values must be positive.",
() =>
{
Undo.RecordObject(capsule, "Fix Capsule Dimensions");
capsule.radius = Mathf.Max(0.25f, capsule.radius);
capsule.height = Mathf.Max(1.8f, capsule.radius * 2f);
capsule.center = new Vector3(capsule.center.x, capsule.height * 0.5f, capsule.center.z);
EditorUtility.SetDirty(capsule);
});
}
if (targetController.CrouchCapsuleHeight >= capsule.height || targetController.ProneCapsuleHeight >= targetController.CrouchCapsuleHeight)
{
_issues.Add(new ValidationIssue(
"Stance heights need review",
"Expected Standing height > CrouchCapsuleHeight > ProneCapsuleHeight. Adjust the PlayerController stance fields or assign a motor preset.",
null));
}
}
private void ValidateLayerMasks()
{
SerializedObject controller = new SerializedObject(targetController);
SerializedProperty ground = controller.FindProperty("<GroundLayerMask>k__BackingField");
SerializedProperty stairs = controller.FindProperty("<StairsLayerMask>k__BackingField");
if (ground != null && ground.intValue == 0)
{
AddFix(
"GroundLayerMask is empty",
"Ground probes will not detect any surfaces.",
() => SetLayerMask("<GroundLayerMask>k__BackingField", LayerMask.GetMask("Default")));
}
if (stairs != null && stairs.intValue == 0)
{
AddFix(
"StairsLayerMask is empty",
"Step-up logic will not detect stair surfaces.",
() =>
{
int mask = targetController.GroundLayerMask.value != 0 ? targetController.GroundLayerMask.value : LayerMask.GetMask("Default");
SetLayerMask("<StairsLayerMask>k__BackingField", mask);
});
}
}
private void ValidateCoreInput()
{
InputHandler inputHandler = targetController.GetComponent<InputHandler>();
if (!inputHandler)
return;
SerializedObject input = new SerializedObject(inputHandler);
SerializedProperty assetProperty = input.FindProperty("movementActionsAsset");
SerializedProperty mapProperty = input.FindProperty("movementActionMapName");
InputActionAsset asset = assetProperty?.objectReferenceValue as InputActionAsset;
string mapName = string.IsNullOrWhiteSpace(mapProperty?.stringValue) ? "Control" : mapProperty.stringValue;
if (!asset)
{
AddFix(
"Core input asset is missing",
"InputHandler requires a core movement input asset.",
() => AssignInputAsset(inputHandler, "movementActionsAsset", AssetDatabase.LoadAssetAtPath<InputActionAsset>(CoreInputPath)));
return;
}
ValidateActionMap(asset, mapName, RequiredCoreActions, "Core input");
}
private void ValidateAnimatorBridge()
{
Component bridge = FindComponentByTypeName(targetController.gameObject, "CharacterAnimatorBridge");
if (!bridge)
return;
SerializedObject serializedBridge = new SerializedObject(bridge);
SerializedProperty parameters = serializedBridge.FindProperty("parameters");
if (parameters != null && !parameters.objectReferenceValue)
{
AddFix(
"Animator bridge parameter mapping is missing",
"CharacterAnimatorBridge is optional, but when present it should reference a CharacterAnimatorParameters asset so animation integrations work without source edits.",
() => AssignSerializedObjectReference(bridge, "parameters", AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(AnimatorParametersPath)));
}
}
private void ValidateCinemachineAdapters()
{
CharacterCinemachineAdapter[] adapters = FindCinemachineAdaptersInTargetScene();
for (int i = 0; i < adapters.Length; i++)
{
CharacterCinemachineAdapter adapter = adapters[i];
if (!adapter)
continue;
PlayerController adapterController = adapter.PlayerController;
if (adapterController && adapterController != targetController)
continue;
if (!adapter.ValidateTargetBindings(out string message))
{
_issues.Add(new ValidationIssue(
"Cinemachine adapter target binding needs review",
$"{adapter.name}: {message} Assign a supported Cinemachine camera component or disable Follow/LookAt assignment on the adapter.",
null));
}
}
}
private CharacterCinemachineAdapter[] FindCinemachineAdaptersInTargetScene()
{
if (!targetController || !targetController.gameObject.scene.IsValid())
return Array.Empty<CharacterCinemachineAdapter>();
List<CharacterCinemachineAdapter> adapters = new List<CharacterCinemachineAdapter>();
GameObject[] roots = targetController.gameObject.scene.GetRootGameObjects();
for (int i = 0; i < roots.Length; i++)
roots[i].GetComponentsInChildren(true, adapters);
return adapters.ToArray();
}
private void ValidateActionMap(InputActionAsset asset, string mapName, string[] requiredActions, string label)
{
InputActionMap map = asset.FindActionMap(mapName, throwIfNotFound: false);
if (map == null)
{
_issues.Add(new ValidationIssue(label + " map missing", $"Action map '{mapName}' was not found in '{asset.name}'.", null));
return;
}
foreach (string actionName in requiredActions)
{
if (map.FindAction(actionName, throwIfNotFound: false) == null)
_issues.Add(new ValidationIssue(label + " action missing", $"Action '{actionName}' was not found in map '{mapName}'.", null));
}
}
private InputActionAsset FindActionAssetWithMap(SerializedProperty arrayProperty, string mapName)
{
if (arrayProperty == null || !arrayProperty.isArray)
return null;
for (int i = 0; i < arrayProperty.arraySize; i++)
{
InputActionAsset asset = arrayProperty.GetArrayElementAtIndex(i).objectReferenceValue as InputActionAsset;
if (!asset)
continue;
InputActionMap map = asset.FindActionMap(mapName, throwIfNotFound: false);
if (map != null)
return asset;
}
return null;
}
private void AddFix(string title, string description, Action fix)
{
_issues.Add(new ValidationIssue(title, description, fix));
}
private void AssignMissingReference<T>(SerializedObject controller, string propertyName, T component, string description) where T : Component
{
SerializedProperty property = controller.FindProperty(propertyName);
if (property == null || property.objectReferenceValue || !component)
return;
AddFix(typeof(T).Name + " reference is empty", description, () =>
{
controller.Update();
SerializedProperty freshProperty = controller.FindProperty(propertyName);
freshProperty.objectReferenceValue = component;
controller.ApplyModifiedProperties();
EditorUtility.SetDirty(targetController);
});
}
private void AddComponentAndAssign<T>(GameObject gameObject, SerializedObject controller, string propertyName) where T : Component
{
Undo.RegisterCompleteObjectUndo(gameObject, "Add " + typeof(T).Name);
T component = Undo.AddComponent<T>(gameObject);
controller.Update();
SerializedProperty property = controller.FindProperty(propertyName);
if (property != null)
property.objectReferenceValue = component;
controller.ApplyModifiedProperties();
MarkSceneDirty();
}
private void SetLayerMask(string propertyName, int mask)
{
SerializedObject controller = new SerializedObject(targetController);
controller.Update();
SerializedProperty property = controller.FindProperty(propertyName);
if (property != null)
property.intValue = mask;
controller.ApplyModifiedProperties();
EditorUtility.SetDirty(targetController);
MarkSceneDirty();
}
private void AssignInputAsset(InputHandler inputHandler, string propertyName, InputActionAsset asset)
{
if (!asset)
{
Debug.LogWarning("[MotionCore Validator] Default input asset was not found at " + CoreInputPath);
return;
}
SerializedObject input = new SerializedObject(inputHandler);
input.Update();
SerializedProperty property = input.FindProperty(propertyName);
if (property != null)
property.objectReferenceValue = asset;
input.ApplyModifiedProperties();
EditorUtility.SetDirty(inputHandler);
MarkSceneDirty();
}
private void AssignSerializedObjectReference(UnityEngine.Object target, string propertyName, UnityEngine.Object value)
{
if (!value)
{
Debug.LogWarning("[MotionCore Validator] Asset was not found for property '" + propertyName + "'.");
return;
}
SerializedObject serializedObject = new SerializedObject(target);
serializedObject.Update();
SerializedProperty property = serializedObject.FindProperty(propertyName);
if (property != null)
property.objectReferenceValue = value;
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
MarkSceneDirty();
}
private void ApplySafeFixes()
{
ValidationIssue[] fixes = _issues.FindAll(issue => issue.Fix != null).ToArray();
foreach (ValidationIssue issue in fixes)
issue.Fix();
}
private bool HasFixableIssues()
{
foreach (ValidationIssue issue in _issues)
{
if (issue.Fix != null)
return true;
}
return false;
}
private void CopyValidationReport()
{
string targetName = targetController ? targetController.name : "None";
int fixableCount = 0;
for (int i = 0; i < _issues.Count; i++)
{
if (_issues[i].Fix != null)
fixableCount++;
}
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.AppendLine("Motion Core Validation Report");
builder.AppendLine("Target: " + targetName);
builder.AppendLine("Unity: " + Application.unityVersion);
builder.AppendLine("Issues: " + _issues.Count);
builder.AppendLine("Fixable: " + fixableCount);
for (int i = 0; i < _issues.Count; i++)
{
builder.AppendLine();
builder.AppendLine((i + 1) + ". " + _issues[i].Title);
builder.AppendLine(_issues[i].Description);
builder.AppendLine("Fixable: " + (_issues[i].Fix != null ? "Yes" : "No"));
}
EditorGUIUtility.systemCopyBuffer = builder.ToString();
}
private static Component FindComponentByTypeName(GameObject gameObject, string typeName)
{
Component[] components = gameObject.GetComponentsInChildren<Component>(true);
foreach (Component component in components)
{
if (component && component.GetType().Name == typeName)
return component;
}
return null;
}
private void MarkSceneDirty()
{
if (targetController && !EditorUtility.IsPersistent(targetController))
EditorSceneManager.MarkSceneDirty(targetController.gameObject.scene);
}
private sealed class ValidationIssue
{
public ValidationIssue(string title, string description, Action fix)
{
Title = title;
Description = description;
Fix = fix;
}
public string Title { get; }
public string Description { get; }
public Action Fix { get; }
public string FixLabel => "Fix";
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: e6c3c29ac05d4930b536cfc0e13da7d2
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CharacterControllerValidationWindow.cs
uploadId: 997018
@@ -0,0 +1,19 @@
{
"name": "CharacterMovement.Core.Editor",
"rootNamespace": "CharacterMovement.Editor",
"references": [
"CharacterMovement.Core",
"Unity.InputSystem"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": false,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: cbe188d68da94db4582ac04865474e57
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CharacterMovement.Core.Editor.asmdef
uploadId: 997018
@@ -0,0 +1,263 @@
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
namespace CharacterMovement.Editor
{
/// <summary>
/// Builds a correctly configured MotionCore character.
/// </summary>
/// <remarks>
/// One definition, used by both the shipped player prefab and the demo scene generator, so the
/// two cannot drift apart. The tuning here is the asset's "sounds good out of the box" baseline:
/// a character built from this should feel right before the user changes anything.
/// </remarks>
public static class CoreCharacterFactory
{
public const string PlayerPrefabPath = "Assets/Character Controller/Core/prefabs/Player.prefab";
private const string InputActionsPath = "Assets/Character Controller/Core/Scripts/Input/Controls.inputactions";
private const string AnimatorParametersPath =
"Assets/Character Controller/Core/Data/DefaultCharacterAnimatorParameters.asset";
private const float CapsuleHeight = 1.8f;
private const float CapsuleRadius = 0.3f;
[MenuItem("Tools/Character Controller/Rebuild Core Player Prefab")]
public static void RebuildPlayerPrefab()
{
GameObject character = CreateCharacter("MotionCore Character");
try
{
string directory = Path.GetDirectoryName(PlayerPrefabPath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
PrefabUtility.SaveAsPrefabAsset(character, PlayerPrefabPath);
AssetDatabase.SaveAssets();
Debug.Log($"[CharacterController] Rebuilt player prefab at '{PlayerPrefabPath}'.");
}
finally
{
Object.DestroyImmediate(character);
}
}
/// <summary>Command-line entry point so the prefab can be rebuilt in CI.</summary>
public static void RebuildPlayerPrefabFromCommandLine()
{
RebuildPlayerPrefab();
EditorApplication.Exit(0);
}
/// <summary>
/// Creates a ready-to-play character in the current scene. The caller owns the result.
/// </summary>
public static GameObject CreateCharacter(string characterName)
{
GameObject root = new GameObject(characterName)
{
layer = 0
};
if (InternalEditorTagExists("Player"))
root.tag = "Player";
CreateVisual(root.transform);
Rigidbody rigidbody = root.AddComponent<Rigidbody>();
rigidbody.mass = 70f;
rigidbody.freezeRotation = true;
rigidbody.useGravity = true;
rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
CapsuleCollider capsule = root.AddComponent<CapsuleCollider>();
capsule.height = CapsuleHeight;
capsule.radius = CapsuleRadius;
capsule.center = new Vector3(0f, CapsuleHeight * 0.5f, 0f);
InputHandler inputHandler = root.AddComponent<InputHandler>();
ConfigureInputHandler(inputHandler);
PlayerController controller = root.AddComponent<PlayerController>();
ConfigureController(controller, rigidbody, inputHandler, capsule);
CharacterAnimatorBridge bridge = root.AddComponent<CharacterAnimatorBridge>();
ConfigureAnimatorBridge(bridge, controller);
return root;
}
private static void CreateVisual(Transform parent)
{
GameObject visual = GameObject.CreatePrimitive(PrimitiveType.Capsule);
visual.name = "Visual";
visual.transform.SetParent(parent, false);
visual.transform.localPosition = new Vector3(0f, CapsuleHeight * 0.5f, 0f);
visual.transform.localScale = new Vector3(CapsuleRadius * 2f, CapsuleHeight * 0.5f, CapsuleRadius * 2f);
// The visual must not collide: grounding, step and clearance probes all use the capsule
// on the root, and a second collider here would fight them.
Object.DestroyImmediate(visual.GetComponent<Collider>());
GameObject facing = GameObject.CreatePrimitive(PrimitiveType.Cube);
facing.name = "Forward Marker";
facing.transform.SetParent(parent, false);
facing.transform.localPosition = new Vector3(0f, CapsuleHeight * 0.75f, CapsuleRadius);
facing.transform.localScale = new Vector3(0.12f, 0.12f, 0.2f);
Object.DestroyImmediate(facing.GetComponent<Collider>());
}
private static void ConfigureInputHandler(InputHandler inputHandler)
{
InputActionAsset inputAsset = AssetDatabase.LoadAssetAtPath<InputActionAsset>(InputActionsPath);
if (!inputAsset)
{
Debug.LogWarning(
$"[CharacterController] Input actions not found at '{InputActionsPath}'. "
+ "Assign an action asset on the InputHandler before playing.");
return;
}
SerializedObject serialized = new SerializedObject(inputHandler);
serialized.FindProperty("movementActionsAsset").objectReferenceValue = inputAsset;
serialized.FindProperty("movementActionMapName").stringValue = "Control";
serialized.ApplyModifiedPropertiesWithoutUndo();
}
private static void ConfigureController(
PlayerController controller,
Rigidbody rigidbody,
InputHandler inputHandler,
CapsuleCollider capsule)
{
SerializedObject serialized = new SerializedObject(controller);
SetObject(serialized, "<RigidBody>k__BackingField", rigidbody);
SetObject(serialized, "<InputHandler>k__BackingField", inputHandler);
SetObject(serialized, "<CapsuleCollider>k__BackingField", capsule);
// Movement
SetFloat(serialized, "<Speed>k__BackingField", 5f);
SetFloat(serialized, "<WalkSpeed>k__BackingField", 2.2f);
SetFloat(serialized, "<GroundAcceleration>k__BackingField", 45f);
SetFloat(serialized, "<GroundDeceleration>k__BackingField", 55f);
SetFloat(serialized, "<RotationDamping>k__BackingField", 12f);
// Sprint
SetEnum(serialized, "<SprintActivation>k__BackingField", (int)SprintActivationMode.Hold);
SetFloat(serialized, "<SprintSpeed>k__BackingField", 8f);
// Jump: a ~1.6m jump with forgiving buffers and tap-to-hop height control.
SetFloat(serialized, "<JumpingForce>k__BackingField", 6.5f);
SetBool(serialized, "<VariableJumpHeight>k__BackingField", true);
SetFloat(serialized, "<JumpCutMultiplier>k__BackingField", 0.45f);
SetBool(serialized, "<CanMoveWhileJumping>k__BackingField", true);
SetFloat(serialized, "<CoyoteTime>k__BackingField", 0.14f);
SetFloat(serialized, "<JumpBufferTime>k__BackingField", 0.14f);
SetFloat(serialized, "<ParkourBufferTime>k__BackingField", 0.14f);
SetFloat(serialized, "<AirAcceleration>k__BackingField", 14f);
SetFloat(serialized, "<AirDeceleration>k__BackingField", 2f);
// Gravity: a slightly heavy rise with a snappier fall reads as responsive rather than floaty.
SetFloat(serialized, "<GravityScale>k__BackingField", 1.15f);
SetFloat(serialized, "<FallGravityMultiplier>k__BackingField", 1.4f);
SetFloat(serialized, "<MaxFallSpeed>k__BackingField", 30f);
// Stance
SetFloat(serialized, "<CrouchSpeed>k__BackingField", 2.4f);
SetFloat(serialized, "<ProneSpeed>k__BackingField", 1.2f);
SetFloat(serialized, "<CrouchCapsuleHeight>k__BackingField", 1.15f);
SetFloat(serialized, "<ProneCapsuleHeight>k__BackingField", 0.55f);
SetFloat(serialized, "<StanceTransitionSpeed>k__BackingField", 14f);
SetFloat(serialized, "<CeilingCheckDistance>k__BackingField", 0.05f);
// Ground detection
SetInt(serialized, "<GroundLayerMask>k__BackingField", ~0);
SetInt(serialized, "<StairsLayerMask>k__BackingField", ~0);
SetFloat(serialized, "<GroundCheckDistance>k__BackingField", 0.15f);
SetFloat(serialized, "<GroundProbeRadiusScale>k__BackingField", 0.95f);
SetFloat(serialized, "<GroundSnapDistance>k__BackingField", 0.2f);
SetFloat(serialized, "<GroundStickForce>k__BackingField", 24f);
// Slopes and steps
SetFloat(serialized, "<MaxSlopeAngle>k__BackingField", 45f);
SetFloat(serialized, "<MaxStairsAngle>k__BackingField", 60f);
SetFloat(serialized, "<StepHeight>k__BackingField", 0.35f);
SetFloat(serialized, "<StepCheckDistance>k__BackingField", 0.22f);
SetFloat(serialized, "<StepProbeRadiusScale>k__BackingField", 0.85f);
SetFloat(serialized, "<UphillSlopeSpeedMultiplier>k__BackingField", 0.9f);
SetFloat(serialized, "<DownhillSlopeSpeedMultiplier>k__BackingField", 1.05f);
SetFloat(serialized, "<SlideForce>k__BackingField", 15f);
// Upright is the neutral choice; turn this on for third-person characters that should
// lean into slopes.
SetBool(serialized, "<AlignToSlopeNormal>k__BackingField", false);
SetFloat(serialized, "<Alignment>k__BackingField", 5f);
SetFloat(serialized, "<ExternalForceDrag>k__BackingField", 5f);
serialized.ApplyModifiedPropertiesWithoutUndo();
}
private static void ConfigureAnimatorBridge(CharacterAnimatorBridge bridge, PlayerController controller)
{
SerializedObject serialized = new SerializedObject(bridge);
SetObject(serialized, "playerController", controller);
CharacterAnimatorParameters parameters =
AssetDatabase.LoadAssetAtPath<CharacterAnimatorParameters>(AnimatorParametersPath);
if (parameters)
SetObject(serialized, "parameters", parameters);
serialized.ApplyModifiedPropertiesWithoutUndo();
}
private static bool InternalEditorTagExists(string tag)
{
foreach (string existing in UnityEditorInternal.InternalEditorUtility.tags)
{
if (existing == tag)
return true;
}
return false;
}
private static void SetFloat(SerializedObject serialized, string path, float value)
{
SerializedProperty property = serialized.FindProperty(path);
if (property != null)
property.floatValue = value;
}
private static void SetInt(SerializedObject serialized, string path, int value)
{
SerializedProperty property = serialized.FindProperty(path);
if (property != null)
property.intValue = value;
}
private static void SetEnum(SerializedObject serialized, string path, int value)
{
SerializedProperty property = serialized.FindProperty(path);
if (property != null)
property.enumValueIndex = value;
}
private static void SetBool(SerializedObject serialized, string path, bool value)
{
SerializedProperty property = serialized.FindProperty(path);
if (property != null)
property.boolValue = value;
}
private static void SetObject(SerializedObject serialized, string path, Object value)
{
SerializedProperty property = serialized.FindProperty(path);
if (property != null)
property.objectReferenceValue = value;
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: b5cb6bf7ca4a4345ac838aed91ee774e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CoreCharacterFactory.cs
uploadId: 997018
@@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace CharacterMovement.Editor
{
public static class CoreDemoSceneVerifier
{
private const string ScenePath = "Assets/Character Controller/Core/Scenes/DemoScene.unity";
[MenuItem("Tools/Character Controller/Verify Core Demo Scene")]
public static void Verify()
{
if (TryVerify(out string report))
{
Debug.Log(report);
return;
}
Debug.LogError(report);
if (!Application.isBatchMode)
EditorUtility.DisplayDialog("Core Demo Verification Failed", report, "OK");
}
public static void VerifyFromCommandLine()
{
if (!TryVerify(out string report))
throw new InvalidOperationException(report);
Debug.Log(report);
}
private static bool TryVerify(out string report)
{
List<string> failures = new List<string>();
if (!File.Exists(ScenePath))
{
failures.Add("Core demo scene file does not exist: " + ScenePath);
report = BuildReport(failures);
return false;
}
Scene scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);
DemoSceneVerificationUtility.AddMissingScriptFailures(scene, failures);
ValidateRequiredObjects(scene, failures);
ValidatePlayer(scene, failures);
ValidateCamera(scene, failures);
report = BuildReport(failures);
return failures.Count == 0;
}
private static void ValidateRequiredObjects(Scene scene, IList<string> failures)
{
DemoSceneVerificationUtility.RequireObject(scene, "Environment", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "Stairs", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "Ramp_Walkable", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "Slope_Steep", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "MovementGym", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "UnevenTerrain", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "LowCeiling", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "MovingPlatform_Test", failures, out GameObject movingPlatform);
DemoSceneVerificationUtility.RequireObject(scene, "Step_TooHigh", failures, out _);
DemoSceneVerificationUtility.RequireObject(scene, "HUD_Canvas", failures, out _);
if (movingPlatform)
{
DemoSceneVerificationUtility.RequireComponent(movingPlatform, "Core demo moving platform", failures, out MovingPlatform _);
DemoSceneVerificationUtility.RequireComponent(movingPlatform, "Core demo moving platform", failures, out DemoMovingPlatformMover _);
}
}
private static void ValidatePlayer(Scene scene, IList<string> failures)
{
if (!DemoSceneVerificationUtility.RequireObject(scene, "Player", failures, out GameObject player))
return;
DemoSceneVerificationUtility.RequireComponent(player, "Core demo player", failures, out Rigidbody rigidbody);
DemoSceneVerificationUtility.RequireComponent(player, "Core demo player", failures, out CapsuleCollider capsule);
DemoSceneVerificationUtility.RequireComponent(player, "Core demo player", failures, out InputHandler inputHandler);
DemoSceneVerificationUtility.RequireComponent(player, "Core demo player", failures, out DemoHudToggle _);
if (!DemoSceneVerificationUtility.RequireComponent(player, "Core demo player", failures, out PlayerController controller))
return;
if (DemoSceneVerificationUtility.GetObjectReference(controller, "<RigidBody>k__BackingField") != rigidbody)
failures.Add("Core demo PlayerController does not reference the generated Rigidbody.");
if (DemoSceneVerificationUtility.GetObjectReference(controller, "<InputHandler>k__BackingField") != inputHandler)
failures.Add("Core demo PlayerController does not reference the generated InputHandler.");
if (DemoSceneVerificationUtility.GetObjectReference(controller, "<CapsuleCollider>k__BackingField") != capsule)
failures.Add("Core demo PlayerController does not reference the generated CapsuleCollider.");
if (!DemoSceneVerificationUtility.GetObjectReference(controller, "<MotorSettings>k__BackingField"))
failures.Add("Core demo PlayerController does not reference a CharacterMotorSettings preset.");
if (!DemoSceneVerificationUtility.GetObjectReference(inputHandler, "movementActionsAsset"))
failures.Add("Core demo InputHandler does not reference Controls.inputactions.");
if (DemoSceneVerificationUtility.GetString(inputHandler, "movementActionMapName") != "Control")
failures.Add("Core demo InputHandler is not configured for the Control action map.");
}
private static void ValidateCamera(Scene scene, IList<string> failures)
{
if (!DemoSceneVerificationUtility.RequireObject(scene, "Main Camera", failures, out GameObject cameraObject))
return;
DemoSceneVerificationUtility.RequireComponent(cameraObject, "Core demo camera", failures, out Camera _);
if (!DemoSceneVerificationUtility.RequireComponent(cameraObject, "Core demo camera", failures, out CameraFollow follow))
return;
if (!DemoSceneVerificationUtility.GetObjectReference(follow, "target"))
failures.Add("Core demo CameraFollow target is not assigned.");
}
private static string BuildReport(IReadOnlyList<string> failures)
{
if (failures.Count == 0)
return "[CharacterController] Core demo scene verification passed.";
StringBuilder builder = new StringBuilder();
builder.AppendLine("[CharacterController] Core demo scene verification failed:");
for (int i = 0; i < failures.Count; i++)
builder.Append("- ").AppendLine(failures[i]);
return builder.ToString();
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 2dc7753c5b5bf67488050aed81209b9f
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/CoreDemoSceneVerifier.cs
uploadId: 997018
@@ -0,0 +1,472 @@
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;
namespace CharacterMovement.Editor
{
public static class DemoSceneSetup
{
private const string MatGround = "Assets/Character Controller/Core/Materials/GridWhite_01_Mat.mat";
private const string MatStairs = "Assets/Character Controller/Core/Materials/GridBlue_01_Mat.mat";
private const string MatRamp = "Assets/Character Controller/Core/Materials/GridOrange_01_Mat.mat";
private const string MatPlatform = "Assets/Character Controller/Core/Materials/GreyBlue_Mat.mat";
private const string MatJump = "Assets/Character Controller/Core/Materials/Blue_Mat.mat";
private const string ScenePath = "Assets/Character Controller/Core/Scenes/DemoScene.unity";
private const string CoreInputPath = "Assets/Character Controller/Core/Scripts/Input/Controls.inputactions";
private const string MotorSettingsPath = "Assets/Character Controller/Core/Data/ParkourLiteMotorSettings.asset";
private static Material _matGround, _matStairs, _matRamp, _matPlatform, _matJump;
[MenuItem("Tools/Character Controller/Build Demo Scene")]
public static void Build()
{
BuildInternal(!Application.isBatchMode);
}
public static void BuildFromCommandLine()
{
BuildInternal(false);
}
private static void BuildInternal(bool interactive)
{
if (interactive && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
return;
var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
LoadMaterials();
ConfigureLighting();
var env = new GameObject("Environment");
CreateGround(env.transform);
CreateStairs(env.transform);
CreateWalkableRamp(env.transform);
CreateSteepSlope(env.transform);
CreateLandingPlatform(env.transform);
CreateJumpSection(env.transform);
CreateMovementGym(env.transform);
CreateWalls(env.transform);
var player = CreatePlayer();
ConfigureCamera(player.transform);
CreateHUD();
Directory.CreateDirectory(Path.GetDirectoryName(ScenePath)!);
EditorSceneManager.SaveScene(scene, ScenePath);
AssetDatabase.Refresh();
Debug.Log("[CharacterController] Demo scene saved to: " + ScenePath);
if (interactive)
{
EditorUtility.DisplayDialog("Done", "Demo scene built!\n\n" + ScenePath, "Open it");
EditorSceneManager.OpenScene(ScenePath);
}
}
private static void LoadMaterials()
{
_matGround = AssetDatabase.LoadAssetAtPath<Material>(MatGround);
_matStairs = AssetDatabase.LoadAssetAtPath<Material>(MatStairs);
_matRamp = AssetDatabase.LoadAssetAtPath<Material>(MatRamp);
_matPlatform = AssetDatabase.LoadAssetAtPath<Material>(MatPlatform);
_matJump = AssetDatabase.LoadAssetAtPath<Material>(MatJump);
}
private static void ApplyMaterial(GameObject go, Material mat)
{
if (mat && go.TryGetComponent<Renderer>(out var r))
r.sharedMaterial = mat;
}
private static void ConfigureLighting()
{
var light = Object.FindAnyObjectByType<Light>();
if (light)
{
light.transform.rotation = Quaternion.Euler(50f, -30f, 0f);
light.intensity = 1.2f;
light.shadows = LightShadows.Soft;
}
RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat;
RenderSettings.ambientLight = new Color(0.25f, 0.28f, 0.35f);
}
private static void CreateGround(Transform parent)
{
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.name = "Ground";
go.transform.SetParent(parent);
go.transform.position = new Vector3(0f, -0.25f, 5f);
go.transform.localScale = new Vector3(30f, 0.5f, 28f);
ApplyMaterial(go, _matGround);
}
private static void CreateStairs(Transform parent)
{
const int steps = 10;
const float stepH = 0.30f;
const float stepD = 0.40f;
const float stepW = 5.00f;
const float startZ = 3.00f;
var root = new GameObject("Stairs");
root.transform.SetParent(parent);
for (int i = 0; i < steps; i++)
{
float solidH = (i + 1) * stepH;
float centerY = solidH * 0.5f;
float centerZ = startZ + (i + 0.5f) * stepD;
var step = GameObject.CreatePrimitive(PrimitiveType.Cube);
step.name = $"Step_{i:00}";
step.transform.SetParent(root.transform);
step.transform.position = new Vector3(0f, centerY, centerZ);
step.transform.localScale = new Vector3(stepW, solidH, stepD);
ApplyMaterial(step, _matStairs);
}
}
private static void CreateLandingPlatform(Transform parent)
{
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.name = "LandingPlatform";
go.transform.SetParent(parent);
go.transform.position = new Vector3(0f, 3.25f, 9.5f);
go.transform.localScale = new Vector3(7f, 0.5f, 5f);
ApplyMaterial(go, _matPlatform);
}
private static void CreateWalkableRamp(Transform parent)
{
const float rise = 3.0f;
const float run = 6.43f;
const float width = 5.0f;
const float thick = 0.3f;
float slant = Mathf.Sqrt(rise * rise + run * run);
float angle = Mathf.Atan2(rise, run) * Mathf.Rad2Deg;
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.name = "Ramp_Walkable";
go.transform.SetParent(parent);
go.transform.position = new Vector3(8f, rise * 0.5f, 3f + run * 0.5f);
go.transform.rotation = Quaternion.Euler(-angle, 0f, 0f);
go.transform.localScale = new Vector3(width, thick, slant);
ApplyMaterial(go, _matRamp);
CreateSignPost("Sign_WalkableRamp", new Vector3(8f, 4f, 3f),
"WALKABLE\nRAMP ~25 deg", parent);
}
private static void CreateSteepSlope(Transform parent)
{
const float rise = 3.0f;
const float run = 2.35f;
const float width = 5.0f;
const float thick = 0.3f;
float slant = Mathf.Sqrt(rise * rise + run * run);
float angle = Mathf.Atan2(rise, run) * Mathf.Rad2Deg;
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.name = "Slope_Steep";
go.transform.SetParent(parent);
go.transform.position = new Vector3(-8f, rise * 0.5f, 3f + run * 0.5f);
go.transform.rotation = Quaternion.Euler(-angle, 0f, 0f);
go.transform.localScale = new Vector3(width, thick, slant);
ApplyMaterial(go, _matRamp);
CreateSignPost("Sign_SteepSlope", new Vector3(-8f, 4f, 3f),
"STEEP SLOPE\n~52 deg (SLIDES)", parent);
}
private static void CreateJumpSection(Transform parent)
{
var root = new GameObject("JumpSection");
root.transform.SetParent(parent);
var ledge = GameObject.CreatePrimitive(PrimitiveType.Cube);
ledge.name = "Ledge";
ledge.transform.SetParent(root.transform);
ledge.transform.position = new Vector3(0f, 0.5f, -4f);
ledge.transform.localScale = new Vector3(6f, 1f, 4f);
ApplyMaterial(ledge, _matPlatform);
var near = GameObject.CreatePrimitive(PrimitiveType.Cube);
near.name = "Platform_Jump";
near.transform.SetParent(root.transform);
near.transform.position = new Vector3(0f, 0f, -10f);
near.transform.localScale = new Vector3(5f, 0.5f, 4f);
ApplyMaterial(near, _matJump);
var far = GameObject.CreatePrimitive(PrimitiveType.Cube);
far.name = "Platform_Dash";
far.transform.SetParent(root.transform);
far.transform.position = new Vector3(0f, 2f, -16f);
far.transform.localScale = new Vector3(5f, 0.5f, 4f);
ApplyMaterial(far, _matJump);
CreateSignPost("Sign_Jump", new Vector3(0f, 2f, -4f), "JUMP", root.transform);
CreateSignPost("Sign_Dash", new Vector3(0f, 3f, -16f), "JUMP\n+ DASH", root.transform);
}
private static void CreateMovementGym(Transform parent)
{
var root = new GameObject("MovementGym");
root.transform.SetParent(parent);
CreateSignPost("Sign_MovementGym", new Vector3(10.5f, 2.2f, -6.5f),
"MOVEMENT GYM\nUNEVEN / CEILING\nMOVING PLATFORM", root.transform);
CreateUnevenTerrain(root.transform);
CreateLowCeiling(root.transform);
CreateMovingPlatformLane(root.transform);
CreateTooHighStep(root.transform);
}
private static void CreateUnevenTerrain(Transform parent)
{
var root = new GameObject("UnevenTerrain");
root.transform.SetParent(parent);
for (int i = 0; i < 9; i++)
{
float x = 7.6f + (i % 3) * 0.85f;
float z = -5.4f + (i / 3) * 0.78f;
float height = 0.06f + (i % 4) * 0.04f;
var block = GameObject.CreatePrimitive(PrimitiveType.Cube);
block.name = $"Uneven_Block_{i + 1:00}";
block.transform.SetParent(root.transform);
block.transform.position = new Vector3(x, height * 0.5f, z);
block.transform.localScale = new Vector3(0.72f, height, 0.68f);
ApplyMaterial(block, _matGround);
}
}
private static void CreateLowCeiling(Transform parent)
{
var floor = GameObject.CreatePrimitive(PrimitiveType.Cube);
floor.name = "LowCeiling_Floor";
floor.transform.SetParent(parent);
floor.transform.position = new Vector3(12.5f, 0.03f, -2.5f);
floor.transform.localScale = new Vector3(3.2f, 0.06f, 2.4f);
ApplyMaterial(floor, _matGround);
var ceiling = GameObject.CreatePrimitive(PrimitiveType.Cube);
ceiling.name = "LowCeiling";
ceiling.transform.SetParent(parent);
ceiling.transform.position = new Vector3(12.5f, 1.55f, -2.5f);
ceiling.transform.localScale = new Vector3(3.2f, 0.16f, 2.4f);
ApplyMaterial(ceiling, _matPlatform);
CreateSignPost("Sign_LowCeiling", new Vector3(12.5f, 2.1f, -4.1f),
"CROUCH / PRONE\nSTAND BLOCKED", parent);
}
private static void CreateMovingPlatformLane(Transform parent)
{
var platform = GameObject.CreatePrimitive(PrimitiveType.Cube);
platform.name = "MovingPlatform_Test";
platform.transform.SetParent(parent);
platform.transform.position = new Vector3(10.5f, 0.1f, 2.5f);
platform.transform.localScale = new Vector3(2.5f, 0.2f, 2f);
ApplyMaterial(platform, _matPlatform);
var body = platform.AddComponent<Rigidbody>();
body.useGravity = false;
body.isKinematic = true;
platform.AddComponent<MovingPlatform>();
var mover = platform.AddComponent<DemoMovingPlatformMover>();
mover.LocalOffset = new Vector3(0f, 0f, 3f);
mover.Duration = 2.5f;
CreateSignPost("Sign_MovingPlatform", new Vector3(10.5f, 1.8f, 0.7f),
"MOVING PLATFORM\nCARRY TEST", parent);
}
private static void CreateTooHighStep(Transform parent)
{
var step = GameObject.CreatePrimitive(PrimitiveType.Cube);
step.name = "Step_TooHigh";
step.transform.SetParent(parent);
step.transform.position = new Vector3(13.8f, 0.35f, 2.6f);
step.transform.localScale = new Vector3(1.4f, 0.7f, 1f);
ApplyMaterial(step, _matStairs);
CreateSignPost("Sign_TooHighStep", new Vector3(13.8f, 1.5f, 1.3f),
"TOO HIGH\nSHOULD NOT STEP", parent);
}
private static void CreateWalls(Transform parent)
{
var root = new GameObject("BoundaryWalls");
root.transform.SetParent(parent);
CreateWall(root.transform, "Wall_North", new Vector3( 0f, 2f, 20f), new Vector3(30f, 4f, 0.5f));
CreateWall(root.transform, "Wall_South", new Vector3( 0f, 2f, -10f), new Vector3(30f, 4f, 0.5f));
CreateWall(root.transform, "Wall_East", new Vector3( 16f, 2f, 5f), new Vector3(0.5f, 4f, 32f));
CreateWall(root.transform, "Wall_West", new Vector3(-16f, 2f, 5f), new Vector3(0.5f, 4f, 32f));
}
private static void CreateWall(Transform parent, string wallName, Vector3 pos, Vector3 scale)
{
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.name = wallName;
go.transform.SetParent(parent);
go.transform.position = pos;
go.transform.localScale = scale;
if (go.TryGetComponent<Renderer>(out var r))
r.enabled = false;
}
private static void CreateSignPost(string goName, Vector3 pos, string text, Transform parent)
{
var sign = new GameObject(goName);
sign.transform.SetParent(parent);
sign.transform.position = pos;
var textGO = new GameObject("Label");
textGO.transform.SetParent(sign.transform);
textGO.transform.localPosition = Vector3.zero;
textGO.transform.localRotation = Quaternion.identity;
var label = textGO.AddComponent<TextMesh>();
label.text = text;
label.font = ResolveDefaultFont();
label.fontSize = 64;
label.characterSize = 0.07f;
label.anchor = TextAnchor.MiddleCenter;
label.alignment = TextAlignment.Center;
label.color = Color.white;
}
private static GameObject CreatePlayer()
{
// Built by the same factory as the shipped prefab, so the demo always demonstrates the
// configuration users actually get.
GameObject player = CoreCharacterFactory.CreateCharacter("Player");
var motorSettings = AssetDatabase.LoadAssetAtPath<CharacterMotorSettings>(MotorSettingsPath);
if (!motorSettings)
throw new FileNotFoundException("Core demo motor settings asset is missing.", MotorSettingsPath);
var controller = player.GetComponent<PlayerController>();
var so = new SerializedObject(controller);
so.FindProperty("<MotorSettings>k__BackingField").objectReferenceValue = motorSettings;
so.FindProperty("<GroundLayerMask>k__BackingField").intValue = LayerMask.GetMask("Default");
so.FindProperty("<StairsLayerMask>k__BackingField").intValue = LayerMask.GetMask("Default");
so.ApplyModifiedPropertiesWithoutUndo();
player.AddComponent<DemoHudToggle>();
player.transform.position = new Vector3(0f, 0.05f, 0f);
return player;
}
private static void ConfigureCamera(Transform playerTransform)
{
var cam = Camera.main;
if (!cam)
{
var camGO = new GameObject("Main Camera");
camGO.tag = "MainCamera";
cam = camGO.AddComponent<Camera>();
camGO.AddComponent<AudioListener>();
}
var follow = cam.gameObject.GetComponent<CameraFollow>()
?? cam.gameObject.AddComponent<CameraFollow>();
var so = new SerializedObject(follow);
var prop = so.FindProperty("target");
if (prop != null)
{
prop.objectReferenceValue = playerTransform;
so.ApplyModifiedPropertiesWithoutUndo();
}
cam.transform.position = new Vector3(0f, 5f, -8f);
cam.transform.rotation = Quaternion.Euler(20f, 0f, 0f);
}
private static void CreateHUD()
{
var esSys = new GameObject("EventSystem");
esSys.AddComponent<EventSystem>();
if (!esSys.TryGetComponent<InputSystemUIInputModule>(out _))
esSys.AddComponent<InputSystemUIInputModule>();
var canvasGO = new GameObject("HUD_Canvas");
var canvas = canvasGO.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
var scaler = canvasGO.AddComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920f, 1080f);
scaler.matchWidthOrHeight = 0.5f;
canvasGO.AddComponent<GraphicRaycaster>();
var labelGO = new GameObject("StateLabel");
labelGO.transform.SetParent(canvasGO.transform, false);
var label = labelGO.AddComponent<Text>();
label.text = "Runtime debug overlay is enabled by default";
label.font = ResolveDefaultFont();
label.fontSize = 28;
label.color = Color.white;
var rect = label.rectTransform;
rect.anchorMin = new Vector2(0f, 1f);
rect.anchorMax = new Vector2(0f, 1f);
rect.pivot = new Vector2(0f, 1f);
rect.anchoredPosition = new Vector2(24f, -24f);
rect.sizeDelta = new Vector2(620f, 60f);
var hintGO = new GameObject("ControlsHint");
hintGO.transform.SetParent(canvasGO.transform, false);
var hint = hintGO.AddComponent<Text>();
hint.text = "WASD - Move Shift - Sprint Alt - Walk\n" +
"Space - Jump E - Dash Ctrl - Crouch\n" +
"Mouse - Camera";
hint.font = ResolveDefaultFont();
hint.fontSize = 18;
hint.color = new Color(1f, 1f, 1f, 0.7f);
var hintRect = hint.rectTransform;
hintRect.anchorMin = new Vector2(0f, 0f);
hintRect.anchorMax = new Vector2(0f, 0f);
hintRect.pivot = new Vector2(0f, 0f);
hintRect.anchoredPosition = new Vector2(24f, 24f);
hintRect.sizeDelta = new Vector2(500f, 80f);
}
private static Font ResolveDefaultFont()
{
return Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf")
?? Resources.GetBuiltinResource<Font>("Arial.ttf");
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4190706f46fd5c5429635ce315991321
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/DemoSceneSetup.cs
uploadId: 997018
@@ -0,0 +1,129 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace CharacterMovement.Editor
{
public static class DemoSceneVerificationUtility
{
public static GameObject FindObject(Scene scene, string objectName)
{
GameObject[] roots = scene.GetRootGameObjects();
for (int i = 0; i < roots.Length; i++)
{
Transform[] transforms = roots[i].GetComponentsInChildren<Transform>(true);
for (int j = 0; j < transforms.Length; j++)
{
if (transforms[j].name == objectName)
return transforms[j].gameObject;
}
}
return null;
}
public static bool RequireObject(Scene scene, string objectName, IList<string> failures, out GameObject gameObject)
{
gameObject = FindObject(scene, objectName);
if (gameObject)
return true;
failures.Add($"Missing required scene object '{objectName}'.");
return false;
}
public static bool RequireComponent<T>(GameObject gameObject, string label, IList<string> failures, out T component)
where T : Component
{
component = gameObject ? gameObject.GetComponent<T>() : null;
if (component)
return true;
failures.Add($"{label} is missing required component {typeof(T).Name}.");
return false;
}
public static void AddMissingScriptFailures(Scene scene, IList<string> failures)
{
GameObject[] roots = scene.GetRootGameObjects();
for (int i = 0; i < roots.Length; i++)
{
Transform[] transforms = roots[i].GetComponentsInChildren<Transform>(true);
for (int j = 0; j < transforms.Length; j++)
{
Component[] components = transforms[j].GetComponents<Component>();
for (int k = 0; k < components.Length; k++)
{
if (!components[k])
failures.Add($"Missing script on {GetPath(transforms[j])}.");
}
}
}
}
public static Object GetObjectReference(Object target, string propertyName)
{
SerializedProperty property = FindProperty(target, propertyName);
return property?.objectReferenceValue;
}
public static string GetString(Object target, string propertyName)
{
SerializedProperty property = FindProperty(target, propertyName);
return property?.stringValue;
}
public static int GetArraySize(Object target, string propertyName)
{
SerializedProperty property = FindProperty(target, propertyName);
return property != null && property.isArray ? property.arraySize : 0;
}
public static Object GetArrayObjectReference(Object target, string propertyName, int index)
{
SerializedProperty property = FindProperty(target, propertyName);
if (property == null || !property.isArray || index < 0 || index >= property.arraySize)
return null;
return property.GetArrayElementAtIndex(index).objectReferenceValue;
}
public static bool GetBool(Object target, string propertyName)
{
SerializedProperty property = FindProperty(target, propertyName);
return property != null && property.boolValue;
}
public static float GetFloat(Object target, string propertyName)
{
SerializedProperty property = FindProperty(target, propertyName);
return property?.floatValue ?? 0f;
}
public static string GetPath(Transform transform)
{
if (!transform)
return "<null>";
string path = transform.name;
Transform parent = transform.parent;
while (parent)
{
path = parent.name + "/" + path;
parent = parent.parent;
}
return path;
}
private static SerializedProperty FindProperty(Object target, string propertyName)
{
if (!target)
return null;
SerializedObject serializedObject = new SerializedObject(target);
return serializedObject.FindProperty(propertyName);
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: af2c736a3495ccb42a7d371198631260
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/DemoSceneVerificationUtility.cs
uploadId: 997018
@@ -0,0 +1,75 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using CharacterMovement;
namespace CharacterMovement.Editor
{
[CustomEditor(typeof(InputHandler))]
public class InputHandlerEditor : UnityEditor.Editor
{
private readonly Dictionary<InputExtensionModule, bool> _foldouts = new();
public override void OnInspectorGUI()
{
DrawDefaultInspector();
var handler = (InputHandler)target;
var extensions = handler.GetComponents<InputExtensionModule>();
if (extensions.Length == 0) return;
EditorGUILayout.Space(8);
var headerStyle = new GUIStyle(EditorStyles.boldLabel) { fontSize = 11 };
EditorGUILayout.LabelField("Input Extensions", headerStyle);
EditorGUILayout.Space(2);
foreach (var extension in extensions)
{
if (!_foldouts.ContainsKey(extension))
_foldouts[extension] = true;
string typeName = extension.GetType().Name;
string label = ObjectNames.NicifyVariableName(typeName);
_foldouts[extension] = EditorGUILayout.Foldout(
_foldouts[extension],
label,
true,
EditorStyles.foldoutHeader);
var descriptionStyle = new GUIStyle(EditorStyles.miniLabel)
{
wordWrap = true,
normal = { textColor = new Color(0.6f, 0.6f, 0.6f) }
};
EditorGUI.indentLevel++;
EditorGUILayout.LabelField(
"This extension reads actions from maps assigned to InputHandler assets.",
descriptionStyle);
EditorGUI.indentLevel--;
if (!_foldouts[extension])
{
EditorGUILayout.Space(2);
continue;
}
EditorGUI.indentLevel++;
var serializedExtension = new SerializedObject(extension);
serializedExtension.Update();
var property = serializedExtension.GetIterator();
property.NextVisible(true);
while (property.NextVisible(false))
EditorGUILayout.PropertyField(property, true);
serializedExtension.ApplyModifiedProperties();
EditorGUI.indentLevel--;
EditorGUILayout.Space(4);
}
}
}
}
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: c6fb3056f51a6274a8c5bc1bf4b8c250
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/InputHandlerEditor.cs
uploadId: 997018
@@ -0,0 +1,416 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace CharacterMovement.Editor
{
/// <summary>
/// Groups the controller's settings into collapsible sections, surfaces configuration problems
/// as inline warnings, and shows live locomotion state during play.
/// </summary>
/// <remarks>
/// Sections are driven by the table below rather than by field declaration order, because the
/// controller is a partial class split across several files and the compiler's field order is not
/// something the inspector should depend on. Any serialized property not listed here still gets
/// drawn, under "Other", so a new field can never silently become invisible.
/// </remarks>
[CustomEditor(typeof(PlayerController))]
[CanEditMultipleObjects]
public class PlayerControllerEditor : UnityEditor.Editor
{
private const string FoldoutPrefKey = "MotionCore.PlayerControllerEditor.Section.";
private static readonly (string Title, bool ExpandedByDefault, string[] Properties)[] Sections =
{
("References", true, new[]
{
"<RigidBody>k__BackingField",
"<InputHandler>k__BackingField",
"<CapsuleCollider>k__BackingField",
"<PlayerAnimator>k__BackingField",
}),
("Preset", true, new[]
{
"<MotorSettings>k__BackingField",
}),
("Movement", true, new[]
{
"<Speed>k__BackingField",
"<WalkSpeed>k__BackingField",
"<GroundAcceleration>k__BackingField",
"<GroundDeceleration>k__BackingField",
"<RotationDamping>k__BackingField",
}),
("Sprint", true, new[]
{
"<AllowSprint>k__BackingField",
"<SprintActivation>k__BackingField",
"<SprintSpeed>k__BackingField",
}),
("Jump", true, new[]
{
"<AllowJump>k__BackingField",
"<JumpingForce>k__BackingField",
"<VariableJumpHeight>k__BackingField",
"<JumpCutMultiplier>k__BackingField",
"<CanMoveWhileJumping>k__BackingField",
"<CoyoteTime>k__BackingField",
"<JumpBufferTime>k__BackingField",
"<ParkourBufferTime>k__BackingField",
"<AirAcceleration>k__BackingField",
"<AirDeceleration>k__BackingField",
"<JumpGraceDuration>k__BackingField",
}),
("Gravity", true, new[]
{
"<GravityScale>k__BackingField",
"<FallGravityMultiplier>k__BackingField",
"<MaxFallSpeed>k__BackingField",
}),
("Crouch & Stance", false, new[]
{
"<AllowCrouch>k__BackingField",
"<AllowProne>k__BackingField",
"<CrouchSpeed>k__BackingField",
"<ProneSpeed>k__BackingField",
"<CrouchCapsuleHeight>k__BackingField",
"<ProneCapsuleHeight>k__BackingField",
"<StanceTransitionSpeed>k__BackingField",
"<CeilingCheckDistance>k__BackingField",
"<CeilingProbeRadiusScale>k__BackingField",
"<StanceClearanceRadiusScale>k__BackingField",
}),
("Ground Detection", false, new[]
{
"<GroundLayerMask>k__BackingField",
"<StairsLayerMask>k__BackingField",
"<GroundCheckDistance>k__BackingField",
"<GroundProbeRadiusScale>k__BackingField",
"<GroundSnapDistance>k__BackingField",
"<GroundStickForce>k__BackingField",
"<UseSupplementaryGroundRays>k__BackingField",
"<SupplementaryRaySpread>k__BackingField",
"<GroundProbeLiftOffset>k__BackingField",
"<GroundProbeEpsilon>k__BackingField",
}),
("Slopes & Steps", false, new[]
{
"<MaxSlopeAngle>k__BackingField",
"<MaxStairsAngle>k__BackingField",
"<StepHeight>k__BackingField",
"<StepCheckDistance>k__BackingField",
"<StepProbeRadiusScale>k__BackingField",
"<UphillSlopeSpeedMultiplier>k__BackingField",
"<DownhillSlopeSpeedMultiplier>k__BackingField",
"<SlideForce>k__BackingField",
"<AlignToSlopeNormal>k__BackingField",
"<Alignment>k__BackingField",
}),
("Abilities: Dash", false, new[]
{
"<AllowDash>k__BackingField",
"<DashDuration>k__BackingField",
"<DashLength>k__BackingField",
"<DashCooldownDuration>k__BackingField",
"<AirDashDownwardBoost>k__BackingField",
}),
("Abilities: Slide", false, new[]
{
"<AllowSlide>k__BackingField",
"<SlideDuration>k__BackingField",
"<SlideStartSpeed>k__BackingField",
"<SlideEndSpeed>k__BackingField",
"<SlideSteeringStrength>k__BackingField",
"<SlideCooldownDuration>k__BackingField",
"<MinimumSlideInputSpeed>k__BackingField",
"<MaxSlopeSlideSpeed>k__BackingField",
}),
("Abilities: Vault", false, new[]
{
"<AllowVault>k__BackingField",
"<VaultDuration>k__BackingField",
"<VaultArcHeight>k__BackingField",
"<VaultCooldownDuration>k__BackingField",
"<VaultForwardCheckDistance>k__BackingField",
"<VaultLandingForwardOffset>k__BackingField",
"<VaultMinHeight>k__BackingField",
"<VaultMaxHeight>k__BackingField",
"<VaultProbeRadiusScale>k__BackingField",
"<VaultGroundOffset>k__BackingField",
}),
("Camera", false, new[]
{
"mainCameraTransform",
"autoFindMainCamera",
"mainCameraRefreshInterval",
"lockCursorOnStart",
}),
("Advanced", false, new[]
{
"inputSourceBehaviour",
"<ExternalForceDrag>k__BackingField",
"movementEventSpeedThreshold",
"<AirborneLaunchVelocityThreshold>k__BackingField",
"<FallDetectionVelocityThreshold>k__BackingField",
"<ConfigureRigidbodyOnStart>k__BackingField",
"<RigidbodyInterpolation>k__BackingField",
"<RigidbodyCollisionDetection>k__BackingField",
}),
("Debug", false, new[]
{
"_enableDebugTools",
"_showDebugOverlay",
"_stateLabel",
"_drawGizmosWhenNotSelected",
"_drawGroundProbeGizmos",
"_drawStepUpGizmos",
"_drawVelocityGizmos",
"_drawMovementGizmos",
"_drawSurfaceNormalGizmos",
"_debugVectorScale",
"_groundHitColor",
"_groundMissColor",
"_stepUpColor",
"_velocityColor",
"_movementColor",
}),
};
private readonly List<string> _validationErrors = new List<string>();
private readonly List<string> _validationWarnings = new List<string>();
private readonly List<string> _validationInfo = new List<string>();
private readonly HashSet<string> _drawnProperties = new HashSet<string>();
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawValidation();
_drawnProperties.Clear();
_drawnProperties.Add("m_Script");
foreach ((string title, bool expandedByDefault, string[] properties) in Sections)
DrawSection(title, expandedByDefault, properties);
DrawRemainingProperties();
DrawRuntimeState();
serializedObject.ApplyModifiedProperties();
}
private void DrawSection(string title, bool expandedByDefault, string[] propertyNames)
{
List<SerializedProperty> properties = new List<SerializedProperty>(propertyNames.Length);
foreach (string propertyName in propertyNames)
{
// Properties can be absent behind compile flags (the TextMeshPro state label) or on
// a future version of the controller. Skipping them keeps the inspector working.
SerializedProperty property = serializedObject.FindProperty(propertyName);
if (property == null)
continue;
properties.Add(property);
_drawnProperties.Add(propertyName);
}
if (properties.Count == 0)
return;
string prefKey = FoldoutPrefKey + title;
bool expanded = EditorPrefs.GetBool(prefKey, expandedByDefault);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
bool nextExpanded = EditorGUILayout.Foldout(expanded, title, true, EditorStyles.foldoutHeader);
if (nextExpanded != expanded)
EditorPrefs.SetBool(prefKey, nextExpanded);
if (nextExpanded)
{
EditorGUI.indentLevel++;
foreach (SerializedProperty property in properties)
EditorGUILayout.PropertyField(property, true);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndVertical();
}
private void DrawRemainingProperties()
{
List<SerializedProperty> remaining = new List<SerializedProperty>();
SerializedProperty iterator = serializedObject.GetIterator();
bool enterChildren = true;
while (iterator.NextVisible(enterChildren))
{
enterChildren = false;
if (!_drawnProperties.Contains(iterator.name))
remaining.Add(iterator.Copy());
}
if (remaining.Count == 0)
return;
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUILayout.LabelField("Other", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
foreach (SerializedProperty property in remaining)
EditorGUILayout.PropertyField(property, true);
EditorGUI.indentLevel--;
EditorGUILayout.EndVertical();
}
private void DrawValidation()
{
_validationErrors.Clear();
_validationWarnings.Clear();
_validationInfo.Clear();
foreach (UnityEngine.Object targetObject in targets)
{
if (targetObject is PlayerController controller)
Validate(controller);
}
foreach (string message in _validationErrors)
EditorGUILayout.HelpBox(message, MessageType.Error);
foreach (string message in _validationWarnings)
EditorGUILayout.HelpBox(message, MessageType.Warning);
foreach (string message in _validationInfo)
EditorGUILayout.HelpBox(message, MessageType.Info);
if (_validationErrors.Count > 0 || _validationWarnings.Count > 0 || _validationInfo.Count > 0)
EditorGUILayout.Space(2f);
}
private void Validate(PlayerController controller)
{
if (controller.GroundLayerMask.value == 0)
{
AddWarning("Ground Layer Mask is empty. The character will fall through the world "
+ "unless it is set; Default is used as a fallback at runtime.");
}
if (controller.SprintSpeed < controller.Speed)
AddWarning("Sprint Speed is lower than Speed, so sprinting will slow the character down.");
if (controller.WalkSpeed > controller.Speed)
AddWarning("Walk Speed is higher than Speed, so walking will be faster than running.");
if (controller.MaxStairsAngle < controller.MaxSlopeAngle)
{
AddWarning("Max Stairs Angle is below Max Slope Angle. Stairs are meant to be more "
+ "forgiving than slopes, so this is usually the wrong way round.");
}
CapsuleCollider capsule = controller.CapsuleCollider
? controller.CapsuleCollider
: controller.GetComponent<CapsuleCollider>();
if (!capsule)
{
AddInfo("No CapsuleCollider assigned. One will be added automatically at runtime, but "
+ "assigning it lets the editor validate heights and clearances.");
}
else
{
if (controller.CrouchCapsuleHeight >= capsule.height)
{
AddWarning($"Crouch Capsule Height ({controller.CrouchCapsuleHeight:0.##}) is not "
+ $"lower than the standing height ({capsule.height:0.##}), so crouching "
+ "will not fit under anything the character cannot already walk under.");
}
if (controller.ProneCapsuleHeight > controller.CrouchCapsuleHeight)
AddWarning("Prone Capsule Height is taller than Crouch Capsule Height.");
if (controller.VaultMaxHeight >= capsule.height)
{
AddWarning("Vault Max Height is at or above the standing capsule height. Obstacles "
+ "that tall should usually be climbed rather than vaulted.");
}
if (controller.StepHeight > capsule.height * 0.5f)
{
AddWarning("Step Height is more than half the capsule height, which lets the "
+ "character climb walls it should have to jump.");
}
}
if (!controller.GetComponent<InputHandler>() && !controller.InputHandler)
{
AddInfo("No InputHandler found. One will be added automatically at runtime, or you can "
+ "assign your own ICharacterInputSource under Advanced.");
}
if (!controller.AllowJump && !controller.AllowCrouch && !controller.AllowSprint)
{
AddInfo("Sprint, jump and crouch are all disabled. This character can only walk, "
+ "which is fine for NPCs but is usually a mistake on a player character.");
}
if (controller.MotorSettings)
{
AddInfo($"A motor preset ('{controller.MotorSettings.name}') is assigned. It drives "
+ "how movement feels (speeds, acceleration, jump arc, gravity, slopes, "
+ "ground probing) and overwrites those fields on validate and on start. "
+ "Edit the preset asset to change the feel, or clear the field to tune "
+ "this character directly. Ability toggles such as Allow Jump and Allow "
+ "Dash, and Sprint Activation, are deliberately not part of a preset, so "
+ "they stay yours to set per character.");
}
}
private void AddError(string message)
{
if (!_validationErrors.Contains(message))
_validationErrors.Add(message);
}
private void AddWarning(string message)
{
if (!_validationWarnings.Contains(message))
_validationWarnings.Add(message);
}
private void AddInfo(string message)
{
if (!_validationInfo.Contains(message))
_validationInfo.Add(message);
}
private void DrawRuntimeState()
{
if (!Application.isPlaying || targets.Length != 1)
return;
PlayerController controller = target as PlayerController;
if (!controller)
return;
EditorGUILayout.Space(4f);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUILayout.LabelField("Live State", EditorStyles.boldLabel);
using (new EditorGUI.DisabledScope(true))
{
EditorGUILayout.EnumPopup("Movement State", controller.MovementState);
EditorGUILayout.EnumPopup("Stance", controller.CurrentStance);
EditorGUILayout.Toggle("Grounded", controller.IsGrounded());
EditorGUILayout.FloatField("Ground Angle", controller.GroundAngle);
EditorGUILayout.FloatField("Planar Speed", controller.GetPlanarSpeed());
EditorGUILayout.FloatField("Vertical Velocity", controller.VerticalVelocity);
EditorGUILayout.FloatField("Speed Multiplier", controller.EffectiveSpeedMultiplier);
EditorGUILayout.IntField("Movement Modifiers", controller.MovementModifierCount);
EditorGUILayout.TextField(
"Blocked",
controller.BlockedCapabilities == MovementCapability.None
? "Nothing"
: controller.BlockedCapabilities.ToString());
}
EditorGUILayout.EndVertical();
Repaint();
}
}
}
@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 080b24f211064494a50c055951234b7d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 367142
packageName: "MotionCore \u2013 Physics Character Controller"
packageVersion: 1.2
assetPath: Assets/Character Controller/Core/Editor/PlayerControllerEditor.cs
uploadId: 997018