diff --git a/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/BeeBuildProgramCommon.Data.gen.csproj b/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/BeeBuildProgramCommon.Data.gen.csproj
index ef251769b5..d6607763d0 100644
--- a/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/BeeBuildProgramCommon.Data.gen.csproj
+++ b/Editor/IncrementalBuildPipeline/BeeBuildProgramCommon.Data/BeeBuildProgramCommon.Data.gen.csproj
@@ -19,11 +19,15 @@
falsefalse
+
+ $(HOME)
+ $(USERPROFILE)
+
-
+
diff --git a/Editor/IncrementalBuildPipeline/PlayerBuildProgramLibrary.Data/PlayerBuildProgramLibrary.Data.gen.csproj b/Editor/IncrementalBuildPipeline/PlayerBuildProgramLibrary.Data/PlayerBuildProgramLibrary.Data.gen.csproj
index 1d221ff092..df912dba35 100644
--- a/Editor/IncrementalBuildPipeline/PlayerBuildProgramLibrary.Data/PlayerBuildProgramLibrary.Data.gen.csproj
+++ b/Editor/IncrementalBuildPipeline/PlayerBuildProgramLibrary.Data/PlayerBuildProgramLibrary.Data.gen.csproj
@@ -20,12 +20,16 @@
falsePlayerBuildProgramLibrary.Data
+
+ $(HOME)
+ $(USERPROFILE)
+
-
+
diff --git a/Editor/IncrementalBuildPipeline/ScriptCompilationBuildProgram.Data/ScriptCompilationBuildProgram.Data.gen.csproj b/Editor/IncrementalBuildPipeline/ScriptCompilationBuildProgram.Data/ScriptCompilationBuildProgram.Data.gen.csproj
index 19b9d56861..bbe27600d3 100644
--- a/Editor/IncrementalBuildPipeline/ScriptCompilationBuildProgram.Data/ScriptCompilationBuildProgram.Data.gen.csproj
+++ b/Editor/IncrementalBuildPipeline/ScriptCompilationBuildProgram.Data/ScriptCompilationBuildProgram.Data.gen.csproj
@@ -19,12 +19,16 @@
falsefalse
+
+ $(HOME)
+ $(USERPROFILE)
+
-
+
diff --git a/Editor/Mono/2D/SpriteAtlas/EditorSpriteAtlas.bindings.cs b/Editor/Mono/2D/SpriteAtlas/EditorSpriteAtlas.bindings.cs
index febe5c2d84..95d2a717df 100644
--- a/Editor/Mono/2D/SpriteAtlas/EditorSpriteAtlas.bindings.cs
+++ b/Editor/Mono/2D/SpriteAtlas/EditorSpriteAtlas.bindings.cs
@@ -37,6 +37,9 @@ public static void PackAtlases(SpriteAtlas[] atlases, BuildTarget target, bool c
[FreeFunction("SpriteAtlasExtensions::CleanupAtlasPacking")]
extern public static void CleanupAtlasPacking();
+
+ [FreeFunction("SpriteAtlasExtensions::OnSpriteAtlasSettingsChanged")]
+ extern internal static void OnSpriteAtlasSettingsChanged();
}
diff --git a/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs b/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs
index 9fde0c7d30..2d61e1d87a 100644
--- a/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs
+++ b/Editor/Mono/2D/SpriteAtlas/SpriteAtlasImporterInspector.cs
@@ -317,6 +317,8 @@ private SerializedObject GetSerializedAssetObject()
public override void OnEnable()
{
base.OnEnable();
+ if (!AreImporterTargetsValid()) // asset gone: base already logged and bailed
+ return;
m_FilterMode = serializedObject.FindProperty("m_TextureSettings.filterMode");
m_AnisoLevel = serializedObject.FindProperty("m_TextureSettings.anisoLevel");
diff --git a/Editor/Mono/Animation/AnimationEventWrapperInspector.cs b/Editor/Mono/Animation/AnimationEventWrapperInspector.cs
index ed34a5f4f1..fb530ee5ff 100644
--- a/Editor/Mono/Animation/AnimationEventWrapperInspector.cs
+++ b/Editor/Mono/Animation/AnimationEventWrapperInspector.cs
@@ -101,16 +101,21 @@ public static void OnEditAnimationEvents(AnimationEventWrapper[] awEvents, Anima
EditorGUIUtility.labelWidth = 130;
EditorGUI.showMixedValue = !singleFunctionName;
- int wasSelected = singleFunctionName ? selected : -1;
+
+ EditorGUI.BeginChangeCheck();
selected = EditorGUILayout.Popup("Function: ", selected, methodsFormatted);
- if (wasSelected != selected && selected != -1 && selected != notSupportedIndex)
+ if (EditorGUI.EndChangeCheck())
{
- foreach (var evt in data.selectedEvents)
+ if (selected >= 0 && selected < notSupportedIndex)
{
- evt.functionName = supportedMethods[selected].Name;
- evt.stringParameter = string.Empty;
+ foreach (var evt in data.selectedEvents)
+ {
+ evt.functionName = supportedMethods[selected].Name;
+ evt.stringParameter = string.Empty;
+ }
}
}
+
EditorGUI.showMixedValue = false;
EditorGUI.indentLevel++;
@@ -134,7 +139,7 @@ public static void OnEditAnimationEvents(AnimationEventWrapper[] awEvents, Anima
if (singleFunctionName && selectedParameter != null)
{
EditorGUILayout.Space();
- if (selectedParameter == typeof(AnimationEvent))
+ if (IsEventDataType(selectedParameter))
EditorGUILayout.PrefixLabel("Event Data");
else
EditorGUILayout.PrefixLabel("Parameters");
@@ -268,7 +273,7 @@ public static void OnDisabledAnimationEvent()
static Dictionary> s_TypeAnimationMethodMapCache = new Dictionary>();
- static void CollectSupportedMethods(GameObject gameObject, List supportedMethods, List overloadedMethods, List duplicatedMethods)
+ internal static void CollectSupportedMethods(GameObject gameObject, List supportedMethods, List overloadedMethods, List duplicatedMethods)
{
if (gameObject == null)
return;
@@ -307,7 +312,7 @@ static void CollectSupportedMethods(GameObject gameObject, List
///
- struct AnimationMethodMap
+ internal struct AnimationMethodMap
{
public Object sourceBehaviour;
public MethodInfo methodInfo;
@@ -418,8 +423,9 @@ public static string FormatEvent(GameObject root, AnimationEvent evt)
private static void DoEditRegularParameters(AnimationEvent[] events, Type selectedParameter)
{
AnimationEvent firstEvent = events[0];
+ bool isEventData = IsEventDataType(selectedParameter);
- if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(float))
+ if (isEventData || selectedParameter == typeof(float))
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.floatParameter == firstEvent.floatParameter);
@@ -435,7 +441,7 @@ private static void DoEditRegularParameters(AnimationEvent[] events, Type select
}
}
- if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(int) || selectedParameter.IsEnum)
+ if (isEventData || selectedParameter == typeof(int) || selectedParameter.IsEnum)
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.intParameter == firstEvent.intParameter);
@@ -455,7 +461,7 @@ private static void DoEditRegularParameters(AnimationEvent[] events, Type select
}
}
- if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(string))
+ if (isEventData || selectedParameter == typeof(string))
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.stringParameter == firstEvent.stringParameter);
@@ -471,13 +477,13 @@ private static void DoEditRegularParameters(AnimationEvent[] events, Type select
}
}
- if (selectedParameter == typeof(AnimationEvent) || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object))
+ if (isEventData || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object))
{
bool singleParamValue = Array.TrueForAll(events, evt => evt.objectReferenceParameter == firstEvent.objectReferenceParameter);
EditorGUI.BeginChangeCheck();
Type type = typeof(UnityEngine.Object);
- if (selectedParameter != typeof(AnimationEvent))
+ if (!isEventData)
type = selectedParameter;
EditorGUI.showMixedValue = !singleParamValue;
@@ -512,6 +518,11 @@ private static int EnumPopup(string label, Type enumType, int selected)
}
}
+ private static bool IsEventDataType(Type type)
+ {
+ return type == typeof(AnimationEvent) || type == typeof(AnimationEventInfo);
+ }
+
private static bool IsSupportedMethodName(string name)
{
return name != "Main" && name != "Start" && name != "Awake" && name != "Update";
@@ -539,7 +550,7 @@ private static string FormatEventArguments(ParameterInfo[] paramTypes, Animation
if (paramType.IsEnum)
return " ( " + paramType.Name + "." + Enum.GetName(paramType, evt.intParameter) + " )";
- if (paramType == typeof(AnimationEvent))
+ if (IsEventDataType(paramType))
return " ( "
+ evt.floatParameter + " / "
+ evt.intParameter + " / \""
diff --git a/Editor/Mono/Animation/AnimationUtility.bindings.cs b/Editor/Mono/Animation/AnimationUtility.bindings.cs
index 63b1c091ce..3e17ddecd8 100644
--- a/Editor/Mono/Animation/AnimationUtility.bindings.cs
+++ b/Editor/Mono/Animation/AnimationUtility.bindings.cs
@@ -430,7 +430,7 @@ public static AnimationCurve GetEditorCurve(AnimationClip clip, string relativeP
extern public static void SetAnimationClipSettings([NotNull] AnimationClip clip, AnimationClipSettings srcClipInfo);
extern internal static void SetAnimationClipSettingsNoDirty([NotNull] AnimationClip clip, AnimationClipSettings srcClipInfo);
- extern public static void SetAdditiveReferencePose(AnimationClip clip, AnimationClip referenceClip, float time);
+ extern public static void SetAdditiveReferencePose([NotNull] AnimationClip clip, [NotNull] AnimationClip referenceClip, float time);
extern internal static bool IsValidOptimizedPolynomialCurve(AnimationCurve curve);
extern public static void ConstrainToPolynomialCurve(AnimationCurve curve);
diff --git a/Editor/Mono/Animation/CurveEditor/CurveEditor.cs b/Editor/Mono/Animation/CurveEditor/CurveEditor.cs
index 8d0303cb84..6e643dcd22 100644
--- a/Editor/Mono/Animation/CurveEditor/CurveEditor.cs
+++ b/Editor/Mono/Animation/CurveEditor/CurveEditor.cs
@@ -2697,6 +2697,14 @@ public void CancelTimeRangeSelection()
const string kPointTimeFieldName = "pointTimeField";
string m_FocusedPointField = null;
Vector2 m_PointEditingFieldPosition;
+ Rect m_PointEditingFieldsRect;
+
+ // Keep the keyboard control on an open "Edit Key..." field when it is the thing being clicked,
+ // otherwise the click counts as an initial one and re-selects all of its text. (UUM-140166)
+ protected override bool captureKeyboardControlOnMouseDown
+ {
+ get { return !(m_EditingPoints && m_PointEditingFieldsRect.Contains(Event.current.mousePosition)); }
+ }
Vector2 GetPointEditionFieldPosition()
{
@@ -2729,6 +2737,7 @@ void StartEditingSelectedPoints()
void StartEditingSelectedPoints(Vector2 fieldPosition)
{
m_PointEditingFieldPosition = fieldPosition;
+ m_PointEditingFieldsRect = Rect.zero;
m_FocusedPointField = kPointValueFieldName;
m_TimeWasEdited = false;
m_ValueWasEdited = false;
@@ -2798,6 +2807,9 @@ void EditSelectedPoints()
fieldPosition.x = Mathf.Clamp(fieldPosition.x, drawAreaInMargins.xMin, drawAreaInMargins.xMax - kFieldWidth);
fieldPosition.y = Mathf.Clamp(fieldPosition.y, drawAreaInMargins.yMin, drawAreaInMargins.yMax - kFieldHeight * 2);
+ // Covers both fields, in drawRect space, which is also the space the zoomable area handles its events in.
+ m_PointEditingFieldsRect = new Rect(fieldPosition.x, fieldPosition.y, kFieldWidth, kFieldHeight * 2);
+
EditorGUI.BeginChangeCheck();
GUI.SetNextControlName(kPointTimeFieldName);
CurveWrapper curveWrapper = GetCurveWrapperFromSelection(selectedCurves[0]);
diff --git a/Editor/Mono/Animation/CurveEditor/CurveEditorSelection.cs b/Editor/Mono/Animation/CurveEditor/CurveEditorSelection.cs
index f7fa130907..da072f4806 100644
--- a/Editor/Mono/Animation/CurveEditor/CurveEditorSelection.cs
+++ b/Editor/Mono/Animation/CurveEditor/CurveEditorSelection.cs
@@ -51,15 +51,15 @@ internal CurveSelection(int curveID, int key, SelectionType type)
public int CompareTo(CurveSelection other)
{
- int cmp = curveID - other.curveID;
+ int cmp = curveID.CompareTo(other.curveID);
if (cmp != 0)
return cmp;
- cmp = key - other.key;
+ cmp = key.CompareTo(other.key);
if (cmp != 0)
return cmp;
- return (int)type - (int)other.type;
+ return ((int)type).CompareTo((int)other.type);
}
public override bool Equals(object _other)
diff --git a/Editor/Mono/Animation/EditorCurveBinding.bindings.cs b/Editor/Mono/Animation/EditorCurveBinding.bindings.cs
index cab5880b58..c822207a91 100644
--- a/Editor/Mono/Animation/EditorCurveBinding.bindings.cs
+++ b/Editor/Mono/Animation/EditorCurveBinding.bindings.cs
@@ -74,7 +74,7 @@ public struct EditorCurveBinding : IEquatable
public override int GetHashCode()
{
- return String.Format("{0}:{1}:{2}", path, type.Name, propertyName).GetHashCode();
+ return HashCode.Combine(path, type, propertyName);
}
public override bool Equals(object other)
diff --git a/Editor/Mono/Animation/ZoomableArea.cs b/Editor/Mono/Animation/ZoomableArea.cs
index b93187d184..940c8d2af5 100644
--- a/Editor/Mono/Animation/ZoomableArea.cs
+++ b/Editor/Mono/Animation/ZoomableArea.cs
@@ -167,6 +167,10 @@ public float vScaleMax
protected bool allowSliderZoomHorizontal { get { return m_EnableSliderZoomHorizontal && m_HScaleMin < m_HScaleMax; } }
protected bool allowSliderZoomVertical { get { return m_EnableSliderZoomVertical && m_VScaleMin < m_VScaleMax; } }
+ // Controls drawn over the area receive a mouse down only after BeginViewGUI has taken the keyboard
+ // control, which ends any editing session they had. Return false to skip that. (UUM-140166)
+ protected virtual bool captureKeyboardControlOnMouseDown { get { return true; } }
+
public bool m_UniformScale;
public bool uniformScale { get { return m_UniformScale; } set { m_UniformScale = value; } }
@@ -673,7 +677,8 @@ public void HandleZoomAndPanEvents(Rect area)
{
// Catch keyboard control when clicked inside zoomable area
// (used to restrict scrollwheel)
- GUIUtility.keyboardControl = id;
+ if (captureKeyboardControlOnMouseDown)
+ GUIUtility.keyboardControl = id;
if (IsZoomEvent() || IsPanEvent())
{
diff --git a/Editor/Mono/AnimatorController.bindings.cs b/Editor/Mono/AnimatorController.bindings.cs
index d676c896de..5fd33feac2 100644
--- a/Editor/Mono/AnimatorController.bindings.cs
+++ b/Editor/Mono/AnimatorController.bindings.cs
@@ -76,7 +76,7 @@ static public StateMachineBehaviourContext[] FindStateMachineBehaviourContext(St
extern internal static StateMachineBehaviourContext[] Internal_FindStateMachineBehaviourContext(ScriptableObject behaviour);
[FreeFunction("AnimatorControllerBindings::Internal_CreateNewStateMachineBehaviour")]
- extern public static EntityId CreateNewStateMachineBehaviour(MonoScript script);
+ extern public static EntityId CreateNewStateMachineBehaviour([NotNull] MonoScript script);
[Obsolete("CreateStateMachineBehaviour is deprecated. Use CreateNewStateMachineBehaviour instead.", true)]
public static int CreateStateMachineBehaviour(MonoScript script) => (int)CreateNewStateMachineBehaviour(script);
diff --git a/Editor/Mono/AssemblyInfo/AssemblyInfo.cs b/Editor/Mono/AssemblyInfo/AssemblyInfo.cs
index 45fd161ca0..f0bb981a77 100644
--- a/Editor/Mono/AssemblyInfo/AssemblyInfo.cs
+++ b/Editor/Mono/AssemblyInfo/AssemblyInfo.cs
@@ -122,6 +122,7 @@
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-firstpass-testable")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")]
[assembly: InternalsVisibleTo("BuildPipelineTestUtilities")]
+[assembly: InternalsVisibleTo("ContentBuildLoadPreview.Editor")]
[assembly: InternalsVisibleTo("Unity.CrossModule.PlayMode.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Module.AssetDatabase.DanglingComponents.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.CoreEditor.ComponentUtility.Tests.Editor")]
@@ -221,6 +222,7 @@
[assembly:InternalsVisibleTo("Unity.AI.Navigation.Editor")]
[assembly: InternalsVisibleTo("Unity.Scenes")]
+[assembly: InternalsVisibleTo("Unity.Scenes.Editor.Tests")]
[assembly: InternalsVisibleTo("UnityEditor.Switch.Tests")]
@@ -252,6 +254,7 @@
[assembly: InternalsVisibleTo("Unity.Modules.BuildProfileEditor.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.UI.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.Multiplayer.Server.Tests.Editor")]
+[assembly: InternalsVisibleTo("Unity.Modules.Multiplayer.PlayMode.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.AssetDatabase.AssetPostProcessor.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.AssetPackage.Tests.Editor")]
// This should move with the AnimationWindow to a module at some point
@@ -259,6 +262,9 @@
[assembly: InternalsVisibleTo("Unity.Modules.Physics.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.GI.EditorBake.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.GI.LightProbes.Tests.Editor")]
+[assembly: InternalsVisibleTo("Unity.Modules.GI.UVUnwrap.Tests.Editor")]
+[assembly: InternalsVisibleTo("Unity.Modules.GI.BakedGI.ColorSpace.Tests.Editor")]
+[assembly: InternalsVisibleTo("Unity.Modules.GI.LightingInspectorMeshRenderer.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.Physics2D.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.U2D.NineSlice.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.GI.Prefabs.Tests.Editor")]
@@ -266,6 +272,7 @@
[assembly: InternalsVisibleTo("Unity.Modules.ShaderCompilationEditor.ShaderCompilation.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.ShaderCompilationEditor.ShaderUtil.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.ShaderCompilationEditor.Rendering.Tests.Editor")]
+[assembly: InternalsVisibleTo("Unity.Modules.ShaderCompilationEditor.ShaderCacheConsistency.Tests.Editor")]
[assembly: InternalsVisibleTo("Unity.Tests.Shared")]
diff --git a/Editor/Mono/AssetDatabase/AssetDatabaseSearching.cs b/Editor/Mono/AssetDatabase/AssetDatabaseSearching.cs
index 4b27ab4cab..5a452d519d 100644
--- a/Editor/Mono/AssetDatabase/AssetDatabaseSearching.cs
+++ b/Editor/Mono/AssetDatabase/AssetDatabaseSearching.cs
@@ -45,6 +45,7 @@ public static GUID[] FindAssetGUIDs(string filter, string[] searchInFolders)
var searchFilter = CreateSearchFilter(filter, searchInFolders);
return FindAssetGUIDs(searchFilter);
}
+ [VisibleToOtherModules("UnityEditor.UIToolkitAuthoringModule")]
internal static string[] FindAssets(SearchFilter searchFilter)
{
#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
diff --git a/Editor/Mono/AssetPipeline/AssetImportContext.bindings.cs b/Editor/Mono/AssetPipeline/AssetImportContext.bindings.cs
index db4bab4fee..c432b93178 100644
--- a/Editor/Mono/AssetPipeline/AssetImportContext.bindings.cs
+++ b/Editor/Mono/AssetPipeline/AssetImportContext.bindings.cs
@@ -97,7 +97,7 @@ internal void DependsOnImportedAsset(string path)
DependsOnImportedAssetInternal(path);
}
- [NativeName("GetArtifactFilePath")]
+ [NativeName("GetArtifactFilePath_Binding")]
private extern string GetArtifactFilePath_Internal(string path, string fileName);
[Obsolete("GetArtifactFilePath has been deprecated. Use GetArtifactData to get the data instead.")]
@@ -113,6 +113,7 @@ public string GetArtifactFilePath(GUID guid, string fileName)
}
[Obsolete("GetArtifactFilePath has been deprecated. Use GetArtifactData to get the data instead.")]
+ [NativeName("GetArtifactFilePath_Binding")]
public extern string GetArtifactFilePath(ArtifactKey key, string fileName);
[NativeName("GetArtifactData")]
diff --git a/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9ImporterEditor.cs b/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9ImporterEditor.cs
index a2a468257b..a2d6c5053d 100644
--- a/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9ImporterEditor.cs
+++ b/Editor/Mono/AssetPipeline/SpeedTree/SpeedTree9ImporterEditor.cs
@@ -46,6 +46,12 @@ internal IEnumerable importers
public override void OnEnable()
{
+ if (!AreImporterTargetsValid())
+ {
+ base.OnEnable(); // lets the base mark the editor enabled/inert (OnDisable symmetry)
+ return;
+ }
+
m_STImporter = target as SpeedTree9Importer;
if (tabs == null)
diff --git a/Editor/Mono/AssetPostprocessor.cs b/Editor/Mono/AssetPostprocessor.cs
index 7428a15723..70ab8a5933 100644
--- a/Editor/Mono/AssetPostprocessor.cs
+++ b/Editor/Mono/AssetPostprocessor.cs
@@ -126,12 +126,17 @@ public class MethodInfoCallback : Callback
public bool MethodDomainReload { get; }
+ // Cached: PostprocessAllAssets runs for every import batch and building this
+ // marker name there would allocate a string per callback per batch.
+ public string PerformanceMarkerName { get; }
+
public override string name => classType.FullName;
public MethodInfoCallback(MethodInfo method, bool methodDomainReload)
{
Method = method;
MethodDomainReload = methodDomainReload;
+ PerformanceMarkerName = $"{method.DeclaringType.Name}.OnPostprocessAllAssets";
}
public override IEnumerable GetCustomAttributes() => Method.GetCustomAttributes();
@@ -323,7 +328,7 @@ static void PostprocessAllAssets(string[] importedAssets, string[] addedAssets,
{
if (assetPostProcessor.MethodDomainReload)
{
- using (new EditorPerformanceMarker($"{assetPostProcessor.classType.Name}.OnPostprocessAllAssets", assetPostProcessor.classType).Auto())
+ using (new EditorPerformanceMarker(assetPostProcessor.PerformanceMarkerName, assetPostProcessor.classType).Auto())
InvokeMethod(assetPostProcessor.Method, argsWithDidDomainReload);
}
else
@@ -331,7 +336,7 @@ static void PostprocessAllAssets(string[] importedAssets, string[] addedAssets,
if (containsNoAssets)
continue;
- using (new EditorPerformanceMarker($"{assetPostProcessor.classType.Name}.OnPostprocessAllAssets", assetPostProcessor.classType).Auto())
+ using (new EditorPerformanceMarker(assetPostProcessor.PerformanceMarkerName, assetPostProcessor.classType).Auto())
InvokeMethod(assetPostProcessor.Method, args);
}
}
diff --git a/Editor/Mono/BuildPipeline/Android/AndroidPostGenerateGradleProject.cs b/Editor/Mono/BuildPipeline/Android/AndroidPostGenerateGradleProject.cs
index eec4c2b16f..0d2740830f 100644
--- a/Editor/Mono/BuildPipeline/Android/AndroidPostGenerateGradleProject.cs
+++ b/Editor/Mono/BuildPipeline/Android/AndroidPostGenerateGradleProject.cs
@@ -20,7 +20,9 @@ public interface IPostGenerateGradleAndroidProject : IOrderedCallback
///
///
/// Use this function to modify the generated Gradle files before the build process begins.
- ///
+ ///
+ /// Common uses include modifying the Android manifest file and changing the Gradle build files of the generated project. The manifest file is located at `src/main/AndroidManifest.xml` in the folder that `path` points to. For more information on the methods available to modify Gradle project files, refer to [[wiki:android-modify-gradle-project-files-methods|Modify the Gradle project files for a Unity application]].
+ ///
/// **Note**: To compile the script for this function as an Editor script and prevent any compilation errors related to the `UnityEditor.Android` namespace, use one of these methods:
///
///* Place the script in the `Assets/Editor` folder of your project.
diff --git a/Editor/Mono/BuildPipeline/AssemblyStripper.cs b/Editor/Mono/BuildPipeline/AssemblyStripper.cs
index 946b0e4da7..ff2c4a5b48 100644
--- a/Editor/Mono/BuildPipeline/AssemblyStripper.cs
+++ b/Editor/Mono/BuildPipeline/AssemblyStripper.cs
@@ -266,13 +266,15 @@ public static string WriteEditorData(BuildPostProcessArgs args, NPath linkerInpu
{
CollectIncludedAndExcludedModules(out var forceIncludeModules, out var forceExcludeModules);
- var editorToLinkerData = new EditorToLinkerData
- {
#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
- typesInScenes = GetTypesInScenesInformation(args.report, args.usedClassRegistry)
+ var typesInScenes = GetTypesInScenesInformation(args.report, args.usedClassRegistry)
+ .OrderBy(data => data.fullManagedTypeName ?? data.nativeClass)
+ .ToArray();
#pragma warning restore UA2001
- .OrderBy(data => data.fullManagedTypeName ?? data.nativeClass)
- .ToArray(),
+
+ var editorToLinkerData = new EditorToLinkerData
+ {
+ typesInScenes = typesInScenes,
allNativeTypes = CollectNativeTypeData().ToArray(),
forceIncludeModules = forceIncludeModules.ToArray(),
forceExcludeModules = forceExcludeModules.ToArray()
@@ -291,9 +293,10 @@ public static string WriteEditorData(BuildPostProcessArgs args, NPath linkerInpu
var unityType = UnityType.FindTypeByName(nativeClass);
var managedName = RuntimeClassMetadataUtils.ScriptingWrapperTypeNameForNativeID(unityType.persistentTypeID);
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
- var usedInScenes = rcr.GetScenesForClass(unityType.persistentTypeID)?.OrderBy(p => p);
-#pragma warning restore UA2001
+
+ var usedInScenes = rcr.GetScenesForClass(unityType.persistentTypeID)?.ToArray();
+ if (usedInScenes != null)
+ Array.Sort(usedInScenes);
bool noManagedType = unityType.persistentTypeID != 0 && managedName == "UnityEngine.Object";
var information = new EditorToLinkerData.TypeInSceneData(
@@ -301,9 +304,7 @@ public static string WriteEditorData(BuildPostProcessArgs args, NPath linkerInpu
noManagedType ? null : managedName,
nativeClass,
unityType.module,
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
- usedInScenes != null ? usedInScenes.ToArray() : null);
-#pragma warning restore UA2001
+ usedInScenes);
items.Add(information);
}
@@ -407,26 +408,14 @@ private static string GetMethodPreserveBlacklistContents(RuntimeClassRegistry rc
#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
var groupedByAssembly = rcr.GetMethodsToPreserve().GroupBy(m => m.assembly);
-#pragma warning restore UA2001
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
foreach (var assembly in groupedByAssembly.OrderBy(a => a.Key))
-#pragma warning restore UA2001
{
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
var assemblyName = assembly.Key;
-#pragma warning restore UA2001
sb.AppendLine(string.Format("\t", assemblyName));
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
var groupedByType = assembly.GroupBy(m => m.fullTypeName);
-#pragma warning restore UA2001
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
foreach (var type in groupedByType.OrderBy(t => t.Key))
-#pragma warning restore UA2001
{
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
sb.AppendLine(string.Format("\t\t", EscapeXmlString(type.Key)));
-#pragma warning restore UA2001
-#pragma warning disable UA2001 // The Banned API Analyzer produces compile errors for any new Linq code. This pre-existing usage has been suppressed, but should be rewritten if possible.
foreach (var method in type.OrderBy(m => m.methodName))
#pragma warning restore UA2001
sb.AppendLine(string.Format("\t\t\t", EscapeXmlString(method.methodName)));
diff --git a/Editor/Mono/BuildPipeline/BuildCallbackContext.bindings.cs b/Editor/Mono/BuildPipeline/BuildCallbackContext.bindings.cs
index c7f3b25fe2..15553fd161 100644
--- a/Editor/Mono/BuildPipeline/BuildCallbackContext.bindings.cs
+++ b/Editor/Mono/BuildPipeline/BuildCallbackContext.bindings.cs
@@ -69,7 +69,7 @@ public bool IsPlayerBuild
[FreeFunction("BuildCallbackContextBindings::IsContentOnlyBuild")]
private static extern bool IsContentOnlyBuildInternal(IntPtr self);
- ///Returns true if the build is a content only build type like an AssetBundle build.
+ ///Returns true if the build is a content directory or AssetBundle build.
public bool IsContentOnlyBuild
{
get
diff --git a/Editor/Mono/BuildPipeline/BuildPipeline.bindings.cs b/Editor/Mono/BuildPipeline/BuildPipeline.bindings.cs
index 80a4f0e31d..5f2203e7e2 100644
--- a/Editor/Mono/BuildPipeline/BuildPipeline.bindings.cs
+++ b/Editor/Mono/BuildPipeline/BuildPipeline.bindings.cs
@@ -46,8 +46,8 @@ public enum PlayerConnectionInitiateMode
}
// Lets you programmatically build players or AssetBundles which can be loaded from the web.
- ///API for building players or AssetBundles.
- ///The BuildPipeline class in the Unity Editor namespace provides essential tools to programmatically Build Players and Build AssetBundles.
+ ///API for building Players or content builds.
+ ///The BuildPipeline class in the Unity Editor namespace provides tools to build Players and create content directory or AssetBundle builds.
///AssetBundles can be loaded from external sources such as the web, enhancing the flexibility and scalability of content delivery in Unity applications.
///The class contains several static properties and methods to facilitate building workflows.
///AssetBundles
@@ -372,9 +372,9 @@ internal static bool ValidateScenePaths(string[] scenes, out string errorMessage
internal static extern bool IsFeatureSupported(string define, BuildTarget platform);
// Is a player currently building?
- ///Returns true when Unity is actively building a Player or AssetBundles
- ///This returns true during Player builds () and AssetBundle builds ().
- ///It can be used to check the context inside script code that could be triggered during a build, for example when is being used on a .
+ ///Checks whether Unity is actively building a Player or a content build.
+ ///This returns true during Player builds (), content directory builds (), and AssetBundle builds ().
+ ///Use it to check the context inside script code that might be triggered during a build, for example when is used on a .
public static extern bool isBuildingPlayer { [FreeFunction("IsBuildingPlayer")] get; }
@@ -425,13 +425,19 @@ internal static BuildReport BuildPlayerData(BuildPlayerDataOptions buildPlayerDa
/// Builds a content directory (serialized assets and scenes plus a manifest) at a defined output path.
///
///
- /// Register the folder at runtime with .
- /// Each entry in must be a ScriptableObject; the build includes those roots and
- /// everything they reference (including , , and ).
- /// Creates an outputPath if missing, normalizes path separators, and defaults to the output folder name.
+ /// Use buildParameters to configure the build, including the root assets to include, the output
+ /// path, and optional compression and build options. Each entry in
+ /// must be a . The build includes those root assets and everything they reference, such as
+ /// assets referenced through , , and
+ /// .
+ ///
+ /// The method creates if it doesn't exist, normalizes path
+ /// separators, and defaults to the output folder name.
///
/// The build uses and the active subtarget configured for that target in the build settings.
/// Select the intended platform in the **Build Profile** window or through [command line arguments](xref:um-command-line-arguments) so that the active target is set to the desired setting prior to calling this method.
+ ///
+ /// To load the built content, register the output directory with .
///
///
///
@@ -525,6 +531,7 @@ public static BuildReport BuildContentDirectory(BuildContentDirectoryParameters
///
///
///
+ ///
public static AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform)
{
BuildAssetBundlesParameters input = new BuildAssetBundlesParameters
@@ -730,6 +737,7 @@ public static AssetBundleManifest BuildAssetBundles(string outputPath, AssetBund
///]]>
///
///AssetBundles
+ ///
public static AssetBundleManifest BuildAssetBundles(BuildAssetBundlesParameters buildParameters)
{
if (buildParameters.targetPlatform == 0 || buildParameters.targetPlatform == BuildTarget.NoTarget)
diff --git a/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs b/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs
index ad3d9db3d1..5091f1b7e7 100644
--- a/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs
+++ b/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs
@@ -22,7 +22,9 @@ namespace UnityEditor.Build
///Interface that provides control over callback order.
///This is the base class for build callback interfaces, for example , , , , and .
///
- ///Every class that implements these interfaces must define the callbackOrder property with a "get" accessor.
+ ///Every class that implements these interfaces must define the callbackOrder property with a "get" accessor.
+ ///
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
public interface IOrderedCallback
{
///Returns a numeric value that determines the order in which the build callback is invoked.
@@ -85,7 +87,15 @@ public abstract class BuildPlayerProcessor : IOrderedCallback
///Returns the relative callback order for callbacks. Callbacks with lower values are called before ones with higher values.
public virtual int callbackOrder => 0;
///Implement this function to receive a callback before a Player build starts.
- ///You can use this function to customize the build before Unity starts building the Player. For example, the following code example demonstrates how to include streaming assets in the Player build without placing them in your project's StreamingAssets folder.
+ ///You can use this function to customize the build before Unity starts building the Player. For example, the following code example demonstrates how to include streaming assets in the Player build without placing them in your project's StreamingAssets folder.
+ ///
+ ///This callback is a good place to confirm that the project is configured correctly before the build starts, and to fail the build early if a required setting is missing. Give validation callbacks a low value so they run before other PrepareForBuild callbacks.
+ ///
+ ///To fail the build from this callback, throw a . It reports a clear message without a call stack.
+ ///
+ ///Unlike , you can trigger a content-only build from this callback, for example by calling . The Addressables package uses this callback to build content during a Player build.
+ ///
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks).
///The context for the scheduled Player build.
///
///
///
///
+ ///
public abstract void PrepareForBuild(BuildPlayerContext buildPlayerContext);
}
///Implement this interface to execute code at the start of the Player build process.
- ///This interface is replaced by , which works for AssetBundle and ContentDirectory builds as well.
- ///
- ///At the start of a Player build, Unity uses the property on each implementation to determine the order in which to invoke the callbacks.
- ///
- ///This callback can be useful for automated tasks and ensuring your build environment is correctly configured.
+ ///This interface behaves like , but is invoked only for Player builds. Use instead, because it is also invoked for AssetBundle and content directory builds.
///
- ///Example usages include:
- ///
- ///* For validation checks, e.g. confirming required build settings, environmental variables, content or other project-specific conditions. When possible you can automatically fix problems by changing settings. Or you can fail the build, by throwing a BuildFailedException along with a clear error message.
- ///* To make sure required Assets are included in the build. See .
- ///* To generate version numbers, change logs, link.xml files or other content that should be regenerated prior to each Player build.
- ///* For logging, reporting or sending analytics.
- ///
- ///Note: Build callbacks are a powerful feature, but it is strongly recommended that their implementations maintain deterministic build outputs.
- ///The result of a build should be predictable and reproducible, based on the project’s content, the Unity version, and installed packages.
- ///Introducing environment-specific behavior, external dependencies, randomness, or other non-deterministic elements can lead to outcomes
- ///that are challenging to debug or reproduce. This unpredictability may also compromise the efficiency and accuracy of incremental builds or incremental upgrades.
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
+ ///
///
///
///
@@ -132,34 +130,35 @@ public abstract class BuildPlayerProcessor : IOrderedCallback
public interface IPreprocessBuildWithReport : IOrderedCallback
{
///Implement this method to receive a callback before the build is started.
- ///This method is replaced by , which works for AssetBundle builds as well.
- /// This callback is invoked during Player builds, but not during AssetBundle builds.
+ ///This method is invoked during Player builds only. Use instead, which is also invoked during AssetBundle and content directory builds.
///A report containing information about the build, such as its target platform and output path.
///
///
///
void OnPreprocessBuild(BuildReport report);
}
- ///Implement this interface to execute code at the start of the Player build or AssetBundle build process.
- ///At the start of a Player build or AssetBundle build, Unity uses the property on each implementation to determine the order in which to invoke the callbacks.
+ ///Implement this interface to execute code at the start of the Player, AssetBundle, or content directory build process.
+ ///At the start of a Player, AssetBundle, or content directory build, Unity uses the property on each implementation to determine the order in which to invoke the callbacks.
///
///This callback can be useful for automated tasks and ensuring your build environment is correctly configured.
///
- ///You can't invoke an additional build from inside this callback. To invoke an AssetBundle build at the start of a Player build you should use instead.
+ ///You can't invoke another build from inside this callback. To invoke a content build at the start of a Player build, use instead.
///
///Example usages include:
///
- ///* For validation checks, e.g. confirming required build settings, environmental variables, content or other project-specific conditions. When possible you can automatically fix problems by changing settings. Or you can fail the build, by throwing a BuildFailedException along with a clear error message.
- ///* To make sure required Assets are included in the build. See .
- ///* To generate version numbers, change logs, link.xml files or other content that should be regenerated prior to each Player build or AssetBundle build.
- ///* For logging, reporting or sending analytics.
+ ///* For validation checks, for example confirming required build settings, environment variables, content, or other project-specific conditions. When possible you can automatically fix problems by changing settings, or you can fail the build.
+ ///* To make sure required Assets are included in the build. Refer to .
+ ///* To generate version numbers, change logs, link.xml files, or other content that must be regenerated before each build.
+ ///* For logging, reporting, or sending analytics.
+ ///
+ ///To fail the build from this callback, throw a . It reports a clear message without a call stack and fails the build whether or not the build uses strict mode. A logged error, such as from Debug.LogError, fails the build only when the build uses strict mode (, , or ).
///
///Note: Build callbacks are a powerful feature, but it is strongly recommended that their implementations maintain deterministic build outputs.
///The result of a build should be predictable and reproducible, based on the project’s content, the Unity version, and installed packages.
///Introducing environment-specific behavior, external dependencies, randomness, or other non-deterministic elements can lead to outcomes
///that are challenging to debug or reproduce. This unpredictability might compromise the efficiency and accuracy of incremental builds or incremental upgrades.
///
- ///The main difference between this interface and or is that this callback gets called on AssetBundle builds and Player builds.
+ ///The main difference between this interface and or is that this callback is invoked on AssetBundle and content directory builds as well as Player builds.
///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
///
///
///
///
+ ///
public interface IPreprocessBuildWithContext : IOrderedCallback
{
///Implement this method to receive a callback before the build is started.
- ///This callback is invoked during Player builds and AssetBundle builds.
+ ///This callback is invoked during Player, AssetBundle, and content directory builds.
///A context containing information about the build, such as its build report.
///
///
///
///
+ ///
void OnPreprocessBuild(BuildCallbackContext ctx);
}
@@ -263,18 +264,17 @@ public interface IPostprocessBuild : IOrderedCallback
}
///Implement this interface to execute code immediately after the Player build process is completed.
- ///This interface is replaced by , which works for AssetBundle and ContentDirectory builds as well.
- ///This is useful for tasks that need to be performed as the last step of building, such as cleaning up assets, generating analytics or reports, or customizing build outputs.
+ ///This interface behaves like , but is invoked only for Player builds. Use instead, because it is also invoked for AssetBundle and content directory builds.
///
- ///As a final step of a Player build, Unity uses the property on each implementation to determine the order in which to invoke the callbacks.
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
+ ///
///
///
public interface IPostprocessBuildWithReport : IOrderedCallback
{
///Implement this function to receive a callback after the build is complete.
- ///This method is replaced by , which works for AssetBundle builds as well.
- /// This callback is invoked during Player builds, but not during AssetBundle builds.
- /// If the build stops early, due to a failure or cancellation, then the callback is not invoked.
+ ///This method is invoked during Player builds only. Use instead, which is also invoked during AssetBundle and content directory builds.
+ /// If the build stops early, due to a failure or cancellation, then this callback is not invoked.
///A BuildReport containing information about the build, such as the target platform and output path.
///
///
void OnPostprocessBuild(BuildReport report);
}
- ///Implement this interface to execute code immediately after the Player build or AssetBundle build process is completed.
- ///This is useful for tasks that need to run after a build completes, even if the build failed or was cancelled. For example, you might want to clean up assets, generate analytics or reports, or customize build outputs. The postprocess callback runs whether the build succeeds, fails, or is cancelled, as long as the corresponding callback ran. It's only skipped if early validation prevents the build from starting.
+ ///Implement this interface to execute code immediately after the Player, AssetBundle, or content directory build process is completed.
+ ///This is useful for tasks that need to run after a build completes, even if the build failed or was canceled. For example, you might want to clean up assets, generate analytics or reports, or customize build outputs. The postprocess callback runs whether the build succeeds, fails, or is canceled, as long as the corresponding callback ran. It's only skipped if early validation prevents the build from starting.
+ ///
+ ///As a final step of a Player, AssetBundle, or content directory build, Unity uses the property on each implementation to determine the order in which to invoke the callbacks.
///
- ///As a final step of a Player build or AssetBundle build, Unity uses the property on each implementation to determine the order in which to invoke the callbacks.
+ ///To fail the build from this callback, throw a . It reports a clear message without a call stack and fails the build whether or not the build uses strict mode. A logged error, such as from Debug.LogError, fails the build only when the build uses strict mode (, , or ).
///
- ///Note: The main difference between this interface and or is that this callback gets called on AssetBundle builds as well as Player builds.
+ ///Note: The main difference between this interface and or is that this callback is invoked on AssetBundle and content directory builds as well as Player builds.
+ ///
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
///
///
///
///
+ ///
public interface IPostprocessBuildWithContext : IOrderedCallback
{
///Implement this function to receive a callback after the build is complete.
- ///This callback is invoked during Player builds or AssetBundle builds.
+ ///This callback is invoked during Player, AssetBundle, and content directory builds.
/// This callback is invoked even when the build stops early due to a failure or cancellation. However it will not be invoked if initial validation checks prevent the build from starting.
///A context containing information about the build, such as its build report.
///
@@ -396,6 +401,7 @@ public interface IPostprocessBuildWithContext : IOrderedCallback
///
///
///
+ ///
///
void OnPostprocessBuild(BuildCallbackContext ctx);
}
@@ -405,7 +411,7 @@ public interface IPostprocessBuildWithContext : IOrderedCallback
public interface IPostBuildPlayerScriptDLLs : IOrderedCallback
{
///Implement this interface to receive a callback just after the player scripts have been compiled.
- ///You can implement this if you need to read or patch managed Assemblies for players being built. You can get assembly locations from the files property of the report parameter. Note that implementing this callback will cause builds to run slower, as assemblies need to be copied to an intermediate location, and is not recommended for best performance.
+ ///You can implement this if you need to read or patch managed Assemblies for players being built. To retrieve assembly locations, call GetFiles on the BuildReport provided as the report parameter, and read the path property from each returned BuildFile. Note that implementing this callback causes builds to run slower, as assemblies need to be copied to an intermediate location, and is not recommended for best performance.
///A report containing information about the build, such as its target platform and output path.
///
///
/// Implement this method to receive a callback for each scene during the build.
///
- /// Unity invokes this callback during Player and AssetBundle builds, and also when a scene is reloaded while entering Play mode. Use to determine in which context the callback is called.
+ /// Unity invokes this callback during Player, AssetBundle, and content directory builds, and also when a scene is loaded while in Play mode. Use to determine in which context the callback is called.
///
/// This callback supports editing the provided scene to prepare it for a Player build or entering Play mode, and reading assets. For example, you can add or remove references to project assets in that scene.
///
- /// This callback doesn't support modifying the state of other assets. Use it to modify only the provided scene.
+ /// This callback doesn't support modifying the state of other assets, creating new assets, or deleting assets. Use it to modify only the provided scene.
+ ///
+ /// Don't access the build history from this callback. For content directory builds this callback can run in a separate worker process where is not available.
+ ///
+ /// To fail the build from this callback, throw a . It reports a clear message without a call stack and fails the build whether or not the build uses strict mode. A logged error, such as from Debug.LogError, fails the build only when the build uses strict mode (, , or ).
///
/// Keep implementations deterministic. Avoid random values, timestamps, or external changing data sources. For more information, refer to [Deterministic builds](xref:um-build-deterministic-builds).
///
+ /// Use and to add explicit dependencies to assets used during your scene modifications.
+ ///
/// Apply to callback types and increment the version whenever the callback logic changes to help Unity invalidate cached scene processing results when needed.
///
/// For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks).
/// The current scene being processed.
/// A report containing information about the current build. When this callback is invoked for scene loading during Play mode, this parameter is null.
- ///
+ ///
///
- ///
- ///
- ///
- ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
void OnProcessScene(UnityEngine.SceneManagement.Scene scene, BuildReport report);
}
@@ -526,7 +540,7 @@ public interface IPreprocessShaders : IOrderedCallback
///- Combinations of keywords that are never used.
///- Keywords you only use in your debug builds.
///
- ///Unity invokes the `OnProcessShader` callback in both Player and AssetBundle builds. If there are any shaders already in the cache, then this method isn't invoked for those shaders. To ensure the callback runs for all shaders, perform a [clean build](xref:um-build-clean-build). To run it for a specific shader, modify that shader or one of its dependent assets.
+ ///Unity invokes the `OnProcessShader` callback in Player, AssetBundle, and content directory builds. If there are any shaders already in the cache, then this method isn't invoked for those shaders. To ensure the callback runs for all shaders, perform a [clean build](xref:um-build-clean-build). To run it for a specific shader, modify that shader or one of its dependent assets.
///
///To help you identify keywords and variants to strip, you can [check what shader variants you have in your project](xref:um-shader-how-many-variants). For example if you [declare a keyword](xref:um-sl-multiple-program-variants) called `DEBUG` in your shader code using `#pragma multi_compile _ DEBUG`, the following [Editor script](xref:um-special-folders) finds and strips shader variants that use the keyword.
///
@@ -537,15 +551,16 @@ public interface IPreprocessShaders : IOrderedCallback
///3. Implements the `OnProcessShader` callback function and iterates over the `data` list, which contains every variant in the shader.
///4. Uses `data.shaderKeywordSet.IsEnabled()` to check if each variant uses the keyword.
///5. Uses `data.removeAt()` to strip a shader variant if it contains the keyword and you've disabled **Development build** in **[Build Settings](xref:um-build-settings)**.
- ///
+ ///
///You can also find local keywords. You must create the `ShaderKeyword` instance inside the implementation of `OnProcessShader`, so you can use the callback's `shader` variable in the `ShaderKeyword` constructor.
///
///For example if you declare a local keyword called `RED` in your shader code using `#pragma multi_compile_local _ RED`, the following script finds and strips shader variants that use the keyword.
- ///
+ ///
///If you strip a variant that a Material needs at runtime, Unity chooses an available shader variant that matches as closely as possible.
///
///Find out about other ways you can [strip shader variants](xref:um-shader-variant-stripping).
///
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
///
///The shader that Unity is about to compile.
///Details about the specific shader code being compiled.
@@ -586,6 +601,7 @@ public interface IPreprocessShaders : IOrderedCallback
///
///
///
+ ///
///
void OnProcessShader(Shader shader, ShaderSnippetData snippet, IList data);
}
@@ -605,7 +621,9 @@ public interface IPreprocessComputeShaders : IOrderedCallback
///
///Note that this callback only provides details of compute shaders. To see regular shaders that Unity is about to compile into the build, see .
///
- ///This callback is invoked for both Player and AssetBundle builds.
+ ///This callback is invoked for Player, AssetBundle, and content directory builds.
+ ///
+ ///For more information about build callbacks, refer to [Use build callbacks](xref:um-build-callbacks)
///The compute shader that Unity is about to compile.
///The name of the kernel that Unity is about to compile.
///The list of shader variants that Unity is about to compile.
@@ -655,6 +673,7 @@ public interface IPreprocessComputeShaders : IOrderedCallback
///Declaring and using shader keywords in HLSL
///
///
+ ///
void OnProcessComputeShader(ComputeShader shader, string kernelName, IList data);
}
diff --git a/Editor/Mono/BuildPipeline/BuildPlayerContext.cs b/Editor/Mono/BuildPipeline/BuildPlayerContext.cs
index 5478ad3b6a..27e9b7d45c 100644
--- a/Editor/Mono/BuildPipeline/BuildPlayerContext.cs
+++ b/Editor/Mono/BuildPipeline/BuildPlayerContext.cs
@@ -17,7 +17,7 @@ public sealed class BuildPlayerContext
internal static BuildPlayerContext ActiveInstance { get; private set; }
///The player build options associated with this build.
- public BuildPlayerOptions BuildPlayerOptions { get; }
+ public BuildPlayerOptions BuildPlayerOptions { get; private set; }
internal BuildPlayerContext(BuildPlayerOptions buildPlayerOptions)
{
@@ -36,18 +36,36 @@ internal BuildPlayerContext(BuildPlayerOptions buildPlayerOptions)
///
///
/// This is useful if you want the player build
- /// to retrieve type stripping information from content-only builds you do prior to the player build.
+ /// to retrieve type stripping information from builds you do prior to the Player build.
///
/// If this method is called on the same path multiple times, the path is only added once.
///
/// If the path passed into this method is not a valid build report directory, at build time an error will be thrown.
///
- /// For more information on locating the build report directory for a build, refer to .
+ /// For more information on locating the build report directory for a build, refer to .
+ ///
+ /// For more information, refer to [How code stripping affects content](xref:um-managed-code-stripping-content).
///The path to a build report directory. If the path is invalid, an error will be thrown during the build process.
+ ///
+ ///
public void AddPreviousBuildReportDirectory(string directory)
{
if (!AdditionalBuildReportDirectories.Contains(directory))
AdditionalBuildReportDirectories.Add(directory);
+
+ var options = BuildPlayerOptions;
+ var existingDirectories = options.previousBuildReportDirectories ?? Array.Empty();
+
+ // The build options can already list the directory, either because a previous call added it or because
+ // the build profile/build window prepopulated it. Either way, don't add it a second time.
+ if (Array.IndexOf(existingDirectories, directory) >= 0)
+ return;
+
+ var updatedDirectories = new string[existingDirectories.Length + 1];
+ Array.Copy(existingDirectories, updatedDirectories, existingDirectories.Length);
+ updatedDirectories[existingDirectories.Length] = directory;
+ options.previousBuildReportDirectories = updatedDirectories;
+ BuildPlayerOptions = options;
}
///
diff --git a/Editor/Mono/BuildPipeline/BuildTarget.cs b/Editor/Mono/BuildPipeline/BuildTarget.cs
index 1209562331..5fbca88679 100644
--- a/Editor/Mono/BuildPipeline/BuildTarget.cs
+++ b/Editor/Mono/BuildPipeline/BuildTarget.cs
@@ -10,7 +10,7 @@ namespace UnityEditor
// Target build platform.
// When adding new platform, read this first - https://confluence.hq.unity3d.com/display/DEV/Adding+new+platform
// When removing platform, read this first - https://confluence.hq.unity3d.com/display/DEV/Removing+platform
- ///Specifies the target platform for a Player or AssetBundle build.
+ ///Specifies the target platform for a Player or content build.
///Pass a platform property to BuildTarget to specify the target platform to build a Player for. For example, use to target the Android platform. At runtime, use BuildTarget to identify the currently selected build target. Only actively supported platforms are documented in this list.
///
///**Important**: When targeting Windows, it's recommended to use the StandaloneWindow64 target unless you specifically need to target devices that use a 32-bit CPU.
@@ -25,7 +25,7 @@ public enum BuildTarget
{
///Build a macOS standalone.
///
- ///To specify which architecture to use (Intel, ARM or Universal), please use .
+ ///To specify which architecture to use (Intel, ARM or Universal), refer to OSXStandalone.UserBuildSettings.architecture.
///
StandaloneOSX = 2,
@@ -156,7 +156,7 @@ public enum BuildTarget
///
tvOS = 37,
- ///Build a Nintendo Switch player.
+ ///Build a Nintendo Switch™ player.
///
Switch = 38,
@@ -199,7 +199,8 @@ public enum BuildTarget
///
VisionOS = 47,
- [ExcludeFromDocs]
+ ///Build a Nintendo Switch™ 2 player.
+ ///
Switch2 = 48,
[ExcludeFromDocs]
diff --git a/Editor/Mono/BuildPipeline/BuildTargetDiscovery.bindings.cs b/Editor/Mono/BuildPipeline/BuildTargetDiscovery.bindings.cs
index eacc7731df..c6e1aedd91 100644
--- a/Editor/Mono/BuildPipeline/BuildTargetDiscovery.bindings.cs
+++ b/Editor/Mono/BuildPipeline/BuildTargetDiscovery.bindings.cs
@@ -90,6 +90,8 @@ public struct DiscoveredTargetInfo
static readonly string k_SDKProviderNotMultiTargetError = L10n.Tr("The SDK platform provider '{0}' with guid '{1}' references a platform that is not marked as a multi-target platform.");
internal static readonly string k_SDKProviderNotDerivedTargetError = L10n.Tr("The SDK platform provider '{0}' with guid '{1}' references a platform that is not marked as a derived platform.");
static readonly string k_CreateIPlatformProviderFailedError = L10n.Tr("Failed to create IPlatformProvider instance for type '{0}'.");
+ static readonly string k_PlatformDeprecatedDefaultWithDisplayName = L10n.Tr("The {0} platform is deprecated.");
+ static readonly string k_DerivedPlatformUsesDeprecatedBase = L10n.Tr("This platform is based on {0}, which is deprecated.");
public static extern bool PlatformHasFlag(BuildTarget platform, TargetAttributes flag);
@@ -136,6 +138,11 @@ public static bool BuildTargetSupportsRenderer(BuildPlatform platform, GraphicsD
if (platform.namedBuildTarget == NamedBuildTarget.Standalone)
buildTarget = DesktopStandaloneBuildWindowExtension.GetBestStandaloneTarget(buildTarget);
+ return BuildTargetSupportsRenderer(buildTarget, type);
+ }
+
+ public static bool BuildTargetSupportsRenderer(BuildTarget buildTarget, GraphicsDeviceType type)
+ {
foreach (int var in GetRenderList(buildTarget))
{
if ((GraphicsDeviceType)var == type)
@@ -321,6 +328,11 @@ internal struct PlatformInfo
// needs to be removed when https://jira.unity3d.com/browse/PLAT-7721 is implemented
public NameAndLink? temporaryLabelAndLinkForIndustrialOnboarding = null;
+ ///
+ /// Custom deprecation copy for UI when is set. May be empty if a generic fallback should be used.
+ ///
+ public string deprecationMessage = string.Empty;
+
public PlatformInfo() {}
public bool HasFlag(PlatformAttributes flag) { return (flags & flag) == flag; }
@@ -345,6 +357,20 @@ internal class PlatformPackageInfo
public string publisher;
public bool hasThumbnail;
+ ///
+ /// Optional catalog flag (e.g. SDK platform JSON, mock platforms). Used as a fallback deprecation
+ /// signal when Package Manager has no for this package.
+ ///
+ public bool deprecated;
+
+ ///
+ /// Optional deprecation tooltip when is true. Used as a fallback when
+ /// Package Manager has no for this package.
+ ///
+ public string deprecationMessage;
+
+ public PlatformPackageInfo() {}
+
public PlatformPackageInfo(string displayName, string qualifiedName, string description, string publisher = "", bool hasThumbnail = false)
{
this.displayName = displayName;
@@ -733,6 +759,7 @@ public PlatformGroup() { }
new PlatformInfo
{
displayName = "Unity Render Service for Android™",
+ downloadLinkName = "Android",
buildTarget = BuildTarget.Android,
iconName = "BuildSettings.Android",
internalPackages = new PlatformPackageList
@@ -954,10 +981,49 @@ public static GUID GetGUIDFromBuildTarget(BuildTarget buildTarget)
return EmptyGuid;
}
+ ///
+ /// Get the server platform GUID corresponding to the NamedBuildTarget.Server and BuildTarget.
+ ///
+ /// The NamedBuildTarget to get the server platform GUID for.
+ /// The BuildTarget to get the server platform GUID for.
+ /// The server platform GUID. Derived server platform GUID when the active platform is a derived server platform. Base server platform GUID otherwise.
+ /// True if a server platform GUID was found; otherwise, false.
internal static bool TryGetServerGUIDFromBuildTarget(NamedBuildTarget namedBuildTarget, BuildTarget buildTarget, out GUID result)
{
result = EmptyGuid;
+ if (namedBuildTarget != NamedBuildTarget.Server || !IsStandalonePlatform(buildTarget))
+ return false;
+
+ if (s_BuildTargetToPlatformGUID.TryGetValue(buildTarget, out var guid))
+ {
+ var module = ModuleManager.FindPlatformSupportModule(guid);
+ if (module is IDerivedBuildTargetProvider)
+ {
+ var derivedPlatformGuid = module.PlatformBuildTarget.Guid;
+ var (_, subtarget) = GetBuildTargetAndSubtargetFromGUID(derivedPlatformGuid);
+ if (subtarget == StandaloneBuildSubtarget.Server)
+ {
+ result = derivedPlatformGuid;
+ return true;
+ }
+ }
+ }
+
+ return TryGetBaseServerGUIDFromBuildTarget(namedBuildTarget, buildTarget, out result);
+ }
+
+ ///
+ /// Get the base server platform GUID corresponding to the NamedBuildTarget.Server and BuildTarget.
+ ///
+ /// The NamedBuildTarget to get the base server platform GUID for.
+ /// The BuildTarget to get the base server platform GUID for.
+ /// The base server platform GUID. If the platform is not a derived platform, the same GUID is returned.
+ /// True if a base server platform GUID was found; otherwise, false.
+ internal static bool TryGetBaseServerGUIDFromBuildTarget(NamedBuildTarget namedBuildTarget, BuildTarget buildTarget, out GUID result)
+ {
+ result = EmptyGuid;
+
if (namedBuildTarget == NamedBuildTarget.Server)
{
foreach (var platform in allPlatforms)
@@ -978,7 +1044,7 @@ internal static bool TryGetServerGUIDFromBuildTarget(NamedBuildTarget namedBuild
internal static GUID GetBasePlatformGUIDFromBuildTarget(NamedBuildTarget namedBuildTarget, BuildTarget buildTarget)
{
- if (TryGetServerGUIDFromBuildTarget(namedBuildTarget, buildTarget, out var value))
+ if (TryGetBaseServerGUIDFromBuildTarget(namedBuildTarget, buildTarget, out var value))
return value;
if (s_BuildTargetToPlatformGUID.TryGetValue(buildTarget, out GUID guid))
@@ -1004,8 +1070,8 @@ internal static GUID GetBasePlatformGUID(GUID platformGuid)
{
if (platformInfo.subtarget != StandaloneBuildSubtarget.Server)
return basePlatformGuid;
-
- if (TryGetServerGUIDFromBuildTarget(NamedBuildTarget.Server, platformInfo.buildTarget, out var serverPlatformGuid))
+
+ if (TryGetBaseServerGUIDFromBuildTarget(NamedBuildTarget.Server, platformInfo.buildTarget, out var serverPlatformGuid))
return serverPlatformGuid;
}
@@ -1094,6 +1160,13 @@ static void LoadSDKPlatforms()
if (string.IsNullOrEmpty(displayName))
Debug.LogWarning(string.Format(k_SDKPlatformMissingDisplayNameWarning, sdkPlatformGuid));
+ if (sdkPlatformInfo.isDeprecated)
+ flags |= PlatformAttributes.IsDeprecated;
+
+ var deprecationMessage = sdkPlatformInfo.isDeprecated && !string.IsNullOrEmpty(sdkPlatformInfo.deprecationMessage)
+ ? sdkPlatformInfo.deprecationMessage
+ : string.Empty;
+
PlatformInfo platformInfo = new()
{
supportedPlatformGuids = sdkPlatformInfo.flags.platformType == SDKPlatformType.MultiTarget ?
@@ -1109,6 +1182,7 @@ static void LoadSDKPlatforms()
buildProfilePlatformBannerBgColorHex = sdkPlatformInfo.bannerBackgroundColorHex ?? "#00000000",
internalPackages = sdkPlatformInfo.internalPackages,
partnerPackages = sdkPlatformInfo.partnerPackages,
+ deprecationMessage = deprecationMessage,
flags = flags | PlatformAttributes.IsSDKPlatform | PlatformAttributes.IsVisibleInPlatformBrowserOnly |
PlatformAttributes.IsWindowsBuildTarget | PlatformAttributes.IsWindowsArm64BuildTarget |
PlatformAttributes.IsLinuxBuildTarget | PlatformAttributes.IsMacBuildTarget,
@@ -1123,6 +1197,11 @@ static void LoadSDKPlatforms()
}
var groupIndex = Array.FindIndex(allPlatformGroups, g => g.groupName == targetGroupName);
+ // SDK platform JSON typically stores the English group identifier (e.g. "Web") while
+ // allPlatformGroups use localized titles (L10n.Tr("Web")). Without this fallback the
+ // platform is registered in allPlatforms but never added to a browser group.
+ if (groupIndex < 0)
+ groupIndex = Array.FindIndex(allPlatformGroups, g => g.groupName == L10n.Tr(targetGroupName));
if (groupIndex < 0)
{
Debug.LogWarning(string.Format(k_SDKPlatformUnknownPlatformGroupWarning, sdkPlatformGuid, targetGroupName));
@@ -1689,6 +1768,58 @@ public static string BuildPlatformSubtitle(GUID guid)
return string.Empty;
}
+ ///
+ /// When the platform is marked deprecated, returns true and sets to the
+ /// configured text. The message may be empty if no custom copy was provided; callers should supply a fallback in that case.
+ /// Base platforms are checked directly. Derived platforms also check their immediate base platform.
+ /// Multi-target platforms are deprecated only when marked deprecated on their own platform entry.
+ ///
+ public static bool BuildPlatformTryGetDeprecationMessage(GUID guid, out string deprecationMessage)
+ {
+ deprecationMessage = string.Empty;
+ if (!TryGetPlatformInfo(guid, out PlatformInfo platformInfo))
+ return false;
+
+ if (platformInfo.HasFlag(PlatformAttributes.IsDeprecated))
+ {
+ deprecationMessage = platformInfo.deprecationMessage;
+ return true;
+ }
+
+ if (platformInfo.HasFlag(PlatformAttributes.IsDerivedBuildTarget))
+ {
+ var basePlatformGuid = GetBasePlatformGUID(guid);
+ if (!basePlatformGuid.Empty()
+ && basePlatformGuid != guid
+ && TryGetDirectDeprecationMessage(basePlatformGuid, out var baseDeprecationMessage))
+ {
+ deprecationMessage = FormatDerivedInheritedDeprecationMessage(basePlatformGuid, baseDeprecationMessage);
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ static bool TryGetDirectDeprecationMessage(GUID guid, out string deprecationMessage)
+ {
+ deprecationMessage = string.Empty;
+ if (!TryGetPlatformInfo(guid, out PlatformInfo platformInfo) || !platformInfo.HasFlag(PlatformAttributes.IsDeprecated))
+ return false;
+
+ deprecationMessage = platformInfo.deprecationMessage;
+ return true;
+ }
+
+ static string FormatDerivedInheritedDeprecationMessage(GUID deprecatedBasePlatformGuid, string baseDeprecationMessage)
+ {
+ var baseDisplayName = BuildPlatformDisplayName(deprecatedBasePlatformGuid);
+ if (string.IsNullOrWhiteSpace(baseDeprecationMessage))
+ baseDeprecationMessage = string.Format(k_PlatformDeprecatedDefaultWithDisplayName, baseDisplayName);
+
+ return $"{baseDeprecationMessage}\n\n{string.Format(k_DerivedPlatformUsesDeprecatedBase, baseDisplayName)}";
+ }
+
public static PlatformGroup[] GetPlatformGroups()
{
return allPlatformGroups;
diff --git a/Editor/Mono/BuildPipeline/BuildTargetGroup.cs b/Editor/Mono/BuildPipeline/BuildTargetGroup.cs
index 21503d74f8..3d1b2e067a 100644
--- a/Editor/Mono/BuildPipeline/BuildTargetGroup.cs
+++ b/Editor/Mono/BuildPipeline/BuildTargetGroup.cs
@@ -116,7 +116,7 @@ public enum BuildTargetGroup
[ExcludeFromDocs]
Facebook = 26,
- ///Nintendo Switch target.
+ ///Nintendo Switch™ target.
Switch = 27,
[Obsolete("Lumin has been removed in 2022.2")]
@@ -153,7 +153,7 @@ public enum BuildTargetGroup
///Apple visionOS target.
VisionOS = 36,
- [ExcludeFromDocs]
+ ///Nintendo Switch™ 2 target.
Switch2 = 37,
[ExcludeFromDocs]
diff --git a/Editor/Mono/BuildPipeline/DataBuildDirtyTracker.cs b/Editor/Mono/BuildPipeline/DataBuildDirtyTracker.cs
index 05c9cf6783..2374469eb1 100644
--- a/Editor/Mono/BuildPipeline/DataBuildDirtyTracker.cs
+++ b/Editor/Mono/BuildPipeline/DataBuildDirtyTracker.cs
@@ -54,6 +54,10 @@ class BuildData
BuildOptions.CompressWithLz4HC;
public string[] assemblyNames;
+
+ // Session GUID of the full build that produced this data cache.
+ // A scripts-only or incremental build that reuses this cache copies it onto its report.
+ public GUID contentSourceBuildSessionGuid;
}
private BuildData buildData;
@@ -207,7 +211,8 @@ static public void WriteBuildData(string buildDataPath, BuildReport report, stri
.Where(m => ModuleMetadata.GetModuleIncludeSettingForModule(m) != ModuleIncludeSetting.ForceExclude)
.ToArray(),
#pragma warning restore UA2001
- assemblyNames = sortedAssemblyNames
+ assemblyNames = sortedAssemblyNames,
+ contentSourceBuildSessionGuid = report.summary.buildSessionGuid
};
buildDataPath.ToNPath().WriteAllText(JsonUtility.ToJson(buildData));
}
@@ -247,5 +252,30 @@ static public void ForceDirty(string buildDataPath)
NPath buildReportPath = buildDataPath;
buildReportPath.DeleteIfExists();
}
+
+ // Called (from native BuildPlayer) when a build reuses the data cache instead of rebuilding it — both the
+ // explicit scripts-only and the automatic (clean CheckDirty) reuse paths converge here. The reused BuildData
+ // carries the session GUID of the full build that produced the cache; record it on this build's report so it
+ // is written into BuildReportSummary and Build Analysis can borrow that exact source build's asset table.
+ [RequiredByNativeCode]
+ static public void SetContentSourceBuild(BuildReport report, string buildDataPath)
+ {
+ try
+ {
+ NPath path = buildDataPath;
+ if (report == null || !path.FileExists())
+ return;
+
+ var buildData = JsonUtility.FromJson(path.ReadAllText());
+ if (buildData == null || buildData.contentSourceBuildSessionGuid.Empty())
+ return;
+
+ report.SetContentSourceBuildSessionGUID(buildData.contentSourceBuildSessionGuid);
+ }
+ catch (Exception e)
+ {
+ Debug.LogWarning($"Failed to record source content build metadata for this scripts-only build: {e.Message}");
+ }
+ }
}
}
diff --git a/Editor/Mono/BuildPipeline/NamedBuildTarget.cs b/Editor/Mono/BuildPipeline/NamedBuildTarget.cs
index 3eadef274c..8edd7f926b 100644
--- a/Editor/Mono/BuildPipeline/NamedBuildTarget.cs
+++ b/Editor/Mono/BuildPipeline/NamedBuildTarget.cs
@@ -8,7 +8,8 @@
namespace UnityEditor.Build
{
- ///Build Target by name. This allows to describe and identify build targets that are not fully represented by BuildTargetGroup and BuildTarget.
+ ///Identifies which platform's build settings an API applies to.
+ ///Use to choose the platform output to build. Use to choose which platform's settings to read or change.
public readonly struct NamedBuildTarget : IEquatable, IComparable
{
private static readonly string[] k_ValidNames =
@@ -40,7 +41,7 @@ namespace UnityEditor.Build
"Kepler",
};
- ///Unknown.
+ ///An unknown or unspecified named build target, typically used as a placeholder.
public static readonly NamedBuildTarget Unknown = new NamedBuildTarget("");
///Desktop Standalone.
public static readonly NamedBuildTarget Standalone = new NamedBuildTarget("Standalone");
diff --git a/Editor/Mono/BuildPipeline/Settings/BuildAssetBundleOptions.bindings.cs b/Editor/Mono/BuildPipeline/Settings/BuildAssetBundleOptions.bindings.cs
index f93cc2aa61..01477b6962 100644
--- a/Editor/Mono/BuildPipeline/Settings/BuildAssetBundleOptions.bindings.cs
+++ b/Editor/Mono/BuildPipeline/Settings/BuildAssetBundleOptions.bindings.cs
@@ -33,7 +33,7 @@ public enum BuildAssetBundleOptions
// Don't compress the data when creating the asset bundle.
///Don't compress the data when creating the AssetBundle.
- ///Builds the AssetBundle without any compression, resulting in larger file sizes but faster build and load times. Uncompressed AssetBundles are 16-byte aligned.
+ ///Builds the AssetBundle without any compression, resulting in larger file sizes but faster build and load times.
///
/// See [AssetBundles compression wiki](xref:um-asset-bundles-cache), , , and .
UncompressedAssetBundle = 1, // 1 << 0
@@ -48,55 +48,42 @@ public enum BuildAssetBundleOptions
[ExcludeFromDocs]
CompleteAssets = 4, // 1 << 2
- // Do not include type information within the AssetBundle.
///Omits type information from the AssetBundle.
- ///This flag is useful for AssetBundles that are included within Player builds and are rebuilt for every new Player release.
- ///However, before using this flag, it is critical to fully understand the compatibility and redistribution implications of removing Type Trees.
- ///
- ///By default (when this flag is **not** specified), each SerializedFile inside an AssetBundle contains the Type Tree information for all types used in that file.
- ///
- ///Type Trees enable Unity to:
+ ///This flag is useful for AssetBundles that are included in Player builds and are rebuilt for every new Player release.
+ ///However, before using this flag, it is critical to fully understand the compatibility and redistribution implications of removing TypeTrees.
///
+ ///By default when this flag isn't specified, each SerializedFile inside an AssetBundle contains the TypeTree information for all types used in that file.
///
+ ///TypeTrees enable Unity to:
///
///* Load content that was built with earlier versions of Unity or with different script versions.
- ///
///* Load AssetBundles in the Editor.
///
- ///
- ///
- ///
- ///When this flag is specified only the hash of each Type Tree is recorded in the SerializedFile headers, not the entire Type Tree definition.
+ ///When this flag is specified, only the hash of each TypeTree is recorded in the SerializedFile headers, not the entire TypeTree definition.
///
///**Example**:
///
- ///Suppose an AssetBundle includes instances of a MonoBehaviour-derived class with two fields: a string `A` followed by an integer `B`.
- ///The Type Tree records the order, types and names of the fields so that the binary presentation of each serialized object of that type can be interpreted properly.
- ///
- ///Then suppose the class definition changes to include a float `C` first, followed by integer `B` and string `A`.
+ ///An AssetBundle includes instances of a MonoBehaviour-derived class with two fields: a string `A` followed by an integer `B`.
+ ///The TypeTree records the order, types and names of the fields so that the binary presentation of each serialized object of that type can be interpreted properly.
///
- ///The Type Tree inside the AssetBundle ensures that new builds of the Player can still load it, recovering the values of the `A` and `B` fields even though they do not match the current definition
- ///of that class.
+ ///If the class definition changes to include a float `C` first, followed by integer `B` and string `A`, then the TypeTree inside the
+ ///AssetBundle ensures that new builds of the Player can still load it. It recovers the values of the `A` and `B` fields even though they
+ ///don't match the current definition of that class.
///
- ///**Advantages to using DisableWriteTypeTree**:
+ ///**Advantages of using DisableWriteTypeTree**:
///
- ///Omitting Type Trees reduces AssetBundle size, which can be significant for projects with many small AssetBundles
+ ///Omitting TypeTrees reduces AssetBundle size, which can be significant for projects with many small AssetBundles
///or complex scripting types containing numerous fields or deeply nested structs.
- ///Therefore this flag can be a useful optimization in cases where you know that you will always
- ///rebuild and redistribute all AssetBundles any time that you rebuild your player.
+ ///Therefore, this flag can be a useful optimization in cases where you know that you will always
+ ///rebuild and redistribute all AssetBundles any time that you rebuild the Player.
///
///**Important Considerations**:
///
- ///AssetBundles built without Type Trees will have strict compatibility requirements:
- ///
- ///* They can only be loaded by Players built with exactly the same types. Unity verifies this by comparing Type Tree hashes at load time, and the load will fail if any mismatch is detected.
+ ///AssetBundles built without TypeTrees have strict compatibility requirements:
///
+ ///* They can only be loaded by Players built with exactly the same types. Unity verifies this by comparing TypeTree hashes at load time, and the load fails if any mismatch is detected.
///* They cannot be loaded in the Editor.
- ///* Tools like binary2text and UnityDataTools cannot view the serialized data.
- ///
- ///**Platform Limitations**
- ///
- ///For some platforms (e.g. ), Type Trees are mandatory. Unity will reject attempts to build AssetBundles with this flag for such targets.
+ ///* Tools like binary2text and UnityDataTools cannot view the serialized data.
DisableWriteTypeTree = 8, // 1 << 3
// Builds an asset bundle using a hash for the id of the object stored in the asset bundle.
@@ -137,7 +124,21 @@ public enum BuildAssetBundleOptions
// Force the build to fail when any errors are encountered
///Fails the build if any errors are reported during it.
- ///Without this flag, non-fatal errors - such as a failure to compile a shader for a particular platform - will not cause the build to fail, but may result in incorrect behaviour at runtime.
+ ///Without this flag, non-fatal errors, such as a failure to compile a shader for a particular platform, won't cause the build to fail, but might result in incorrect behavior at runtime.
+ ///
+ /// Always set this flag, unless errors are logged from packages or other third-party code that you can't fix, and you need the build to proceed despite them.
+ ///
+ /// When this flag is set, errors logged from these build callbacks also fail the build:
+ /// ,
+ /// ,
+ /// ,
+ /// , and
+ /// .
+ ///
+ /// This flag is the AssetBundle equivalent of .
+ ///
+ ///
+ ///
///
///
///
diff --git a/Editor/Mono/BuildPipeline/Settings/BuildAssetBundlesParameters.bindings.cs b/Editor/Mono/BuildPipeline/Settings/BuildAssetBundlesParameters.bindings.cs
index 987e46e690..1aa3ae2466 100644
--- a/Editor/Mono/BuildPipeline/Settings/BuildAssetBundlesParameters.bindings.cs
+++ b/Editor/Mono/BuildPipeline/Settings/BuildAssetBundlesParameters.bindings.cs
@@ -50,7 +50,6 @@ public struct BuildAssetBundlesParameters
///
///
///
- ///
public int subtarget { get; set; }
///User-specified preprocessor defines used while compiling assemblies during the AssetBundle build. (optional)
///Preprocessor defines may be used to exclude serialized fields from class definitions, so this can be have an influence on how objects are serialized during the build process.
diff --git a/Editor/Mono/BuildPipeline/Settings/BuildContentDirectoryParameters.bindings.cs b/Editor/Mono/BuildPipeline/Settings/BuildContentDirectoryParameters.bindings.cs
index aa6927314e..b82e63e32e 100644
--- a/Editor/Mono/BuildPipeline/Settings/BuildContentDirectoryParameters.bindings.cs
+++ b/Editor/Mono/BuildPipeline/Settings/BuildContentDirectoryParameters.bindings.cs
@@ -29,15 +29,17 @@ public struct BuildContentDirectoryParameters
public string outputPath { get; set; }
///
- /// Array of paths to the root Assets that should be included in the build.
+ /// Array of paths to the root assets to include in the build.
///
///
- /// This property should contain project-relative paths to existing ScriptableObject-derived Assets. Each specified
- /// Asset will be included in the build, and available for direct load. Any dependency referenced from the Asset will also
- /// be included in the build. Root assets are automatically loaded when a Content Directory is registered, so only
- /// ScriptableObject-derived assets are permitted to prevent accidental misuse (such as attempting to use large assets
- /// like Textures or Meshes as root assets).
+ /// Set this property to project-relative paths of existing -derived assets. The build
+ /// includes each specified asset along with any dependency it references. After you register the content directory, retrieve
+ /// the root assets at runtime with .
+ ///
+ /// Only ScriptableObject-derived assets are permitted as roots, to prevent accidental misuse such as using large assets
+ /// like Textures or Meshes as root assets.
///
+ ///
public string[] rootAssetPaths { get; set; }
///
@@ -48,6 +50,17 @@ public struct BuildContentDirectoryParameters
///
/// The compression settings for the build. Defaults to .
///
+ ///
+ /// With the default , the build writes the content as individual loose files
+ /// without an archive wrapper. Set to wrap the output in archive (.archive)
+ /// files instead. Any other compression setting always produces archive files.
+ ///
+ /// can load a content directory whether
+ /// its content is stored as loose files or wrapped in archive files. You can also create archive files from loose-file
+ /// output as a separate step after the build with
+ /// .
+ ///
+ ///
public BuildCompression compression { get; set; }
// Internal: optional BuildTarget. When unset at default, native code takes both platform and subtarget from current Editor build settings.
@@ -72,9 +85,14 @@ public struct BuildContentDirectoryParameters
/// Optional name for the build.
///
///
- /// This name is stored in the BuildReport and BuildManifest for identification purposes.
+ /// This name is stored in the BuildReport and BuildManifest for identification purposes. It is reported as
+ /// in the build's , and as
+ /// in the lightweight build summary.
/// If not specified, the leaf folder name of is used as the default.
///
+ ///
+ ///
+ ///
public string name { get; set; }
///
diff --git a/Editor/Mono/BuildPipeline/Settings/BuildContentOptions.bindings.cs b/Editor/Mono/BuildPipeline/Settings/BuildContentOptions.bindings.cs
index 0695dba7b8..e185bfbad9 100644
--- a/Editor/Mono/BuildPipeline/Settings/BuildContentOptions.bindings.cs
+++ b/Editor/Mono/BuildPipeline/Settings/BuildContentOptions.bindings.cs
@@ -27,7 +27,7 @@ public enum BuildContentOptions
///
/// When this flag is set, the build system will package content into archive files with the ".archive" extension,
/// which can improve loading performance and reduce file system overhead.
- ///
+ ///
/// This flag is unnecessary if compression is enabled using the field.
///
UseArchive = 1 << 0,
@@ -45,20 +45,32 @@ public enum BuildContentOptions
///
/// Clear all cached build results, resulting in a full rebuild of content.
- ///
+ ///
+ ///
///
///
CleanBuildCache = 1 << 5,
///
- /// Do not allow the build to succeed if any errors are reported during it.
+ /// Fail the build if any errors are logged while it runs.
///
///
- /// Without this flag, non-fatal errors - such as a failure to compile a shader for a particular platform - will not
- /// cause the build to fail, but may result in incorrect behaviour at runtime.
+ /// Without this flag, non-fatal errors, such as a failure to compile a shader for a particular platform, don't
+ /// cause the build to fail, but might result in incorrect behavior at runtime.
+ ///
+ /// Always set this flag, unless errors are logged from packages or other third-party code that you can't fix, and you need the build to proceed despite them.
+ ///
+ /// When this flag is set, errors logged from these build callbacks also fail the build:
+ /// ,
+ /// ,
+ /// ,
+ /// , and
+ /// .
///
- /// This flag is equivalent to .
+ /// This flag is the content directory equivalent of .
///
+ ///
+ ///
FailBuildWhenErrorsLogged = 1 << 9,
///
diff --git a/Editor/Mono/BuildPipeline/Settings/BuildOptions.bindings.cs b/Editor/Mono/BuildPipeline/Settings/BuildOptions.bindings.cs
index 7afcb1a4f4..dc5abcfa8a 100644
--- a/Editor/Mono/BuildPipeline/Settings/BuildOptions.bindings.cs
+++ b/Editor/Mono/BuildPipeline/Settings/BuildOptions.bindings.cs
@@ -44,7 +44,7 @@ public enum BuildOptions
// Do not overwrite player directory, but accept user's modifications.
///Appends to an existing Xcode (iOS) project during the build process.
- ///This preserves any changes made to the existing Xcode project settings. With the IL2CPP scripting backend, this setting also allows incremental builds of the generated C++ code to work in Xcode. Appending to Xcode projects is supported only on macOS and Windows platforms.
+ ///This preserves any changes made to the existing Xcode project settings. With the IL2CPP scripting backend, this setting also allows incremental builds of the generated C++ code to work in Xcode. Appending to Xcode projects is supported only on macOS and Windows platforms. This option applies to iOS builds; for similar behavior on Android, use instead.
///
AcceptExternalModificationsToPlayer = 1 << 5,
@@ -220,7 +220,21 @@ public enum BuildOptions
// Force the build to fail when any errors are encountered
///Prevent the build from succeeding if any errors are reported during the build process.
- ///Without this flag, non-fatal errors, such as shader compilation issues on a particular platform, won't cause the build to fail, but might lead to incorrect behavior at runtime.
+ ///Without this flag, non-fatal errors, such as shader compilation issues on a particular platform, won't cause the build to fail, but might lead to incorrect behavior at runtime.
+ ///
+ /// Set this flag in most builds. Omit it only when errors are logged from packages or other third-party code that you can't fix, and you need the build to proceed despite them.
+ ///
+ /// This flag is set automatically when you use **Build and Run** in the Editor.
+ ///
+ /// When this flag is set, errors logged from these build callbacks also fail the build:
+ /// ,
+ /// ,
+ /// ,
+ /// , and
+ /// .
+ ///
+ ///
+ ///
StrictMode = 1 << 21,
///Build will include Assemblies for testing.
diff --git a/Editor/Mono/BuildPipeline/Settings/BuildPlayerOptions.bindings.cs b/Editor/Mono/BuildPipeline/Settings/BuildPlayerOptions.bindings.cs
index 86d1b44f04..2401ff46cd 100644
--- a/Editor/Mono/BuildPipeline/Settings/BuildPlayerOptions.bindings.cs
+++ b/Editor/Mono/BuildPipeline/Settings/BuildPlayerOptions.bindings.cs
@@ -64,6 +64,11 @@ public struct BuildPlayerOptions
[NativeName("platformGroup")]
public BuildTargetGroup targetGroup { get; set; }
///The to build.
+ ///For best results, leave this property unset so that the build uses the target defined in the active . If you do set it, set it to match the active build target.
+ ///
+ ///Building a target that doesn't match the active build target is unreliable. Changing the active build target requires recompiling Editor scripts for the new platform and a domain reload, which can't happen while a build script is running. As a result, build callbacks and platform-dependent code might compile for the wrong platform, and some platforms fail to build at all.
+ ///
+ ///To select the target, set the active build profile first: use the Build Profiles window in the Editor, or the -activeBuildProfile or -buildTarget argument on the [command line](xref:um-build-command-line). For more information, refer to [Create a custom build script](xref:um-build-script-build).
///
[NativeName("platform")]
public BuildTarget target { get; set; }
@@ -84,16 +89,22 @@ public struct BuildPlayerOptions
///
///
///
- ///
public int subtarget { get; set; }
- ///Additional , like whether to run the built player.
+ ///The flags to apply when building the Player.
+ ///Set this property to a bitwise combination of values before you pass to . For example, set options = BuildOptions.Development | BuildOptions.AutoRunPlayer to create a development build and run it automatically after the build completes.
public BuildOptions options { get; set; }
///The additional preprocessor defines you can specify while compiling assemblies for the Player. These defines are appended to the existing Scripting Define Symbols list configured in the Player settings.
public string[] extraScriptingDefines { get; set; }
- ///Use this property to reference the output folders or build report directories from one or more content directory builds.
+ ///Use this property to reference the output folders or build report directories from one or more builds.
///The types used in those builds are included in the information provided to UnityLinker.
- ///This ensures that the player can load all the content from those additional builds.
+ ///This ensures that the Player can load all the content from those additional builds.
+ ///
+ ///During a build you can also add directories from a build callback with .
+ ///
+ ///For more information, refer to [How code stripping affects content](xref:um-managed-code-stripping-content).
+ ///
+ ///
public string[] previousBuildReportDirectories { get; set; }
[NativeHeader("Editor/Src/BuildPipeline/BuildPlayerOptions.h")]
diff --git a/Editor/Mono/BuildPlayerWindowBuildMethods.cs b/Editor/Mono/BuildPlayerWindowBuildMethods.cs
index 59b69f04e3..aacfc7d400 100644
--- a/Editor/Mono/BuildPlayerWindowBuildMethods.cs
+++ b/Editor/Mono/BuildPlayerWindowBuildMethods.cs
@@ -377,6 +377,14 @@ private static bool PickBuildLocation(BuildTargetGroup targetGroup, BuildTarget
defaultName = Path.GetDirectoryName(defaultName);
}
+ // Prevent file extension stacking on file extensions MacOS natively does not support
+ if (Application.platform == RuntimePlatform.OSXEditor && !String.IsNullOrEmpty(defaultName)
+ && !String.IsNullOrEmpty(extension)
+ && String.Equals(FileUtil.GetPathExtension(defaultName), extension, StringComparison.OrdinalIgnoreCase))
+ {
+ defaultName = Path.GetFileNameWithoutExtension(defaultName);
+ }
+
string title = "Build " + BuildPlatforms.instance.GetBuildTargetDisplayName(targetGroup, target, subtarget);
string path;
diff --git a/Editor/Mono/BuildProfile/BuildProfileContext.cs b/Editor/Mono/BuildProfile/BuildProfileContext.cs
index 9934c6af83..f298a810e0 100644
--- a/Editor/Mono/BuildProfile/BuildProfileContext.cs
+++ b/Editor/Mono/BuildProfile/BuildProfileContext.cs
@@ -572,19 +572,17 @@ void OnEnable()
EditorGraphicsSettings.activeProfileHasGraphicsSettings = ActiveProfileHasGraphicsSettings();
- var buildProfile = activeProfile;
+ if (activeProfile != null)
+ return;
- if (buildProfile == null)
- {
- buildProfile = GetForClassicPlatform(EditorUserBuildSettings.activePlatformGuid);
+ var buildProfile = GetForClassicPlatform(EditorUserBuildSettings.activePlatformGuid);
- // profile can be null if we're in the middle of creating classic profiles
- if (buildProfile == null)
- return;
+ // profile can be null if we're in the middle of creating classic profiles
+ if (buildProfile == null)
+ return;
- // We only copy EditorUserBuildSettings into the build profile for classic platforms as we don't want to modify actual user assets
- EditorUserBuildSettings.CopyToBuildProfile(buildProfile);
- }
+ // We only copy EditorUserBuildSettings into the build profile for classic platforms as we don't want to modify actual user assets
+ EditorUserBuildSettings.CopyToBuildProfile(buildProfile);
var extension = ModuleManager.GetBuildProfileExtension(buildProfile.platformGuid);
if (extension != null)
diff --git a/Editor/Mono/BuildProfile/BuildProfileGraphicsSettingsEditor.cs b/Editor/Mono/BuildProfile/BuildProfileGraphicsSettingsEditor.cs
index 09cbac3d80..3d491602d6 100644
--- a/Editor/Mono/BuildProfile/BuildProfileGraphicsSettingsEditor.cs
+++ b/Editor/Mono/BuildProfile/BuildProfileGraphicsSettingsEditor.cs
@@ -29,13 +29,18 @@ void OnDisable()
if (!m_ShaderBuildSettingsUI.HasUnsavedChanges)
return;
- string profileName = null;
+ var parentProfile = FindProfileStillOwningTarget();
+ if (parentProfile == null)
+ return;
+
+ m_ShaderBuildSettingsUI.HandleUnsavedChangesDialog(parentProfile.name);
+ }
+
+ BuildProfile FindProfileStillOwningTarget()
+ {
var assetPath = AssetDatabase.GetAssetPath(target);
var parentProfile = AssetDatabase.LoadMainAssetAtPath(assetPath) as BuildProfile;
- if (parentProfile != null)
- profileName = parentProfile.name;
-
- m_ShaderBuildSettingsUI.HandleUnsavedChangesDialog(profileName);
+ return parentProfile != null && parentProfile.graphicsSettings == target ? parentProfile : null;
}
public override VisualElement CreateInspectorGUI()
@@ -75,11 +80,8 @@ void BindEnumFieldWithFadeGroup(VisualElement content, string id, Action buttonC
var enumModeGroup = content.MandatoryQ($"{id}ModesGroup");
var enumModeProperty = serializedObject.FindProperty($"m_{id}Stripping");
- static bool IsModesGroupVisible(StrippingModes mode) => mode == StrippingModes.Custom;
- UIElementsEditorUtility.SetVisibility(enumModeGroup, IsModesGroupVisible((StrippingModes)enumModeProperty.intValue));
- var lightmapModesUpdate = UIElementsEditorUtility.BindSerializedProperty(enumMode, enumModeProperty,
- mode => UIElementsEditorUtility.SetVisibility(enumModeGroup, IsModesGroupVisible(mode)));
- lightmapModesUpdate?.Invoke();
+ UIElementsEditorUtility.BindSerializedProperty(enumMode, enumModeProperty,
+ mode => UIElementsEditorUtility.SetVisibility(enumModeGroup, mode == StrippingModes.Custom));
content.MandatoryQ
[Icon("UIToolkit/Icons/EnumFlagsField.png")]
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
public partial class EnumFlagsField : BaseMaskField
{
///
diff --git a/Editor/Mono/UIElements/Controls/FontDefinitionField.cs b/Editor/Mono/UIElements/Controls/FontDefinitionField.cs
index 0ae2a50c88..2b05513817 100644
--- a/Editor/Mono/UIElements/Controls/FontDefinitionField.cs
+++ b/Editor/Mono/UIElements/Controls/FontDefinitionField.cs
@@ -53,6 +53,7 @@ public FontDefinitionField(string label) : base(label, null)
{
m_TypeOptions = new Dictionary();
m_ObjectField = new ObjectField().WithClassList(objectFieldUssClassName);
+ m_ObjectField.allowBuiltinResources = false;
m_ObjectField.RegisterValueChangedCallback(OnObjectValueChange);
m_ObjectField.objectFieldDisplay.RegisterDefaultDragAndDrop(new List() { typeof(Font), typeof(FontAsset) });
diff --git a/Editor/Mono/UIElements/Controls/GradientField.cs b/Editor/Mono/UIElements/Controls/GradientField.cs
index 2dd586523d..ac73d8b788 100644
--- a/Editor/Mono/UIElements/Controls/GradientField.cs
+++ b/Editor/Mono/UIElements/Controls/GradientField.cs
@@ -3,6 +3,7 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
+using System.Collections.Generic;
using Unity.Properties;
using UnityEngine;
using UnityEditorInternal;
@@ -14,7 +15,7 @@ namespace UnityEditor.UIElements
///
/// Makes a field for editing an . For more information, refer to [[wiki:UIE-uxml-element-GradientField|UXML element GradientField]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/GradientField.png")]
public partial class GradientField : BaseField
{
@@ -127,7 +128,7 @@ internal static Gradient GradientCopy(Gradient other)
VisualElement m_GradientTextureImage;
readonly Background m_DefaultBackground = new Background();
- bool isShowingGradientPicker => GradientPicker.visible && rawValue != null && ReferenceEquals(GradientPicker.gradient, rawValue);
+ internal bool isShowingGradientPicker => GradientPicker.visible && rawValue != null && ReferenceEquals(GradientPicker.gradient, rawValue);
///
/// Constructor.
@@ -223,7 +224,7 @@ void OnAttach()
UpdateGradientTexture();
}
- void ShowGradientPicker()
+ internal void ShowGradientPicker()
{
// Re-clicking the field while the picker is already shown for it must NOT advance the
// undo group or reset our bookkeeping. GradientPicker.Show() suppresses the previous
@@ -238,16 +239,36 @@ void ShowGradientPicker()
GradientPicker.Show(rawValue, hdr, colorSpace, OnGradientChanged, OnPickerClosed);
}
+ internal event Action pickerClosed;
+
void OnPickerClosed()
{
- // Increment and name a new group before collapsing so that any redo entries created
- // by mid-session undos are truncated from the stack. (UUM-142114)
- if (m_PickerHasChanges)
+ try
{
- Undo.IncrementCurrentGroup();
- Undo.SetCurrentGroupName("Modify Gradient");
+ pickerClosed?.Invoke();
}
- Undo.CollapseUndoOperations(m_PickerUndoGroup);
+ finally
+ {
+ // Increment and name a new group before collapsing so that any redo entries created
+ // by mid-session undos are truncated from the stack. (UUM-142114)
+ if (m_PickerHasChanges && IsAnyPickerChangeApplied())
+ {
+ Undo.IncrementCurrentGroup();
+ Undo.SetCurrentGroupName("Modify Gradient");
+ }
+ Undo.CollapseUndoOperations(m_PickerUndoGroup);
+ }
+ }
+
+ // Once every picker change is undone, naming would only add an empty entry and clear redo. (UUM-153510)
+ bool IsAnyPickerChangeApplied()
+ {
+ Undo.FlushTrackedObjects();
+ if (!Undo.HasRedo())
+ return true;
+
+ Undo.GetRecords(new List(), out var undoCursor);
+ return undoCursor > 0 && Undo.GetGroupFromStack(undoCursor - 1) >= m_PickerUndoGroup;
}
// We dont want Undo operations to be combined when the picker is still open so we will handle the collapsing. (UUM-142114)
@@ -275,7 +296,7 @@ void UpdateGradientTexture()
}
}
- void OnGradientChanged(Gradient newValue)
+ internal void OnGradientChanged(Gradient newValue)
{
m_PickerHasChanges = true;
m_ForceSendEvent = true;
diff --git a/Editor/Mono/UIElements/Controls/LayerField.cs b/Editor/Mono/UIElements/Controls/LayerField.cs
index 1e633a6c08..5c08fc44ee 100644
--- a/Editor/Mono/UIElements/Controls/LayerField.cs
+++ b/Editor/Mono/UIElements/Controls/LayerField.cs
@@ -15,7 +15,7 @@ namespace UnityEditor.UIElements
/// A LayerField editor. For more information, refer to [[wiki:UIE-uxml-element-LayerField|UXML element LayerField]].
///
[Icon("UIToolkit/Icons/LayerField.png")]
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
public partial class LayerField : PopupField
{
[UxmlAttribute("value"), LayerDecorator]
@@ -31,6 +31,10 @@ public override int value
get { return base.value; }
set
{
+ // Assign m_Choices directly: the choices property setter would recurse via SetValueWithoutNotify
+ if (!m_Choices.Contains(value))
+ m_Choices = InitializeLayers();
+
if (m_Choices.Contains(value))
{
base.value = value;
@@ -74,6 +78,10 @@ public override Func formatListItemCallback
public override void SetValueWithoutNotify(int newValue)
{
+ // Assign m_Choices directly: the choices property setter would recurse via SetValueWithoutNotify
+ if (!m_Choices.Contains(newValue))
+ m_Choices = InitializeLayers();
+
if (m_Choices.Contains(newValue))
{
base.SetValueWithoutNotify(newValue);
diff --git a/Editor/Mono/UIElements/Controls/LayerMaskField.cs b/Editor/Mono/UIElements/Controls/LayerMaskField.cs
index eeef9459b4..cabc888bd8 100644
--- a/Editor/Mono/UIElements/Controls/LayerMaskField.cs
+++ b/Editor/Mono/UIElements/Controls/LayerMaskField.cs
@@ -14,7 +14,7 @@ namespace UnityEditor.UIElements
/// A LayerMaskField editor. For more information, refer to [[wiki:UIE-uxml-element-LayerMaskField|UXML element LayerMaskField]].
///
[Icon("UIToolkit/Icons/LayerMaskField.png")]
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
public partial class LayerMaskField : MaskField
{
[UxmlAttribute("choices"), UxmlAttributeBindingPath(nameof(choices)), HideInInspector]
diff --git a/Editor/Mono/UIElements/Controls/ObjectField.cs b/Editor/Mono/UIElements/Controls/ObjectField.cs
index 03069428d2..419823f761 100644
--- a/Editor/Mono/UIElements/Controls/ObjectField.cs
+++ b/Editor/Mono/UIElements/Controls/ObjectField.cs
@@ -16,7 +16,7 @@ namespace UnityEditor.UIElements
///
/// Makes a field to receive any object type. For more information, refer to [[wiki:UIE-uxml-element-ObjectField|UXML element ObjectField]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ObjectField.png")]
public partial class ObjectField : BaseField
{
diff --git a/Editor/Mono/UIElements/Controls/PropertyField.cs b/Editor/Mono/UIElements/Controls/PropertyField.cs
index fa420355fc..8150e57c60 100644
--- a/Editor/Mono/UIElements/Controls/PropertyField.cs
+++ b/Editor/Mono/UIElements/Controls/PropertyField.cs
@@ -18,7 +18,7 @@ namespace UnityEditor.UIElements
/// A SerializedProperty wrapper VisualElement that, on [[BindingExtensions.Bind|Bind()]], will generate the correct field elements with the correct binding paths. For more information, refer to [[wiki:UIE-uxml-element-PropertyField|UXML element PropertyField]].
///
[Icon("UIToolkit/Icons/PropertyField.png")]
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
public partial class PropertyField : VisualElement, IBindable
{
static readonly BindingId labelProperty = nameof(label);
@@ -33,6 +33,7 @@ public partial class PropertyField : VisualElement, IBindable
static readonly string listViewNamePrefix = "unity-list-";
static readonly string buttonGroupNamePrefix = "unity-button-group-";
+ static readonly UniqueStyleString toggleButtonGroupFixedSizeUssClassNameUnique = new(ToggleButtonGroup.ussClassName + "--fixed-size");
///
/// Binding object that will be updated.
@@ -335,6 +336,14 @@ void ResetInternal(SerializedProperty newProperty)
else
{
RegisterPropertyChangesOnCustomDrawerElement(customPropertyGUI);
+
+ // Bind a custom drawer's root foldout to its expanded state (like the default drawer) so recursive expand/collapse reaches it.
+ if (customPropertyGUI is Foldout customFoldout
+ && string.IsNullOrEmpty(customFoldout.bindingPath)
+ && m_SerializedProperty.hasChildren)
+ {
+ customFoldout.bindingPath = m_SerializedProperty.propertyPath;
+ }
}
}
else
@@ -829,56 +838,71 @@ private VisualElement ConfigureLabelOnly(SerializedProperty property)
private static readonly Action SetListViewHeaderTitle = (view, s) => view.headerTitle = s;
private static readonly Action SetFoldoutText = (f, s) => f.text = s;
+ private EventCallback m_DebugAltKeyDownCallback;
+ private EventCallback m_DebugAltKeyUpCallback;
+
private void ConfigureDebugHelpers(TField field) where TField : BaseField
{
field.RegisterCallback>(AttachDebugCallbackOnPanel, (f, s) => f.label = s);
- field.RegisterCallback(DetachDebugCallbackFromPanel);
+ field.RegisterCallback(DetachDebugCallbackFromPanel);
}
private void ConfigureFoldoutDebugHelpers(Foldout view)
{
view.RegisterCallback>(AttachDebugCallbackOnPanel, SetFoldoutText);
- view.RegisterCallback(DetachDebugCallbackFromPanel);
+ view.RegisterCallback(DetachDebugCallbackFromPanel);
}
private void ConfigureListViewDebugHelpers(BaseListView view)
{
view.RegisterCallback>(AttachDebugCallbackOnPanel, SetListViewHeaderTitle);
- view.RegisterCallback(DetachDebugCallbackFromPanel);
+ view.RegisterCallback(DetachDebugCallbackFromPanel);
}
private void AttachDebugCallbackOnPanel(AttachToPanelEvent evt, Action setLabelAction)
- where T:VisualElement
+ where T : VisualElement
{
if (evt.destinationPanel == null)
return;
- var p = evt.destinationPanel;
+
+ var visualTree = evt.destinationPanel.visualTree;
var field = evt.elementTarget as T;
- var propertyPath = serializedProperty.propertyPath;
- var regularLabel = label ?? serializedProperty.localizedDisplayName;
- p.visualTree.RegisterCallback((e, f) =>
+
+ UnregisterDebugAltCallbacks(visualTree);
+
+ // A pooled list item can re-attach before being rebound, so read serializedProperty on key events and guard with isValid. (UUM-143676)
+ m_DebugAltKeyDownCallback = e =>
{
- if (e.altKey)
- {
- setLabelAction.Invoke(f, propertyPath);
- }
- }, field, TrickleDown.TrickleDown);
- p.visualTree.RegisterCallback((e, f) =>
+ if (e.altKey && serializedProperty.isValid)
+ setLabelAction.Invoke(field, serializedProperty.propertyPath);
+ };
+ m_DebugAltKeyUpCallback = e =>
{
if (!e.altKey)
- {
- setLabelAction.Invoke(f, regularLabel);
- }
- }, field, TrickleDown.TrickleDown);
+ setLabelAction.Invoke(field, label ?? (serializedProperty.isValid ? serializedProperty.localizedDisplayName : null));
+ };
+
+ visualTree.RegisterCallback(m_DebugAltKeyDownCallback, TrickleDown.TrickleDown);
+ visualTree.RegisterCallback(m_DebugAltKeyUpCallback, TrickleDown.TrickleDown);
}
- private void DetachDebugCallbackFromPanel(DetachFromPanelEvent evt)
- where T:VisualElement
+ private void DetachDebugCallbackFromPanel(DetachFromPanelEvent evt)
{
if (evt.originPanel != null)
+ UnregisterDebugAltCallbacks(evt.originPanel.visualTree);
+ }
+
+ private void UnregisterDebugAltCallbacks(VisualElement visualTree)
+ {
+ if (m_DebugAltKeyDownCallback != null)
{
- evt.originPanel.visualTree.UnregisterCallback>(AttachDebugCallbackOnPanel);
- evt.originPanel.visualTree.UnregisterCallback(DetachDebugCallbackFromPanel);
+ visualTree.UnregisterCallback(m_DebugAltKeyDownCallback, TrickleDown.TrickleDown);
+ m_DebugAltKeyDownCallback = null;
+ }
+ if (m_DebugAltKeyUpCallback != null)
+ {
+ visualTree.UnregisterCallback(m_DebugAltKeyUpCallback, TrickleDown.TrickleDown);
+ m_DebugAltKeyUpCallback = null;
}
}
@@ -931,17 +955,13 @@ VisualElement ConfigureListView(ListView listView, SerializedProperty property,
return listView;
}
- VisualElement ConfigureToggleButtonGroup(ToggleButtonGroup buttonGroup, SerializedProperty property, Func factory)
+ VisualElement ConfigureToggleButtonGroup(SerializedProperty property)
{
var propertyCopy = property.Copy();
- if (buttonGroup == null)
- {
- buttonGroup = factory();
- buttonGroup.AddToClassList(BaseField.alignedFieldUssClassName);
- buttonGroup.AddToClassList(ToggleButtonGroup.ussClassName + "--fixed-size");
- buttonGroup.RegisterValueChangedCallback(OnToggleGroupChanged);
- }
+ var buttonGroup = new ToggleButtonGroup();
+ buttonGroup.AddToClassList(BaseField.alignedFieldUssClassNameUnique);
+ buttonGroup.AddToClassList(toggleButtonGroupFixedSizeUssClassNameUnique);
var lengthProperty = propertyCopy.FindPropertyRelative("m_Length");
var dataProperty = propertyCopy.FindPropertyRelative("m_Data");
@@ -974,7 +994,15 @@ VisualElement ConfigureToggleButtonGroup(ToggleButtonGroup buttonGroup, Serializ
buttonGroup.SetProperty(BaseField.serializedPropertyCopyName, propertyCopy);
buttonGroup.name = buttonGroupName;
buttonGroup.label = fieldLabel;
- buttonGroup.Q(className: ToggleButtonGroup.buttonGroupClassName).Clear();
+
+ for (var i = 0; i < length; i++)
+ {
+ buttonGroup.Add(new Button { text = i.ToString() });
+ }
+
+ // Discard the adjustments populating made, then start reporting changes.
+ buttonGroup.SetValueWithoutNotify((ToggleButtonGroupState)propertyCopy.structValue);
+ buttonGroup.RegisterValueChangedCallback(OnToggleGroupChanged);
// Track changes to the ToggleButtonGroupState values.
buttonGroup.TrackPropertyValue(propertyCopy);
@@ -982,13 +1010,14 @@ VisualElement ConfigureToggleButtonGroup(ToggleButtonGroup buttonGroup, Serializ
buttonGroup.TrackPropertyValue(lengthProperty, OnPropertyChanged);
buttonGroup.TrackPropertyValue(dataProperty, OnPropertyChanged);
- for (var i = 0; i < length; i++)
- {
- buttonGroup.Add(new Button { text = i.ToString() });
- }
-
void OnToggleGroupChanged(ChangeEvent evt)
{
+ var current = (ToggleButtonGroupState)propertyCopy.structValue;
+
+ // Writing an unchanged value dirties the asset and rebuilds the inspector, which loops.
+ if (evt.newValue.Equals(current))
+ return;
+
propertyCopy.structValue = evt.newValue;
propertyCopy.serializedObject.ApplyModifiedPropertiesWithoutUndo();
}
@@ -1030,6 +1059,12 @@ void OnPropertyChanged(SerializedProperty _)
return buttonGroup;
}
+ // Named (not lambda) so -= matches on re-subscribe: the field is reused across rebinds and onValidateValue persists.
+ static uint ClampToUShort(uint v) => Math.Min(v, ushort.MaxValue);
+ static uint ClampToByte(uint v) => Math.Min(v, byte.MaxValue);
+ static int ClampToShort(int v) => Mathf.Clamp(v, short.MinValue, short.MaxValue);
+ static int ClampToSByte(int v) => Mathf.Clamp(v, sbyte.MinValue, sbyte.MaxValue);
+
private VisualElement CreateOrUpdateFieldFromProperty(SerializedProperty property, object originalField = null)
{
var propertyType = property.propertyType;
@@ -1060,23 +1095,23 @@ private VisualElement CreateOrUpdateFieldFromProperty(SerializedProperty propert
if (uintField != null)
{
+ // Remove both first: the field can be reused for another integer subtype, so drop any stale clamp.
+ uintField.onValidateValue -= ClampToUShort;
+ uintField.onValidateValue -= ClampToByte;
switch (property.type)
{
case "ushort":
- uintField.onValidateValue += v => Math.Min(v, ushort.MaxValue);
+ uintField.onValidateValue += ClampToUShort;
break;
case "byte":
- uintField.onValidateValue += v => Math.Min(v, byte.MaxValue);
+ uintField.onValidateValue += ClampToByte;
break;
- default:
- break;
-
}
-
+
}
return uintField;
}
-
+
{
var intField = ConfigureField(originalField as IntegerField, property,
() => new IntegerField()) as IntegerField;
@@ -1086,17 +1121,17 @@ private VisualElement CreateOrUpdateFieldFromProperty(SerializedProperty propert
// If the field was recycled from an ArraySize property
intField.isDelayed = false;
+ intField.onValidateValue -= ClampToShort;
+ intField.onValidateValue -= ClampToSByte;
switch (property.type)
{
case "short":
- intField.onValidateValue += v => Mathf.Clamp(v, short.MinValue, short.MaxValue);
+ intField.onValidateValue += ClampToShort;
break;
case "sbyte":
- intField.onValidateValue += v => Mathf.Clamp(v, sbyte.MinValue, sbyte.MaxValue);
+ intField.onValidateValue += ClampToSByte;
break;
- default:
- break;
- }
+ }
}
return intField;
@@ -1304,7 +1339,7 @@ private VisualElement CreateOrUpdateFieldFromProperty(SerializedProperty propert
case SerializedPropertyType.Generic:
if (property.type == nameof(ToggleButtonGroupState))
{
- return ConfigureToggleButtonGroup(originalField as ToggleButtonGroup, property, () => new ToggleButtonGroup());
+ return ConfigureToggleButtonGroup(property);
}
return property.isArray
diff --git a/Editor/Mono/UIElements/Controls/TagField.cs b/Editor/Mono/UIElements/Controls/TagField.cs
index 666e90c0da..a7465b4f74 100644
--- a/Editor/Mono/UIElements/Controls/TagField.cs
+++ b/Editor/Mono/UIElements/Controls/TagField.cs
@@ -15,7 +15,7 @@ namespace UnityEditor.UIElements
/// A editor. For more information, refer to [[wiki:UIE-uxml-element-TagField|UXML element TagField]].
///
[Icon("UIToolkit/Icons/TagField.png")]
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
public partial class TagField : PopupField
{
internal override string GetValueToDisplay()
@@ -41,6 +41,10 @@ public override string value
get { return base.value; }
set
{
+ // Assign m_Choices directly: the choices property setter would recurse via SetValueWithoutNotify
+ if (!m_Choices.Contains(value))
+ m_Choices = InitializeTags();
+
// Allow the setting of value outside of Tags, but do nothing with them...
if (m_Choices.Contains(value))
{
@@ -51,6 +55,10 @@ public override string value
public override void SetValueWithoutNotify(string newValue)
{
+ // Assign m_Choices directly: the choices property setter would recurse via SetValueWithoutNotify
+ if (!m_Choices.Contains(newValue))
+ m_Choices = InitializeTags();
+
// Allow the setting of value outside of Tags, but do nothing with them...
if (m_Choices.Contains(newValue))
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/Toolbar.cs b/Editor/Mono/UIElements/Controls/Toolbar/Toolbar.cs
index f611cdafcf..fb54e42c8e 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/Toolbar.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/Toolbar.cs
@@ -12,7 +12,7 @@ namespace UnityEditor.UIElements
///
/// A toolbar for tool windows. For more information, refer to [[wiki:UIE-uxml-element-Toolbar|UXML element Toolbar]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/Toolbar.png")]
public partial class Toolbar : VisualElement
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarBreadcrumbs.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarBreadcrumbs.cs
index ebf5f867ce..3bd6ded06e 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarBreadcrumbs.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarBreadcrumbs.cs
@@ -47,7 +47,7 @@ namespace UnityEditor.UIElements
/// ]]>
///
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarBreadcrumbs.png")]
public partial class ToolbarBreadcrumbs : VisualElement
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarButton.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarButton.cs
index 266e30f872..76e91e3257 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarButton.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarButton.cs
@@ -22,7 +22,7 @@ namespace UnityEditor.UIElements
///
/// SA: [[Button]], [[Toolbar]]
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarButton.png")]
public partial class ToolbarButton : Button
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarMenu.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarMenu.cs
index eedf40b2ed..07fd572f13 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarMenu.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarMenu.cs
@@ -13,7 +13,7 @@ namespace UnityEditor.UIElements
///
/// A drop-down menu for the toolbar. For more information, refer to [[wiki:UIE-uxml-element-ToolbarMenu|UXML element ToolbarMenu]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarMenu.png")]
public partial class ToolbarMenu : TextElement, IToolbarMenuElement
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarPopupSearchField.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarPopupSearchField.cs
index a4b8f7cd77..665decd57e 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarPopupSearchField.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarPopupSearchField.cs
@@ -13,7 +13,7 @@ namespace UnityEditor.UIElements
///
/// The pop-up search field for the toolbar. The search field includes a menu button. For more information, refer to [[wiki:UIE-uxml-element-ToolbarPopupSearchField|UXML element ToolbarPopupSearchField]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarPopupSearchField.png")]
public partial class ToolbarPopupSearchField : ToolbarSearchField, IToolbarMenuElement
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSearchField.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSearchField.cs
index 58ff38ebbc..a3b541388b 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSearchField.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSearchField.cs
@@ -12,7 +12,7 @@ namespace UnityEditor.UIElements
///
/// A search field for the toolbar. For more information, refer to [[wiki:UIE-uxml-element-ToolbarSearchField|UXML element ToolbarSearchField]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarSearchField.png")]
public partial class ToolbarSearchField : SearchFieldBase
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSpacer.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSpacer.cs
index 0c4dd5251c..7ae6512b54 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSpacer.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarSpacer.cs
@@ -13,7 +13,7 @@ namespace UnityEditor.UIElements
///
/// A toolbar spacer of static size. For more information, refer to [[wiki:UIE-uxml-element-ToolbarSpacer|UXML element ToolbarSpacer]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarSpacer.png")]
public partial class ToolbarSpacer : VisualElement
{
diff --git a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarToggle.cs b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarToggle.cs
index afb9f4fa31..23e4d34733 100644
--- a/Editor/Mono/UIElements/Controls/Toolbar/ToolbarToggle.cs
+++ b/Editor/Mono/UIElements/Controls/Toolbar/ToolbarToggle.cs
@@ -12,7 +12,7 @@ namespace UnityEditor.UIElements
///
/// A toggle for the toolbar. For more information, refer to [[wiki:UIE-uxml-element-ToolbarToggle|UXML element ToolbarToggle]].
///
- [UxmlElement]
+ [UxmlElement(visibility = LibraryVisibility.Visible)]
[Icon("UIToolkit/Icons/ToolbarToggle.png")]
public partial class ToolbarToggle : Toggle
{
diff --git a/Editor/Mono/UIElements/Drawers/Internal/UnityEventItem.cs b/Editor/Mono/UIElements/Drawers/Internal/UnityEventItem.cs
index a52bdc4b13..46b0b0f2e4 100644
--- a/Editor/Mono/UIElements/Drawers/Internal/UnityEventItem.cs
+++ b/Editor/Mono/UIElements/Drawers/Internal/UnityEventItem.cs
@@ -17,11 +17,11 @@ public struct PropertyData
{
public SerializedProperty listener;
public SerializedProperty mode;
- public SerializedProperty arguments;
public SerializedProperty callState;
public SerializedProperty listenerTarget;
public SerializedProperty methodName;
public SerializedProperty objectArgument;
+ public SerializedProperty objectArgumentAssemblyTypeName;
}
// uss names
@@ -38,6 +38,10 @@ public struct PropertyData
PropertyData m_PropertyData;
+ bool m_HasAppliedParameterField;
+ PersistentListenerMode m_AppliedMode;
+ string m_AppliedObjectArgumentTypeName;
+
public PropertyField callStateDropdown
{
get;
@@ -144,7 +148,7 @@ public UnityEventItem()
internal void BindFields(PropertyData data)
{
- // As this is a reusable item in a ListView, we need to unbind as you can only TrackPropertyValue on one property at a time
+ // As this is a reusable item in a ListView, we need to unbind as an element can only track properties on one SerializedObject at a time
listenerTarget.Unbind();
m_PropertyData = data;
@@ -164,13 +168,16 @@ internal void BindFields(PropertyData data)
functionDropdown.SetValueWithoutNotify(functionDropdown.value);
});
+ // Variants of one function share a method name, and per-property tracking never reports the mode change.
+ listenerTarget.TrackSerializedObjectValue(m_PropertyData.listener.serializedObject, _ => UpdateParameterField());
+
+ m_HasAppliedParameterField = false;
UpdateParameterField();
}
internal void UpdateParameterField()
{
var modeEnum = (PersistentListenerMode)m_PropertyData.mode.enumValueIndex;
- var argument = getArgumentCallback.Invoke(m_PropertyData);
//only allow argument if we have a valid target / method
if (m_PropertyData.listenerTarget.objectReferenceValue == null || string.IsNullOrEmpty(m_PropertyData.methodName.stringValue))
@@ -178,6 +185,22 @@ internal void UpdateParameterField()
modeEnum = PersistentListenerMode.Void;
}
+ var objectArgumentTypeName = modeEnum == PersistentListenerMode.Object
+ ? m_PropertyData.objectArgumentAssemblyTypeName.stringValue
+ : null;
+
+ // This runs on every edit to the object, so only rebuild when the shown field would actually differ.
+ if (m_HasAppliedParameterField && modeEnum == m_AppliedMode && objectArgumentTypeName == m_AppliedObjectArgumentTypeName)
+ {
+ return;
+ }
+
+ m_HasAppliedParameterField = true;
+ m_AppliedMode = modeEnum;
+ m_AppliedObjectArgumentTypeName = objectArgumentTypeName;
+
+ var argument = getArgumentCallback.Invoke(m_PropertyData);
+
if (modeEnum == PersistentListenerMode.Void || modeEnum == PersistentListenerMode.EventDefined)
{
parameterProperty.style.display = DisplayStyle.None;
@@ -188,12 +211,11 @@ internal void UpdateParameterField()
parameterProperty.style.display = DisplayStyle.None;
objectParameter.style.display = DisplayStyle.Flex;
- var desiredArgTypeName = m_PropertyData.arguments.FindPropertyRelative(UnityEventDrawer.kObjectArgumentAssemblyTypeName).stringValue;
var desiredType = typeof(UnityEngine.Object);
- if (!string.IsNullOrEmpty(desiredArgTypeName))
+ if (!string.IsNullOrEmpty(objectArgumentTypeName))
{
- desiredType = Type.GetType(desiredArgTypeName, false) ?? typeof(UnityEngine.Object);
+ desiredType = Type.GetType(objectArgumentTypeName, false) ?? typeof(UnityEngine.Object);
}
objectParameter.objectType = desiredType;
diff --git a/Editor/Mono/UIElements/Inspector/InspectorElement.cs b/Editor/Mono/UIElements/Inspector/InspectorElement.cs
index 52081dca7e..33442f6927 100644
--- a/Editor/Mono/UIElements/Inspector/InspectorElement.cs
+++ b/Editor/Mono/UIElements/Inspector/InspectorElement.cs
@@ -290,13 +290,13 @@ internal InspectorElement(Editor editor, DefaultInspectorFramework defaultInspec
prefabOverrideBlueBarsContainer = new VisualElement
{
name = BindingExtensions.prefabOverrideBarContainerName,
- style = { position = Position.Absolute }
+ pickingMode = PickingMode.Ignore
};
livePropertyYellowBarsContainer = new VisualElement
{
name = BindingExtensions.livePropertyBarContainerName,
- style = { position = Position.Absolute }
+ pickingMode = PickingMode.Ignore
};
Add(prefabOverrideBlueBarsContainer);
diff --git a/Editor/Mono/UIElements/StyleSheets/StyleSheetImporter.cs b/Editor/Mono/UIElements/StyleSheets/StyleSheetImporter.cs
index 099458ea1a..b4f8630fba 100644
--- a/Editor/Mono/UIElements/StyleSheets/StyleSheetImporter.cs
+++ b/Editor/Mono/UIElements/StyleSheets/StyleSheetImporter.cs
@@ -109,6 +109,8 @@ class StyleSheetImporterEditor : ScriptedImporterEditor
public override void OnEnable()
{
base.OnEnable();
+ if (!AreImporterTargetsValid()) // asset gone: base already logged and bailed
+ return;
m_DisableValidation = serializedObject.FindProperty("disableValidation");
m_UnsupportedSelectorAction = serializedObject.FindProperty("unsupportedSelectorAction");
diff --git a/Editor/Mono/UIElements/StyleSheets/StyleSheetImporterImpl.cs b/Editor/Mono/UIElements/StyleSheets/StyleSheetImporterImpl.cs
index 2a3780dfb2..4fd24f8be4 100644
--- a/Editor/Mono/UIElements/StyleSheets/StyleSheetImporterImpl.cs
+++ b/Editor/Mono/UIElements/StyleSheets/StyleSheetImporterImpl.cs
@@ -581,6 +581,32 @@ void VisitUrlFunction(string path)
}
}
+ static bool HasEmptyArgument(FunctionToken functionToken)
+ {
+ bool hasToken = false;
+ bool previousWasComma = true;
+ foreach (var token in functionToken.ArgumentTokens)
+ {
+ if (token.Type == TokenType.Whitespace)
+ continue;
+
+ hasToken = true;
+
+ if (token.Type == TokenType.Comma)
+ {
+ if (previousWasComma)
+ return true;
+ previousWasComma = true;
+ }
+ else
+ {
+ previousWasComma = false;
+ }
+ }
+
+ return hasToken && previousWasComma;
+ }
+
bool ValidateFunction(FunctionToken functionToken, out StyleValueFunction func)
{
func = StyleValueFunction.Unknown;
@@ -609,6 +635,12 @@ bool ValidateFunction(FunctionToken functionToken, out StyleValueFunction func)
return false;
}
+ if (HasEmptyArgument(functionToken))
+ {
+ m_Errors.AddValidationWarning(glossary.emptyFunctionArgument, functionToken.Position.Line, functionToken.Position.Column);
+ return false;
+ }
+
return true;
}
@@ -911,6 +943,13 @@ void VisitCustomFilter(FunctionToken functionToken)
bool TryCreateColorFromFunctionToken(FunctionToken functionToken, int expectedChannels, out Color color)
{
+ color = default;
+ if (HasEmptyArgument(functionToken))
+ {
+ m_Errors.AddValidationWarning(glossary.emptyFunctionArgument, functionToken.Position.Line, functionToken.Position.Column);
+ return false;
+ }
+
// We expect colors in the form rgba(int, int, int, float) or rgba(float, float, float, float)
// Extract the channels as float values and determine if the rgb format is int or float
@@ -1226,6 +1265,9 @@ void VisitSheet(ParserStyleSheet styleSheet)
// Note: we must rely on recursion to correctly handle parser types here
VisitBaseSelector(rule.Selector);
+ foreach (var nestedRule in rule.NestedRules)
+ m_Errors.AddSemanticError(StyleSheetImportErrorCode.UnsupportedSelectorFormat, string.Format(glossary.unsupportedSelectorFormat, nestedRule.SelectorText), m_CurrentLine);
+
foreach (var property in rule.Style.Declarations)
{
// Property doesnt seem to have a position. StylesheetText is always null.
@@ -1292,6 +1334,12 @@ void VisitBaseSelector(ISelector selector)
VisitUnknownSelector(unknownSelector);
break;
+ case NotSelector:
+ case HasSelector:
+ case MatchesSelector:
+ m_Errors.AddSemanticError(StyleSheetImportErrorCode.RecursiveSelectorDetected, string.Format(glossary.unsupportedSelectorFormat, selector.Text), m_CurrentLine);
+ break;
+
default:
m_Errors.AddSemanticError(StyleSheetImportErrorCode.UnsupportedSelectorFormat, string.Format(glossary.unsupportedSelectorFormat, $"{selector.GetType().Name}: `{selector.Text}`"), m_CurrentLine);
break;
@@ -1374,6 +1422,12 @@ bool TryExtractSelectorsParts(Selectors selectors, out StyleSelectorPart[] parts
break;
}
+ case NotSelector:
+ case HasSelector:
+ case MatchesSelector:
+ m_Errors.AddSemanticError(StyleSheetImportErrorCode.RecursiveSelectorDetected, string.Format(glossary.unsupportedSelectorFormat, selectors.Text), m_CurrentLine);
+ return false;
+
case TypeSelector typeSelector:
parts[i] = StyleSelectorPart.CreateType(typeSelector.Name);
break;
diff --git a/Editor/Mono/UIElements/StyleSheets/StyleSheetResourceUtil.cs b/Editor/Mono/UIElements/StyleSheets/StyleSheetResourceUtil.cs
index 737f12550a..4888b6719a 100644
--- a/Editor/Mono/UIElements/StyleSheets/StyleSheetResourceUtil.cs
+++ b/Editor/Mono/UIElements/StyleSheets/StyleSheetResourceUtil.cs
@@ -49,6 +49,7 @@ public static Object LoadResource(string pathName, System.Type type, float displ
if (type == typeof(Sprite))
{
// Special case for sprites, which are stored as Texture2D sub-assets
+ // Note: the path manipulation causes an allocation on every call
var spriteResource = Resources.Load(Path.GetFileNameWithoutExtension(pathName), type);
if (spriteResource != null)
resource = spriteResource;
diff --git a/Editor/Mono/UIElements/StyleSheets/ThemeStyleSheetImporterEditor.cs b/Editor/Mono/UIElements/StyleSheets/ThemeStyleSheetImporterEditor.cs
index cc2fc9809c..6b5a0fb05e 100644
--- a/Editor/Mono/UIElements/StyleSheets/ThemeStyleSheetImporterEditor.cs
+++ b/Editor/Mono/UIElements/StyleSheets/ThemeStyleSheetImporterEditor.cs
@@ -27,6 +27,8 @@ class ThemeStyleSheetImporterEditor : ScriptedImporterEditor
public override void OnEnable()
{
base.OnEnable();
+ if (!AreImporterTargetsValid()) // asset gone: base already logged and bailed
+ return;
m_StyleSheetsProperty = extraDataSerializedObject.FindProperty("StyleSheets");
m_InheritedThemesProperty = extraDataSerializedObject.FindProperty("InheritedThemes");
diff --git a/Editor/Mono/UIElements/UIElementsEditorUtility.cs b/Editor/Mono/UIElements/UIElementsEditorUtility.cs
index 9b8c1da759..743bd2cd2b 100644
--- a/Editor/Mono/UIElements/UIElementsEditorUtility.cs
+++ b/Editor/Mono/UIElements/UIElementsEditorUtility.cs
@@ -187,7 +187,6 @@ internal static Action BindSerializedProperty(BaseField field, SerializedP
where T : struct
{
BindingsStyleHelpers.RegisterRightClickMenu(field, property);
- field.TrackPropertyValue(property);
field.AddToClassList(BaseField.alignedFieldUssClassName);
field.RegisterValueChangedCallback(e =>
@@ -195,12 +194,19 @@ internal static Action BindSerializedProperty(BaseField field, SerializedP
setter.Invoke(e.newValue, property);
});
+ // External-sync path. Must be non-notifying (SetValueWithoutNotify) so that refreshing the
+ // field from the property — e.g. on Reset/Undo via TrackPropertyValue, or manual polling by
+ // consumers like CameraEditor — does not raise the value-changed callback above, which would
+ // re-apply the property and push a new Undo step (wiping the Redo stack). See UUM-139005.
var updateCallback = () =>
{
- field.value = getter.Invoke(property);
+ var newValue = getter.Invoke(property);
+ if (!EqualityComparer.Default.Equals(field.value, newValue))
+ field.SetValueWithoutNotify(newValue);
field.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(field, property));
};
- updateCallback?.Invoke();
+ updateCallback.Invoke();
+ field.TrackPropertyValue(property, _ => updateCallback());
return updateCallback;
}
@@ -213,8 +219,6 @@ internal static Action BindSerializedProperty(DropdownField dropdown, Serialized
foreach (var val in stringValues)
dropdown.choices.Add(val.text);
- dropdown.TrackPropertyValue(property);
-
return BindSerializedProperty(dropdown, property, p =>
{
var value = boolProperty ? (property.boolValue ? 1 : 0) : property.intValue;
@@ -235,7 +239,6 @@ internal static Action BindSerializedProperty(DropdownField dropdown, Serialized
internal static Action BindSerializedProperty(DropdownField dropdown, SerializedProperty property, Func getter, Action setter)
{
BindingsStyleHelpers.RegisterRightClickMenu(dropdown, property);
- dropdown.TrackPropertyValue(property);
dropdown.AddToClassList(BaseField.alignedFieldUssClassName);
dropdown.RegisterValueChangedCallback(e =>
@@ -243,12 +246,16 @@ internal static Action BindSerializedProperty(DropdownField dropdown, Serialized
setter.Invoke(dropdown.index, property);
});
+ // External-sync path — see the note on the BaseField overload above (UUM-139005).
var updateCallback = () =>
{
- dropdown.index = getter.Invoke(property);
+ var newIndex = getter.Invoke(property);
+ if (dropdown.index != newIndex)
+ dropdown.SetIndexWithoutNotify(newIndex);
dropdown.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(dropdown, property));
};
- updateCallback?.Invoke();
+ updateCallback.Invoke();
+ dropdown.TrackPropertyValue(property, _ => updateCallback());
return updateCallback;
}
@@ -269,24 +276,31 @@ internal static Action BindSerializedProperty(EnumField enumField, Serialized
property.serializedObject.ApplyModifiedProperties();
onValueChange?.Invoke((T)e.newValue);
+ enumField.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(enumField, property));
});
+ // External-sync path. Uses SetValueWithoutNotify so refreshing from the property (Reset/Undo
+ // via TrackPropertyValue, or manual polling) doesn't raise the value-changed callback and
+ // re-apply the property — that would push a new Undo step and wipe the Redo stack (UUM-139005).
+ // Because the callback won't fire, onValueChange is invoked here so visibility/grouping side
+ // effects still run. The initialized flag fires onValueChange once for the initial setup, then
+ // only on genuine external changes — user-driven changes already fired it via the callback above.
+ bool initialized = false;
var updateCallback = () =>
{
- foreach (T value in Enum.GetValues(typeof(T)))
+ var propertyValue = boolProperty ? (property.boolValue ? 1 : 0) : property.intValue;
+ var value = (T)Enum.ToObject(typeof(T), propertyValue);
+ if (!initialized || !enumField.value.Equals(value))
{
- var propertyValue = boolProperty ? (property.boolValue ? 1 : 0) : property.intValue;
-
- if (value.ToInt32(null) != propertyValue)
- continue;
-
- enumField.value = value;
- break;
+ enumField.SetValueWithoutNotify(value);
+ onValueChange?.Invoke(value);
}
+ initialized = true;
enumField.schedule.Execute(() => BindingsStyleHelpers.UpdateElementStyle(enumField, property));
};
- updateCallback?.Invoke();
+ updateCallback.Invoke();
+ enumField.TrackPropertyValue(property, _ => updateCallback());
return updateCallback;
}
diff --git a/Editor/Mono/UnityConnect/UnityConnect.bindings.cs b/Editor/Mono/UnityConnect/UnityConnect.bindings.cs
index bf465f6fb3..55b38e7931 100644
--- a/Editor/Mono/UnityConnect/UnityConnect.bindings.cs
+++ b/Editor/Mono/UnityConnect/UnityConnect.bindings.cs
@@ -31,7 +31,9 @@ internal enum CloudConfigUrl
CloudPackagesApi = 11,
CloudPackagesKey = 12,
CloudAssetStoreUrl = 13,
- ServicesGateway = 20 // these get marshalled to native, and the native side has extra entries.
+ // these get marshalled to native, and the native side has extra entries.
+ ServicesGateway = 20,
+ EcosystemApi = 23
}
internal enum COPPACompliance
diff --git a/Editor/Mono/VersionControl/Common/VersionControlManager.cs b/Editor/Mono/VersionControl/Common/VersionControlManager.cs
index 8966485f2e..2c9a9d56c8 100644
--- a/Editor/Mono/VersionControl/Common/VersionControlManager.cs
+++ b/Editor/Mono/VersionControl/Common/VersionControlManager.cs
@@ -32,19 +32,31 @@ internal static bool isConnected
static VersionControlManager()
{
+ // Deferred version control mode validation to ensure packages are loaded and TypeCache is ready.
+ EditorApplication.delayCall += ValidateVersionControlMode;
+ }
+
+ static void ValidateVersionControlMode()
+ {
+ // Clear cached descriptors to ensure we read fresh TypeCache data
+ s_Descriptors = null;
+
if (Provider.enabled)
return;
var mode = VersionControlSettings.mode;
+
+ // Skip validation for internal modes
if (mode == ExternalVersionControl.Disabled || mode == ExternalVersionControl.Generic || mode == ExternalVersionControl.AutoDetect)
return;
- // This can be true even if !Provider.enabled. It happens when this method is invoked from VCProvider::UpdateSettings.
+ // Skip validation for native executable plugins (Perforce, PlasticSCM)
+ // Note: PlasticSCM is the old DLL plugin, different from "Unity Version Control" (managed)
if (mode == "Perforce" || mode == "PlasticSCM")
return;
- if (!HasDescriptor(mode))
- SetVersionControl(ExternalVersionControl.Disabled);
+ // Validate managed providers and ensure activation if the provider exists
+ SetVersionControl(HasDescriptor(mode) ? mode : ExternalVersionControl.Disabled);
}
static VersionControlDescriptor[] GetDescriptors()
diff --git a/Editor/Mono/VersionControl/VCProvider.bindings.cs b/Editor/Mono/VersionControl/VCProvider.bindings.cs
index bdce34118f..36c7f68d77 100644
--- a/Editor/Mono/VersionControl/VCProvider.bindings.cs
+++ b/Editor/Mono/VersionControl/VCProvider.bindings.cs
@@ -47,6 +47,7 @@ private struct Traits
public bool enablesVersioningFolders;
public bool enablesChangelists;
public bool enablesLocking;
+ public bool enablesRevertUnchanged;
}
private static extern Traits activeTraits
@@ -75,6 +76,11 @@ public static bool hasLockingSupport
get { return activeTraits.enablesLocking; }
}
+ public static bool hasRevertUnchangedSupport
+ {
+ get { return activeTraits.enablesRevertUnchanged; }
+ }
+
public static bool isVersioningFolders
{
get { return activeTraits.enablesVersioningFolders; }
diff --git a/External/ExCSS/builds/builds/lib/netstandard2.0/ExCSS.Unity.dll b/External/ExCSS/builds/builds/lib/netstandard2.0/ExCSS.Unity.dll
index 509fd7c0f9..29076bef00 100644
Binary files a/External/ExCSS/builds/builds/lib/netstandard2.0/ExCSS.Unity.dll and b/External/ExCSS/builds/builds/lib/netstandard2.0/ExCSS.Unity.dll differ
diff --git a/External/ScriptingCore/Unity.Scripting/AssemblyInfo.cs b/External/ScriptingCore/Unity.Scripting/AssemblyInfo.cs
index 4ed62f6128..13449cc9ad 100644
--- a/External/ScriptingCore/Unity.Scripting/AssemblyInfo.cs
+++ b/External/ScriptingCore/Unity.Scripting/AssemblyInfo.cs
@@ -19,12 +19,14 @@
//Remove when we move API to be public
[assembly: InternalsVisibleTo("SomeTestAssembly")]
+[assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsModule")]
[assembly: InternalsVisibleTo("UnityEngine.ContentLoadModule")]
[assembly: InternalsVisibleTo("UnityEngine.HierarchyModule")]
[assembly: InternalsVisibleTo("UnityEditor.HierarchyModule")]
[assembly: InternalsVisibleTo("UnityEngine.HierarchyCoreModule")]
[assembly: InternalsVisibleTo("UnityEditor.ShaderFoundryModule")]
[assembly: InternalsVisibleTo("UnityEditor.QuickSearchModule")]
+[assembly: InternalsVisibleTo("UnityEditor.LightingModule")]
[assembly: InternalsVisibleTo("UnityEditor.EditorToolbarModule")]
[assembly: InternalsVisibleTo("UnityEditor.UIToolkitAuthoringModule")]
[assembly: InternalsVisibleTo("UnityEngine.InputModule")]
@@ -33,6 +35,14 @@
[assembly: InternalsVisibleTo("UnityEngine.InputForUIModule")]
[assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")]
[assembly: InternalsVisibleTo("UnityEngine.IMGUIModule")]
+[assembly: InternalsVisibleTo("UnityEngine.MarshallingModule")]
+[assembly: InternalsVisibleTo("UnityEngine.AIModule")]
+[assembly: InternalsVisibleTo("UnityEditor.AIModule")]
+[assembly: InternalsVisibleTo("UnityEngine.VFXModule")]
+[assembly: InternalsVisibleTo("UnityEditor.VFXModule")]
+[assembly: InternalsVisibleTo("UnityEditor.ProjectAuditorModule")]
+[assembly: InternalsVisibleTo("UnityEngine.VideoModule")]
+[assembly: InternalsVisibleTo("UnityEditor.VideoModule")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-firstpass-testable")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")]
[assembly: InternalsVisibleTo("Assembly-CSharp-testable")]
@@ -40,3 +50,6 @@
[assembly: InternalsVisibleTo("LifecycleTestAssembly2")]
[assembly: InternalsVisibleTo("LifecycleTestAssembly3")]
[assembly: InternalsVisibleTo("LifecycleTestAssembly4")]
+[assembly: InternalsVisibleTo("Unity.IntegrationTests.Scripting")]
+[assembly: InternalsVisibleTo("UnityEngine.AdaptivePerformanceModule")]
+[assembly: InternalsVisibleTo("UnityEngine.ParticleSystemModule")]
diff --git a/External/ScriptingCore/Unity.Scripting/CoreAttributes/PreserveAttribute.cs b/External/ScriptingCore/Unity.Scripting/CoreAttributes/PreserveAttribute.cs
index 6c4714865b..64b3b2db28 100644
--- a/External/ScriptingCore/Unity.Scripting/CoreAttributes/PreserveAttribute.cs
+++ b/External/ScriptingCore/Unity.Scripting/CoreAttributes/PreserveAttribute.cs
@@ -1,10 +1,7 @@
using System;
-namespace UnityEngine.Scripting
+namespace Unity.Private.Scripting;
+
+class PreserveAttribute : Attribute
{
- [System.AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property
- | AttributeTargets.Constructor | AttributeTargets.Interface | AttributeTargets.Delegate | AttributeTargets.Event | AttributeTargets.Struct | AttributeTargets.Assembly | AttributeTargets.Enum, Inherited = false)]
- public class PreserveAttribute : Attribute
- {
- }
}
diff --git a/External/ScriptingCore/Unity.Scripting/Diagnostics/Profiling.cs b/External/ScriptingCore/Unity.Scripting/Diagnostics/Profiling.cs
index 1072f6af16..781f154299 100644
--- a/External/ScriptingCore/Unity.Scripting/Diagnostics/Profiling.cs
+++ b/External/ScriptingCore/Unity.Scripting/Diagnostics/Profiling.cs
@@ -13,20 +13,26 @@ public readonly unsafe struct ProfilerCallbacks
{
public ProfilerCallbacks(
delegate* unmanaged[Cdecl] profiler_marker_create,
+ delegate* unmanaged[Cdecl] profiler_marker_get_static,
delegate* unmanaged[Cdecl] profiler_marker_begin_with_string,
delegate* unmanaged[Cdecl] profiler_marker_begin,
- delegate* unmanaged[Cdecl] profiler_marker_end)
+ delegate* unmanaged[Cdecl] profiler_marker_end,
+ delegate* unmanaged[Cdecl] profiler_domain_reload_phase = null)
{
this.profiler_marker_create = profiler_marker_create;
+ this.profiler_marker_get_static = profiler_marker_get_static;
this.profiler_marker_begin_with_string = profiler_marker_begin_with_string;
this.profiler_marker_begin = profiler_marker_begin;
this.profiler_marker_end = profiler_marker_end;
+ this.profiler_domain_reload_phase = profiler_domain_reload_phase;
}
public readonly delegate* unmanaged[Cdecl] profiler_marker_create;
+ public readonly delegate* unmanaged[Cdecl] profiler_marker_get_static;
public readonly delegate* unmanaged[Cdecl] profiler_marker_begin_with_string;
public readonly delegate* unmanaged[Cdecl] profiler_marker_begin;
public readonly delegate* unmanaged[Cdecl] profiler_marker_end;
+ public readonly delegate* unmanaged[Cdecl] profiler_domain_reload_phase;
}
///
@@ -39,6 +45,51 @@ public ProfilerCallbacks(
///
private static ProfilerCallbacks profilerCallbacks;
+ internal enum DomainReloadPhase
+ {
+ StartPhase1 = 1,
+ EndPhase1 = 2,
+ StartPhase2 = 3,
+ EndPhase2 = 4,
+ }
+
+ public readonly struct DomainReloadPhaseScope : IDisposable
+ {
+ private readonly DomainReloadPhase _endPhase;
+
+ internal DomainReloadPhaseScope(DomainReloadPhase startPhase, DomainReloadPhase endPhase)
+ {
+ _endPhase = endPhase;
+ EmitPhase(startPhase);
+ }
+
+ public void Dispose() => EmitPhase(_endPhase);
+ }
+
+ public static DomainReloadPhaseScope DomainReloadPhase1() =>
+ new(DomainReloadPhase.StartPhase1, DomainReloadPhase.EndPhase1);
+
+ public static DomainReloadPhaseScope DomainReloadPhase2() =>
+ new(DomainReloadPhase.StartPhase2, DomainReloadPhase.EndPhase2);
+
+ private static unsafe void EmitPhase(DomainReloadPhase phase)
+ {
+ if (profilerCallbacks.profiler_domain_reload_phase != null)
+ profilerCallbacks.profiler_domain_reload_phase((int)phase);
+ }
+
+ public static unsafe ProfilerMarker GetStaticMarker(string name)
+ {
+ if (profilerCallbacks.profiler_marker_get_static == null)
+ return default;
+
+ fixed (char* p = name)
+ {
+ IntPtr ptr = profilerCallbacks.profiler_marker_get_static(name.Length, p);
+ return new ProfilerMarker(ptr);
+ }
+ }
+
///
/// Struct that defines a code instrumentation scope.
///
@@ -55,6 +106,11 @@ public readonly unsafe struct ProfilerMarker
{
internal readonly IntPtr ptr;
+ internal ProfilerMarker(IntPtr existingPtr)
+ {
+ ptr = existingPtr;
+ }
+
public ProfilerMarker(string name)
{
if (profilerCallbacks.profiler_marker_create == null)
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ActiveLifecycleScopesTracker.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ActiveLifecycleScopesTracker.cs
index bd65e6e016..ca865c8b74 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ActiveLifecycleScopesTracker.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ActiveLifecycleScopesTracker.cs
@@ -435,14 +435,15 @@ private void TryEnterScope(LifecycleScopeWithContext lifecyc
activeScope.OnEnter(_scopeTransitionHelper);
}
- private void CollectNestedScopesToExit(string scopeName, List nestedActiveScopesInOrder)
+ private void CollectNestedScopesToExit(string scopeName, ref List? nestedActiveScopesInOrder)
{
foreach (var activeScope in _activeScopes.Values)
{
if (activeScope.Scope.MustBeNestedInsideScope(scopeName))
{
var activeScopeName = activeScope.Scope.Name;
- CollectNestedScopesToExit(activeScopeName, nestedActiveScopesInOrder);
+ CollectNestedScopesToExit(activeScopeName, ref nestedActiveScopesInOrder);
+ nestedActiveScopesInOrder ??= new List();
nestedActiveScopesInOrder.Add(activeScope);
}
}
@@ -456,7 +457,7 @@ private bool PrepareTryExitScope(LifecycleScope lifecycleScope, bool alsoExitNes
return false;
}
- var nestedActiveScopesInOrder = new List();
+ List? nestedActiveScopesInOrder = null;
int numActiveInstancesOfOuterScope = 0;
foreach (var activeScope in _activeScopes.Values)
@@ -469,10 +470,10 @@ private bool PrepareTryExitScope(LifecycleScope lifecycleScope, bool alsoExitNes
// We only exit nested scopes if we are exiting the last remaining active instance of the outer scope
if (numActiveInstancesOfOuterScope == 1)
{
- CollectNestedScopesToExit(lifecycleScope.Name, nestedActiveScopesInOrder);
+ CollectNestedScopesToExit(lifecycleScope.Name, ref nestedActiveScopesInOrder);
}
- if (nestedActiveScopesInOrder.Count > 0)
+ if (nestedActiveScopesInOrder != null)
{
if (!alsoExitNestedScopes)
{
@@ -486,7 +487,8 @@ private bool PrepareTryExitScope(LifecycleScope lifecycleScope, bool alsoExitNes
foreach (var nestedScope in nestedActiveScopesInOrder)
{
- DebugLifecycle.Log($"Lifecycle : Exiting nested scope '{nestedScope.Scope.Name}' due to exiting scope '{lifecycleScope.Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Exiting nested scope '{nestedScope.Scope.Name}' due to exiting scope '{lifecycleScope.Name}'");
nestedScope.OnExit(_scopeTransitionHelper);
RaiseAutoCleanups(nestedScope.Scope.GetType(), ScopeTransitionType.ExitScope);
_activeScopes.Remove(nestedScope.ScopeKey);
@@ -504,7 +506,7 @@ private bool PrepareTryExitScope(LifecycleScopeWithContext lifecycleScope,
return false;
}
- var nestedActiveScopesInOrder = new List();
+ List? nestedActiveScopesInOrder = null;
int numActiveInstancesOfOuterScope = 0;
foreach (var activeScope in _activeScopes.Values)
{
@@ -516,10 +518,10 @@ private bool PrepareTryExitScope(LifecycleScopeWithContext lifecycleScope,
// We only exit nested scopes if we are exiting the last remaining active instance of the outer scope
if (numActiveInstancesOfOuterScope == 1)
{
- CollectNestedScopesToExit(lifecycleScope.Name, nestedActiveScopesInOrder);
+ CollectNestedScopesToExit(lifecycleScope.Name, ref nestedActiveScopesInOrder);
}
- if (nestedActiveScopesInOrder.Count > 0)
+ if (nestedActiveScopesInOrder != null)
{
if (!alsoExitNestedScopes)
{
@@ -533,7 +535,8 @@ private bool PrepareTryExitScope(LifecycleScopeWithContext lifecycleScope,
foreach (var nestedScope in nestedActiveScopesInOrder)
{
- DebugLifecycle.Log($"Lifecycle : Exiting nested scope '{nestedScope.Scope.Name}' due to exiting scope '{lifecycleScope.Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Exiting nested scope '{nestedScope.Scope.Name}' due to exiting scope '{lifecycleScope.Name}'");
nestedScope.OnExit(_scopeTransitionHelper);
RaiseAutoCleanups(nestedScope.Scope.GetType(), ScopeTransitionType.ExitScope);
_activeScopes.Remove(nestedScope.ScopeKey);
@@ -597,7 +600,8 @@ private void CreateScopeTransitionRequest(LifecycleScope lifecycleScope, ScopeTr
_transitionRequestQueue.Enqueue(newRequest);
if (!transitionRequestQueueWasEmpty)
{
- DebugLifecycle.Log($"Lifecycle : Scope Transition request has been queued up for '{newRequest.Scope.Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Scope Transition request has been queued up for '{newRequest.Scope.Name}'");
// If there's older transition request in the queue, then we should process the new or other request right now, as they are being handled lower in the stack (or potentially in another thread).
return;
}
@@ -622,7 +626,8 @@ private void CreateScopeTransitionRequest(LifecycleScopeWithContext lifecy
_transitionRequestQueue.Enqueue(newRequest);
if (!transitionRequestQueueWasEmpty)
{
- DebugLifecycle.Log($"Lifecycle : Scope Transition request has been queued up for '{newRequest.Scope.Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Scope Transition request has been queued up for '{newRequest.Scope.Name}'");
// If there's older transition request in the queue, then we should process the new or other request right now, as they are being handled lower in the stack (or potentially in another thread).
return;
}
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/BurstScope.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/BurstScope.cs
index fd42c99af3..70fff059c1 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/BurstScope.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/BurstScope.cs
@@ -1,6 +1,6 @@
-using UnityEngine.Scripting;
using System.Reflection;
using System.Runtime.CompilerServices;
+using PreserveAttribute = Unity.Private.Scripting.PreserveAttribute;
[assembly: InternalsVisibleTo("UnityEditor.BurstModule")]
namespace Unity.Scripting.LifecycleManagement
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/CodeLoadedScope.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/CodeLoadedScope.cs
index d78604d6a7..3593bda81b 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/CodeLoadedScope.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/CodeLoadedScope.cs
@@ -1,5 +1,5 @@
using System.Runtime.CompilerServices;
-using UnityEngine.Scripting;
+using PreserveAttribute = Unity.Private.Scripting.PreserveAttribute;
[assembly: InternalsVisibleTo("Unity.ScriptingTests.CodeLoadedGeneration")]
[assembly: InternalsVisibleTo("DomainReload-editor")]
@@ -25,10 +25,10 @@ public sealed class ClearCacheBetweenCodeLoadsAttribute : LifecycleAttributeBase
internal sealed class CodeLoadedScope : LifecycleScope
{
public static readonly string ScopeName = "CodeLoaded";
+
+ // Callers compare their own captured generation against this to detect stale async work.
private static int _codeLoadedGeneration;
- static AsyncLocal _executionContextGeneration = new AsyncLocal();
public static int CurrentCodeLoadedGeneration => _codeLoadedGeneration;
- public static int ExecutionContextGeneration => _executionContextGeneration.Value;
private static CancellationTokenSource? _cancellationTokenSource;
@@ -43,15 +43,13 @@ internal sealed class CodeLoadedScope : LifecycleScope
internal static int IncrementCodeLoadedGeneration()
{
RecycleCancellationTokenSource();
- var generation = ++_codeLoadedGeneration;
- _executionContextGeneration.Value = generation;
- return generation;
+ return ++_codeLoadedGeneration;
}
- public static void CancelIfNotInCorrectGeneration()
+ // Generation should be captured by the caller when the async work started.
+ public static void CancelIfNotInGeneration(int generation)
{
-
- if (_executionContextGeneration.Value != _codeLoadedGeneration)
+ if (generation != _codeLoadedGeneration)
{
throw new OperationCanceledException(
"Running async code belongs to the previous CodeLoaded scope and must be cancelled before Code Reload");
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/DebugLifecycle.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/DebugLifecycle.cs
index 271af93f83..618b965d41 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/DebugLifecycle.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/DebugLifecycle.cs
@@ -11,6 +11,11 @@ static DebugLifecycle()
verificationEnabled = IsVerificationEnabled();
}
+ ///
+ /// Check before building log messages on hot paths to avoid interpolation allocations when logging is disabled.
+ ///
+ public static bool LoggingEnabled => loggingEnabled;
+
public static void Log(string message)
{
if (loggingEnabled)
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleController.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleController.cs
index 386bf56cc2..c5be25e299 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleController.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleController.cs
@@ -207,29 +207,29 @@ internal void ExpectPresentScope(string scopeName, LifecycleScopePresence expect
}
}
- private void ExecuteOnMainThread(string transitionType, string scopeName, Action action)
+ private bool CheckMainThread(string transitionType, string scopeName)
{
if (!IsOnMainThread)
{
DebugLifecycle.ReportError($"Lifecycle ERROR : {transitionType} scope {scopeName} can only be executed on the main thread\n" +
$"Calling thread was {Thread.CurrentThread.ManagedThreadId} while main thread is {MainThreadId}.");
- return;
+ return false;
}
- lock (_lock)
- {
- action.Invoke();
- }
+ return true;
}
internal void EnterScope()
where TScope : LifecycleScope, new()
{
var scope = new TScope();
- ExecuteOnMainThread("Enter", scope.Name, () =>
+ if (!CheckMainThread("Enter", scope.Name))
+ return;
+
+ lock (_lock)
{
_lifecycleTracker.RequestEnterScope(scope);
- });
+ }
}
// EnterScope() and ExitScope() functions have a void return value even though this scope transition request may fail.
@@ -239,26 +239,35 @@ internal void EnterScope()
// To improve on this we can return a small struct which contains info whether the request has been processed, whether it was succesful and the reason for failure in case it isn't
internal void EnterScope(LifecycleScope scope)
{
- ExecuteOnMainThread("Enter", scope.Name, () =>
+ if (!CheckMainThread("Enter", scope.Name))
+ return;
+
+ lock (_lock)
{
_lifecycleTracker.RequestEnterScope(scope);
- });
+ }
}
internal void EnterScope(LifecycleScopeWithContext scope)
where T : class
{
- ExecuteOnMainThread("Enter", scope.Name, () =>
+ if (!CheckMainThread("Enter", scope.Name))
+ return;
+
+ lock (_lock)
{
_lifecycleTracker.RequestEnterScope(scope);
- });
+ }
}
internal void ExitScope()
where TScope : LifecycleScope, new()
{
var scopeName = typeof(TScope).Name;
- ExecuteOnMainThread("Exit", scopeName, () =>
+ if (!CheckMainThread("Exit", scopeName))
+ return;
+
+ lock (_lock)
{
if (!_lifecycleTracker.TryGetActiveScope(out var scope))
{
@@ -268,7 +277,7 @@ internal void ExitScope()
_lifecycleTracker.RequestExitScope(scope!);
Debug.Assert(!_lifecycleTracker.IsOrWillBeInsideScope(scope));
- });
+ }
}
internal void ExitScope(TContext context)
@@ -276,7 +285,10 @@ internal void ExitScope(TContext context)
where TScope : LifecycleScopeWithContext
{
var scopeName = typeof(TScope).Name;
- ExecuteOnMainThread("Exit", scopeName, () =>
+ if (!CheckMainThread("Exit", scopeName))
+ return;
+
+ lock (_lock)
{
if (!_lifecycleTracker.TryGetActiveScope(context, out var scope))
{
@@ -286,24 +298,30 @@ internal void ExitScope(TContext context)
_lifecycleTracker.RequestExitScope(scope);
Debug.Assert(!_lifecycleTracker.IsOrWillBeInsideScopeWithActivationContext(scope.Context));
- });
+ }
}
internal void ExitScope(LifecycleScope scope)
{
- ExecuteOnMainThread("Exit", scope.Name, () =>
+ if (!CheckMainThread("Exit", scope.Name))
+ return;
+
+ lock (_lock)
{
_lifecycleTracker.RequestExitScope(scope);
- });
+ }
}
internal void ExitScope(LifecycleScopeWithContext scope)
where TContext : class
{
- ExecuteOnMainThread("Exit", scope.Name, () =>
+ if (!CheckMainThread("Exit", scope.Name))
+ return;
+
+ lock (_lock)
{
_lifecycleTracker.RequestExitScope(scope);
- });
+ }
}
internal void RegisterAutoCleanup(ClassAutoCleanup classAutoCleanup, Type scopeType, ScopeTransitionType cleanOn)
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleMethodRegistry.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleMethodRegistry.cs
index e9ef53a7d0..f2255f733f 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleMethodRegistry.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleMethodRegistry.cs
@@ -32,22 +32,28 @@ public void Register(Type lifecycleAttributeType, Assembly assembly, string meth
attributeTypes.Add(lifecycleAttributeType);
}
+ private static readonly List s_NoMethods = new();
+
internal List Get(Type lifecycleAttributeType, IReadOnlyList assemblies)
{
- var result = new List();
+ // Early-out without allocating: most attribute types have no registered methods at all
+ // and this runs on every scope transition (multiple times per domain reload).
+ if (!_lifecycleCallbacks.TryGetValue(lifecycleAttributeType, out var typeCallbacks) || typeCallbacks.Count == 0)
+ {
+ return s_NoMethods;
+ }
- if (_lifecycleCallbacks.TryGetValue(lifecycleAttributeType, out var typeCallbacks))
+ List? result = null;
+ foreach (var assembly in assemblies)
{
- foreach (var assembly in assemblies)
+ if (typeCallbacks.TryGetValue(assembly, out var assemblyCallbacks))
{
- if (typeCallbacks.TryGetValue(assembly, out var assemblyCallbacks))
- {
- result.AddRange(assemblyCallbacks);
- }
+ result ??= new List();
+ result.AddRange(assemblyCallbacks);
}
}
- return result;
+ return result ?? s_NoMethods;
}
internal void Clear(IReadOnlyList assemblies)
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleScopeBase.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleScopeBase.cs
index 5e3537d572..860472fdfa 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleScopeBase.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/LifecycleScopeBase.cs
@@ -43,16 +43,20 @@ public bool MustBeNestedInsideScope(string scopeName)
internal void OnEnter(ScopeTransitionHelper scopeTransitionHelper)
{
- DebugLifecycle.Log($"Lifecycle : Entering scope '{Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Entering scope '{Name}'");
Enter(scopeTransitionHelper);
- DebugLifecycle.Log($"Lifecycle : Entered scope '{Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Entered scope '{Name}'");
}
internal void OnExit(ScopeTransitionHelper scopeTransitionHelper)
{
- DebugLifecycle.Log($"Lifecycle : Exiting scope '{Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Exiting scope '{Name}'");
Exit(scopeTransitionHelper);
- DebugLifecycle.Log($"Lifecycle : Exited scope '{Name}'");
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : Exited scope '{Name}'");
}
}
}
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ManagedObjectsAwokenScope.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ManagedObjectsAwokenScope.cs
deleted file mode 100644
index a7296d1c83..0000000000
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ManagedObjectsAwokenScope.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-using System.Runtime.CompilerServices;
-
-[assembly: InternalsVisibleTo("DomainReload-editor")]
-[assembly: InternalsVisibleTo("Assembly-CSharp-testable")]
-
-namespace Unity.Scripting.LifecycleManagement
-{
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
- internal sealed class AfterManagedObjectsAwokenAttribute : LifecycleAttributeBase
- {
- }
-
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
- internal sealed class BeforeManagedObjectsDisabledAttribute : LifecycleAttributeBase
- {
- }
- internal sealed class ManagedObjectsAwokenScope : LifecycleScope
- {
- public static readonly string ScopeName = "ManagedObjectsAwoken";
- public ManagedObjectsAwokenScope() : base(ScopeName)
- {
- ExplicitRequiredOuterScopes.Add(CodeInitializedScope.ScopeName);
- }
- protected override void Enter(ScopeTransitionHelper scopeTransitionHelper)
- {
- scopeTransitionHelper.ExecuteMethodsInOrder();
- }
-
- protected override void Exit(ScopeTransitionHelper scopeTransitionHelper)
- {
- scopeTransitionHelper.ExecuteMethodsInReverseOrder();
- }
- }
-}
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ScopeTransitionHelper.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ScopeTransitionHelper.cs
index f4f96c8035..ac53a9e752 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ScopeTransitionHelper.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/ScopeTransitionHelper.cs
@@ -17,6 +17,7 @@ internal sealed class ScopeTransitionHelper
private readonly StackOrderedAssemblyList _assemblyList = new();
private readonly LifecycleMethodRegistry _lifecycleMethodRegistry;
+ private readonly Dictionary _processMarkers = new();
internal INativeCallbackProvider? NativeCallbackProvider { get; set; }
@@ -35,6 +36,22 @@ private List FindStaticMethodsWithAttribute(Type attributeT
return _lifecycleMethodRegistry.Get(attributeType, assemblies);
}
+ private Profiling.ProfilerMarker GetProcessMarker(Type attributeType)
+ {
+ // Cache markers per attribute type: creating one allocates a string and calls into
+ // the native profiler, and this runs on every scope transition.
+ if (!_processMarkers.TryGetValue(attributeType, out var marker))
+ {
+ marker = new Profiling.ProfilerMarker(k_ProfilerMarkerPrefix + attributeType.Name);
+ if (marker.ptr != IntPtr.Zero)
+ {
+ _processMarkers.Add(attributeType, marker);
+ }
+ }
+
+ return marker;
+ }
+
///
/// Executes all static methods with the given attribute type in the given assemblies in the assembly order.
///
@@ -52,15 +69,16 @@ public void ExecuteMethodsInOrder(ReadOnlyAssemblyList? assemblies = null)
private void ExecuteMethodsInOrder(Type attributeType, IReadOnlyList assemblies)
{
- using var executeMethodsProfilerScope = new Profiling.ProfilerMarker(k_ProfilerMarkerPrefix + attributeType.Name).Auto();
-
var methods = FindStaticMethodsWithAttribute(attributeType, assemblies);
if (methods.Count == 0)
{
return;
}
- DebugLifecycle.Log($"Lifecycle : *inside scope transition* executing {methods.Count} hooks for type {attributeType}");
+ using var executeMethodsProfilerScope = GetProcessMarker(attributeType).Auto();
+
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : *inside scope transition* executing {methods.Count} hooks for type {attributeType}");
// Check if detailed profiling is enabled and create a marker which would wrap each method invocation
Profiling.ProfilerMarker? detailedInvokeMarker = EnableDetailedProfiling ? new Profiling.ProfilerMarker(k_DetailedInvokeMarkerPrefix + attributeType.Name) : null;
@@ -101,15 +119,16 @@ public void ExecuteMethodsInReverseOrder(ReadOnlyAssemblyList? assemblies = n
private void ExecuteMethodsInReverseOrder(Type attributeType, IReadOnlyList assemblies)
{
- using var executeMethodsProfilerScope = new Profiling.ProfilerMarker(k_ProfilerMarkerPrefix + attributeType.Name).Auto();
-
var methods = FindStaticMethodsWithAttribute(attributeType, assemblies);
if (methods.Count == 0)
{
return;
}
- DebugLifecycle.Log($"Lifecycle : *inside scope transition* executing {methods.Count} hooks for type {attributeType} in reverse");
+ using var executeMethodsProfilerScope = GetProcessMarker(attributeType).Auto();
+
+ if (DebugLifecycle.LoggingEnabled)
+ DebugLifecycle.Log($"Lifecycle : *inside scope transition* executing {methods.Count} hooks for type {attributeType} in reverse");
// Check if detailed profiling is enabled and create a marker which would wrap each method invocation
Profiling.ProfilerMarker? detailedInvokeMarker = EnableDetailedProfiling ? new Profiling.ProfilerMarker(k_DetailedInvokeMarkerPrefix + attributeType.Name) : null;
diff --git a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/UDMScope.cs b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/UDMScope.cs
index 29a44639e6..12e1cc24ec 100644
--- a/External/ScriptingCore/Unity.Scripting/LifecycleManagement/UDMScope.cs
+++ b/External/ScriptingCore/Unity.Scripting/LifecycleManagement/UDMScope.cs
@@ -1,4 +1,5 @@
using UnityEngine.Scripting;
+using PreserveAttribute = Unity.Private.Scripting.PreserveAttribute;
namespace Unity.Scripting.LifecycleManagement
{
diff --git a/External/ScriptingCore/Unity.Scripting/ReflectionFormatting.cs b/External/ScriptingCore/Unity.Scripting/ReflectionFormatting.cs
index c1ca4d8c1c..66ca02b811 100644
--- a/External/ScriptingCore/Unity.Scripting/ReflectionFormatting.cs
+++ b/External/ScriptingCore/Unity.Scripting/ReflectionFormatting.cs
@@ -9,6 +9,24 @@ namespace Unity.Scripting
*/
internal class ReflectionFormatting
{
- internal static string FormatMethod(MethodBase method) => $"{method.ReflectedType}.{method}";
+ internal static string FormatMethod(MethodBase method)
+ {
+ // MethodBase.ToString() is "()". Drop the leading return type so
+ // the method portion matches Mono's mono_method_full_name, which omits it.
+ //
+ // Splitting on the first space is safe: a type rendered by reflection never contains a space
+ // (generic arguments are comma-separated with no space, e.g. "Dictionary`2[System.Int32,System.String]",
+ // arrays are "T[]"), so the first space always delimits the return type from the name. The
+ // ", " between parameters comes later and is preserved. We can't instead strip
+ // ReturnType.ToString() because that disagrees with the rendering here for some types (e.g.
+ // "System.Void" vs the "Void" produced above).
+ var signature = method.ToString();
+ int nameStart = signature.IndexOf(' ');
+ if (nameStart >= 0)
+ {
+ signature = signature.Substring(nameStart + 1);
+ }
+ return $"{method.ReflectedType}.{signature}";
+ }
}
}
diff --git a/Modules/AI/Builder/NavMeshBuilder.bindings.cs b/Modules/AI/Builder/NavMeshBuilder.bindings.cs
index 2e9cf560e7..4f58f2dfc4 100644
--- a/Modules/AI/Builder/NavMeshBuilder.bindings.cs
+++ b/Modules/AI/Builder/NavMeshBuilder.bindings.cs
@@ -8,10 +8,23 @@
namespace UnityEngine.AI
{
+ ///Navigation mesh builder interface.
[NativeHeader("Modules/AI/Builder/NavMeshBuilder.bindings.h")]
[StaticAccessor("NavMeshBuilderBindings", StaticAccessorType.DoubleColon)]
public static class NavMeshBuilder
{
+ ///Collects renderers or physics colliders, and terrains within a volume. This function might not collect some MeshColliders that are a distance greater than 1E7 from the origin.
+ ///For convenience, you can create a list of build sources directly from the current geometry.
+ ///
+ ///The collection can be controlled in terms of layers, type of geometry and by collecting either by hierarchy or volume.
+ ///The queried objects must overlap these bounds to be included in the results.
+ ///Specifies which layers are included in the query.
+ ///Which type of geometry to collect - e.g. physics colliders.
+ ///Area type to assign to results, unless modified by .
+ ///If true, all the source will be considered for generating links. Otherwise, only the marked sources will be considered.
+ ///List of markups which allows finer control over how objects are collected.
+ ///Specifies if only objects with markups are collected.
+ ///List where results are stored, the list is cleared at the beginning of the call.
public static void CollectSources(
Bounds includedWorldBounds, int includedLayerMask, NavMeshCollectGeometry geometry, int defaultArea, bool generateLinksByDefault,
List markups, bool includeOnlyMarkedObjects, List results)
@@ -30,6 +43,16 @@ public static void CollectSources(
results.AddRange(resultsArray);
}
+ ///Collects renderers or physics colliders, and terrains within a volume. This function might not collect some MeshColliders that are a distance greater than 1E7 from the origin.
+ ///For convenience, you can create a list of build sources directly from the current geometry.
+ ///
+ ///The collection can be controlled in terms of layers, type of geometry and by collecting either by hierarchy or volume.
+ ///The queried objects must overlap these bounds to be included in the results.
+ ///Specifies which layers are included in the query.
+ ///Which type of geometry to collect - e.g. physics colliders.
+ ///Area type to assign to results, unless modified by .
+ ///List of markups which allows finer control over how objects are collected.
+ ///List where results are stored, the list is cleared at the beginning of the call.
public static void CollectSources(
Bounds includedWorldBounds, int includedLayerMask, NavMeshCollectGeometry geometry, int defaultArea,
List markups, List results)
@@ -37,6 +60,18 @@ public static void CollectSources(
CollectSources(includedWorldBounds, includedLayerMask, geometry, defaultArea, false, markups, false, results);
}
+ ///Collects renderers or physics colliders, and terrains within a transform hierarchy.
+ ///For convenience, you can create a list of build sources directly from the current geometry.
+ ///
+ ///The collection can be controlled in terms of layers, type of geometry and by collecting either by hierarchy or volume.
+ ///If not null, consider only root and its children in the query; if null, includes everything loaded.
+ ///Specifies which layers are included in the query.
+ ///Which type of geometry to collect - e.g. physics colliders.
+ ///Area type to assign to results, unless modified by NavMeshMarkup.
+ ///If true, all the source will be considered for generating links. Otherwise, only the marked sources will be considered.
+ ///List of markups which allows finer control over how objects are collected.
+ ///Specifies if only objects with markups are collected.
+ ///List where results are stored, the list is cleared at the beginning of the call.
public static void CollectSources(
Transform root, int includedLayerMask, NavMeshCollectGeometry geometry, int defaultArea, bool generateLinksByDefault,
List markups, bool includeOnlyMarkedObjects, List results)
@@ -56,6 +91,16 @@ public static void CollectSources(
results.AddRange(resultsArray);
}
+ ///Collects renderers or physics colliders, and terrains within a transform hierarchy.
+ ///For convenience, you can create a list of build sources directly from the current geometry.
+ ///
+ ///The collection can be controlled in terms of layers, type of geometry and by collecting either by hierarchy or volume.
+ ///If not null, consider only root and its children in the query; if null, includes everything loaded.
+ ///Specifies which layers are included in the query.
+ ///Which type of geometry to collect - e.g. physics colliders.
+ ///Area type to assign to results, unless modified by NavMeshMarkup.
+ ///List of markups which allows finer control over how objects are collected.
+ ///List where results are stored, the list is cleared at the beginning of the call.
public static void CollectSources(
Transform root, int includedLayerMask, NavMeshCollectGeometry geometry, int defaultArea,
List markups, List results)
@@ -69,6 +114,15 @@ static extern NavMeshBuildSource[] CollectSourcesInternal(
NavMeshBuildMarkup[] markups, bool includeOnlyMarkedObjects);
// Immediate NavMeshData building
+ ///Builds a NavMesh data object from the provided input sources.
+ ///Note: that has same effect as creating a new empty and calling .
+ ///Settings for the bake process, see .
+ ///List of input geometry used for baking, they describe the surfaces to walk on or obstacles to avoid.
+ ///Bounding box relative to position and rotation which describes the volume where the NavMesh should be built. Empty bounds is treated as no bounds, i.e. the NavMesh will cover all the inputs.
+ ///Center of the NavMeshData. This specifies the origin for the NavMesh tiles.
+ ///Orientation of the NavMeshData, you can use this to generate NavMesh with an arbitrary up-vector – e.g. for walkable vertical surfaces.
+ ///The newly built NavMeshData, or null if the NavMeshData was empty or an error occurred.
+ ///
public static NavMeshData BuildNavMeshData(
NavMeshBuildSettings buildSettings, List sources,
Bounds localBounds, Vector3 position, Quaternion rotation)
@@ -87,6 +141,18 @@ public static NavMeshData BuildNavMeshData(
}
// Immediate NavMeshData updating
+ ///Incrementally updates the NavMeshData based on the sources.
+ ///Each time NavMeshData is built or updated, the source data is hashed, and the hashes are stored along with the .
+ ///
+ ///When called, first the hashes are recomputed and compared and only changed portions are rebuilt. For this reason, the list of sources should always contain all the input geometry, even if they haven't moved or changed. If the list of sources is modified between calls to UpdateNavMeshData the missing/added sources are considered changes. Try to provide the sources that have not changed since the last update in the same relative order as before because their sequence can affect the values of the hashes. This measure ensures that unchanged portions don't get rebuilt unnecessarily.
+ ///
+ ///You must supply a Bounds struct for the localBounds parameter.
+ ///The NavMeshData to update.
+ ///The build settings which is used to update the NavMeshData. The build settings is also hashed along with the data, so changing settings will cause a full rebuild.
+ ///List of input geometry used for baking, they describe the surfaces to walk on or obstacles to avoid.
+ ///Bounding box relative to position and rotation which describes the volume where the NavMesh should be built.
+ ///true if the update was successful.
+ ///
public static bool UpdateNavMeshData(
NavMeshData data, NavMeshBuildSettings buildSettings, List sources, Bounds localBounds)
{
@@ -102,6 +168,19 @@ static extern bool UpdateNavMeshDataListInternal(
NavMeshData data, NavMeshBuildSettings buildSettings, ReadOnlySpan sources, Bounds localBounds);
// Async NavMeshData updating
+ ///Asynchronously and incrementally updates the NavMeshData based on the sources.
+ ///Each time NavMeshData is built or updated, the source data is hashed, and the hashes are stored along with the NavMeshData.
+ ///
+ ///
+ ///When UpdateNavMeshDataAsync() is called, first the hashes are compared and only changed portions are rebuilt. For this reason, the list of sources should always contain all the input geometry, even if they haven't moved or changed. If the list of sources is modified between calls to UpdateNavMeshDataAsync the missing/added sources are considered changes. Try to provide the sources that have not changed since the last update in the same relative order as before because their sequence can affect the values of the hashes. This measure ensures that unchanged portions don't get rebuilt unnecessarily.
+ ///
+ ///You must supply a Bounds struct for the localBounds parameter.
+ ///The NavMeshData to update.
+ ///The build settings used to update the NavMeshData. The build settings are also hashed along with the data, so changing the settings is likely to cause a full rebuild.
+ ///List of input geometry used for baking, they describe the surfaces to walk on or obstacles to avoid.
+ ///Bounding box relative to position and rotation which describes to volume where the NavMesh should be built.
+ ///Can be used to check the progress of the update.
+ ///
public static AsyncOperation UpdateNavMeshDataAsync(
NavMeshData data, NavMeshBuildSettings buildSettings, List sources, Bounds localBounds)
{
@@ -113,6 +192,9 @@ public static AsyncOperation UpdateNavMeshDataAsync(
return UpdateNavMeshDataAsyncListInternal(data, buildSettings, NoAllocHelpers.CreateReadOnlySpan(sources), localBounds);
}
+ ///Cancels an asynchronous update of the specified NavMesh data.
+ ///The data associated with asynchronous updating.
+ ///
[NativeHeader("Modules/AI/NavMeshManager.h")]
[StaticAccessor("GetNavMeshManager().GetNavMeshBuildManager()", StaticAccessorType.Arrow)]
[NativeMethod("Purge")]
diff --git a/Modules/AI/Components/NavMeshAgent.bindings.cs b/Modules/AI/Components/NavMeshAgent.bindings.cs
index ede51532a4..9d4e187a92 100644
--- a/Modules/AI/Components/NavMeshAgent.bindings.cs
+++ b/Modules/AI/Components/NavMeshAgent.bindings.cs
@@ -9,139 +9,418 @@
namespace UnityEngine.AI
{
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
+ ///Level of obstacle avoidance.
[MovedFrom("UnityEngine")]
public enum ObstacleAvoidanceType
{
- // Disable avoidance.
+ ///Disable avoidance.
NoObstacleAvoidance = 0,
- // Enable simple avoidance. Low performance impact.
+ ///Enable simple avoidance. Low performance impact.
LowQualityObstacleAvoidance = 1,
- // Medium avoidance. Medium performance impact
+ ///Medium avoidance. Medium performance impact.
MedQualityObstacleAvoidance = 2,
- // Good avoidance. High performance impact
+ ///Good avoidance. High performance impact.
GoodQualityObstacleAvoidance = 3,
- // Enable highest precision. Highest performance impact.
+ ///Enable highest precision. Highest performance impact.
HighQualityObstacleAvoidance = 4
}
- // Navigation mesh agent.
+ ///Navigation mesh agent.
+ ///Attach this component to a mobile character in the game to allow the character to use the NavMesh to navigate the scene. For more details refer to AI Navigation.
[MovedFrom("UnityEngine")]
[NativeHeader("Modules/AI/Components/NavMeshAgent.bindings.h")]
[NativeHeader("Modules/AI/NavMesh/NavMesh.bindings.h")]
[HelpURL("https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/NavMeshAgent.html")]
public sealed class NavMeshAgent : Behaviour
{
- // Sets or updates the destination. This triggers calculation for a new path.
+ ///Sets or updates the destination thus triggering the calculation for a new path.
+ ///Note that the path may not become available until after a few frames later.
+ ///While the path is being computed, will be true.
+ ///If a valid path becomes available then the agent will resume movement.
+ ///The target point to navigate to.
+ ///True if the destination was requested successfully, otherwise false.
+ ///
+ /// ();
+ /// }
+ ///
+ /// void Update()
+ /// {
+ /// if (Input.GetMouseButtonDown(0))
+ /// {
+ /// SetDestinationToMousePosition();
+ /// }
+ /// }
+ ///
+ /// void SetDestinationToMousePosition()
+ /// {
+ /// RaycastHit hit;
+ /// Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
+ /// if (Physics.Raycast(ray, out hit))
+ /// {
+ /// myNavMeshAgent.SetDestination(hit.point);
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
public extern bool SetDestination(Vector3 target);
- // Destination to navigate towards.
+ ///Gets or attempts to set the destination of the agent in world-space units.
+ ///Getting:
+ ///
+ ///Returns the destination set for this agent.
+ ///
+ ///• If a destination is set but the path is not yet processed the position returned will be valid navmesh position that's closest to the previously set position.<br>
+ ///• If the agent has no path or requested path - returns the agents position on the navmesh.<br>
+ ///• If the agent is not mapped to the navmesh (e.g. Scene has no navmesh) - returns a position at infinity.
+ ///
+ ///Setting:
+ ///
+ ///Requests the agent to move to the valid navmesh position that's closest to the requested destination.
+ ///
+ ///• The path result may not become available until after a few frames. Use to query for outstanding results.<br>
+ ///• If it's not possible to find a valid nearby navmesh position (e.g. Scene has no navmesh) no path is requested. Use and check return value if you need to handle this case explicitly.
+ ///
+ /// ();
+ /// destination = agent.destination;
+ /// }
+ ///
+ /// void Update()
+ /// {
+ /// // Update destination if the target moves one unit
+ /// if (Vector3.Distance(destination, target.position) > 1.0f)
+ /// {
+ /// destination = target.position;
+ /// agent.destination = destination;
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
public extern Vector3 destination { get; set; }
- // Stop within this distance from the target position.
+ ///Stop within this distance from the target position.
+ ///It is seldom possible to land exactly at the target point, so this property can be used to set an acceptable radius within which the agent should stop. A larger stopping distance will give the agent more room for manoeuvre at the end of the path and might avoid sudden braking, turning or other unconvincing AI behaviour.
public extern float stoppingDistance { get; set; }
- // The current velocity of the [[NavMeshAgent]] component.
+ ///Access the current velocity of the component, or set a velocity to control the agent manually.
+ ///Reading the variable will return the current velocity of the agent based on the crowd simulation.
+ ///
+ ///Setting the variable will override the simulation (including: moving towards destination, collision avoidance, and acceleration control) and command the NavMesh Agent to move using the specific velocity directly. When the agent is controlled using a velocity, its movement is still constrained on the NavMesh.
+ ///
+ ///Setting the velocity directly, can be used for implementing player characters, which are moving on NavMesh and affecting the rest of the simulated crowd. In addition, setting priority to high (a small value is higher priority), will make other simulated agents to avoid the player controlled agent even more eagerly.
+ ///
+ ///It is recommended to set the velocity each frame when controlling the agent manually, and if releasing the control to the simulation, set the velocity to zero. If agent’s velocity is set to some value and then stopped updating it, the simulation will pick up from there and the agent will slowly decelerate (assuming no destination is set).
+ ///
+ ///Note that reading the velocity will always return value from the simulation. If you set the value, the effect will show up in the next update. Since the returned velocity comes from the simulation (including avoidance and collision handling), it can be different than the one you set.
+ ///
+ ///The velocity is specified in distance units per second (same as physics), and represented in global coordinate system.
public extern Vector3 velocity { get; set; }
- // The next position on the path.
+ ///Gets or sets the simulation position of the navmesh agent.
+ ///
+ /// The position vector is in world space coordinates and units.
+ ///
+ ///The nextPosition is coupled to . In the default case the navmesh agent's Transform position will match the internal simulation position at the time the script Update function is called. This coupling can be turned on and off by setting .
+ ///
+ ///When is true, the reflects the simulated position, when false the position of the transform and the navmesh agent is not synchronized, and you'll see a difference between the two in general. When is turned back on, the will be immediately move to match nextPosition.
+ ///
+ ///By setting nextPosition you can directly control where the internal agent position should be. The agent will be moved towards the position, but is constrained by the navmesh connectivity and boundaries. As such it will be useful only if the positions are continuously updated and assessed.
+ ///
+ /// Additionally it can be useful to control the agent position directly - especially if the
+ ///gameobject transform is controlled by something else - e.g. animator, physics, scripted or input.
+ ///
+ ///
+ /// ().updatePosition = false;
+ /// }
+ ///
+ /// void OnAnimatorMove()
+ /// {
+ /// transform.position = GetComponent().nextPosition;
+ /// }
+ ///}
+ ///]]>
+ ///
+ ///
+ /// ();
+ /// agent.updatePosition = !agentIsControlledByOther;
+ /// if (agentIsControlledByOther)
+ /// {
+ /// GetComponent().nextPosition = transform.position;
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
+ ///
+ ///
[NativeProperty("Position")]
public extern Vector3 nextPosition { get; set; }
- // The current steering target - usually the next corner or end point of the current path. (RO)
+ ///Get the current steering target along the path.
+ ///This is typically the next corner along the path or the end point of the path.
+ ///
+ ///Unless the agent is moving on an , there is a straight path between the agent and the steeringTarget.
+ ///
+ ///When approaching an OffMeshLink for traversal - the value is the position where the agent will enter the link.
+ ///While agent is traversing an OffMeshLink the value is the position where the agent will leave the link.
public extern Vector3 steeringTarget { get; }
- // The desired velocity of the agent including any potential contribution from avoidance. (RO)
+ ///The desired velocity of the agent including any potential contribution from avoidance.
public extern Vector3 desiredVelocity { get; }
- // Remaining distance along the current path - or infinity when not known. (RO)
+ ///The distance between the agent's position and the destination on the current path.
+ ///If the remaining distance is unknown then this will have a value of infinity.
public extern float remainingDistance { get; }
- // The relative vertical displacement of the owning [[GameObject]].
+ ///The relative vertical displacement of the owning .
public extern float baseOffset { get; set; }
- // Is agent currently positioned on an OffMeshLink. (RO)
+ ///Is the agent currently positioned on an OffMeshLink?
+ ///This property is useful when is false and custom movement is needed when crossing the link.
+ ///
+ ///
public extern bool isOnOffMeshLink
{
[NativeName("IsOnOffMeshLink")]
get;
}
- // Enables or disables the current link.
+ ///Enables or disables the current off-mesh link.
+ ///This function activates or deactivates the off-mesh link
+ ///where the agent is currently waiting. This is useful for
+ ///granting access to newly discovered areas of the game world or
+ ///simulating the creation or removal of an obstacle to an area.
+ ///Is the link activated?
+ ///
+ /// ();
+ /// }
+ /// void OpenDiscoveredArea(Hashtable areasDiscovered) {
+ /// if (agent.isOnOffMeshLink)
+ /// if (areasDiscovered.ContainsKey(agent.currentOffMeshLinkData.offMeshLink.name))
+ /// agent.ActivateCurrentOffMeshLink(true);
+ /// }
+ ///}
+ ///]]>
+ ///
public extern void ActivateCurrentOffMeshLink(bool activated);
- // The current [[OffMeshLinkData]].
+ ///The current .
+ ///In the case that this agent is not on an OffMeshLink the is marked as invalid. See also
public OffMeshLinkData currentOffMeshLinkData => GetCurrentOffMeshLinkDataInternal();
[FreeFunction("NavMeshAgentScriptBindings::GetCurrentOffMeshLinkDataInternal", HasExplicitThis = true)]
internal extern OffMeshLinkData GetCurrentOffMeshLinkDataInternal();
- // The next [[OffMeshLinkData]] on the current path.
+ ///The next on the current path.
+ ///In the case that the current path does not contain an OffMeshLink the is marked as invalid.
public OffMeshLinkData nextOffMeshLinkData => GetNextOffMeshLinkDataInternal();
[FreeFunction("NavMeshAgentScriptBindings::GetNextOffMeshLinkDataInternal", HasExplicitThis = true)]
internal extern OffMeshLinkData GetNextOffMeshLinkDataInternal();
- // Terminate OffMeshLink occupation and transfer the agent to the closest point on other side.
+ ///Completes the movement on the current OffMeshLink.
+ ///The agent will move to the closest valid navmesh position on the other end of the current OffMeshLink.
+ ///
+ ///CompleteOffMeshLink has no effect unless the agent is on an OffMeshLink ().
+ ///
+ ///When is disabled an agent will pause at an off-mesh link until this function is called.
+ ///It is useful for implementing custom movement across OffMeshLinks.
+ ///
+ /// ();
+ /// agent.autoTraverseOffMeshLink = false;
+ /// while (true)
+ /// {
+ /// if (agent.isOnOffMeshLink)
+ /// {
+ /// if (method == OffMeshLinkMoveMethod.NormalSpeed)
+ /// yield return StartCoroutine(NormalSpeed(agent));
+ /// else if (method == OffMeshLinkMoveMethod.Parabola)
+ /// yield return StartCoroutine(Parabola(agent, 2.0f, 0.5f));
+ /// agent.CompleteOffMeshLink();
+ /// }
+ /// yield return null;
+ /// }
+ /// }
+ ///
+ /// IEnumerator NormalSpeed(NavMeshAgent agent)
+ /// {
+ /// OffMeshLinkData data = agent.currentOffMeshLinkData;
+ /// Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
+ /// while (agent.transform.position != endPos)
+ /// {
+ /// agent.transform.position = Vector3.MoveTowards(agent.transform.position, endPos, agent.speed * Time.deltaTime);
+ /// yield return null;
+ /// }
+ /// }
+ ///
+ /// IEnumerator Parabola(NavMeshAgent agent, float height, float duration)
+ /// {
+ /// OffMeshLinkData data = agent.currentOffMeshLinkData;
+ /// Vector3 startPos = agent.transform.position;
+ /// Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
+ /// float normalizedTime = 0.0f;
+ /// while (normalizedTime < 1.0f)
+ /// {
+ /// float yOffset = height * 4.0f * (normalizedTime - normalizedTime * normalizedTime);
+ /// agent.transform.position = Vector3.Lerp(startPos, endPos, normalizedTime) + yOffset * Vector3.up;
+ /// normalizedTime += Time.deltaTime / duration;
+ /// yield return null;
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
+ ///
public extern void CompleteOffMeshLink();
- // Automate movement onto and off of OffMeshLinks.
+ ///Should the agent move across OffMeshLinks automatically?
+ ///Off-mesh links are used to connect disjoint regions of the NavMesh. Usually, a character should be able to pass through or traverse a link automatically, which will happen if this property is set to true. However, it can also be set to false in cases where special control over movement is needed.
+ ///
+ ///
public extern bool autoTraverseOffMeshLink { get; set; }
- // Automate braking of NavMeshAgent to avoid overshooting the destination.
+ ///Should the agent brake automatically to avoid overshooting the destination point?
+ ///If the agent needs to land close to the destination point then it will typically need to brake to avoid overshooting or endless "orbiting" around the target zone. If this property is set to true, the agent will brake automatically as it nears the destination.
public extern bool autoBraking { get; set; }
- // Attempt to acquire a new path if the existing path becomes invalid
+ ///Should the agent attempt to acquire a new path if the existing path becomes invalid?
+ ///A new path calculation is also attempted aquired if the agent reaches the end of a partial and stale path.
public extern bool autoRepath { get; set; }
- // Does this agent currently have a path. (RO)
+ ///Does the agent currently have a path? (RO)
+ ///This property will be true if the agent has a path calculated to the desired destination and false otherwise.
public extern bool hasPath
{
[NativeName("HasPath")]
get;
}
- // A path is being computed, but not yet ready. (RO)
+ ///Is a path in the process of being computed but not yet ready? (RO)
public extern bool pathPending
{
[NativeName("PathPending")]
get;
}
- // Is the current path stale. (RO)
+ ///Is the current path stale. (RO)
+ ///When true, the path may no longer be valid or optimal.
+ ///This flag will be set if: there are any changes to the , if any is enabled or disabled, or if the costs for the NavMeshAreas have been changed.
public extern bool isPathStale
{
[NativeName("IsPathStale")]
get;
}
- // Query the state of the current path.
+ ///The status of the current path (complete, partial or invalid).
+ ///Returns if either the path is invalid, or the agent is not yet initialized. (.)
+ ///
public extern NavMeshPathStatus pathStatus { get; }
- //*undocumented*
+ ///
[NativeProperty("EndPositionOfCurrentPath")]
public extern Vector3 pathEndPosition { get; }
- //*undocumented*
+ ///Warps agent to the provided position.
+ ///Returns true if successful, otherwise returns false.
+ ///New position to warp the agent to.
+ ///True if agent is successfully warped, otherwise false.
public extern bool Warp(Vector3 newPosition);
- // Apply relative movement to current position.
+ ///Apply relative movement to current position.
+ ///If the agent has a path it will be adjusted.
+ ///The relative movement vector.
public extern void Move(Vector3 offset);
+ ///Stop movement of this agent along its current path.
+ ///See for how to resume movement after stopping.
[Obsolete("Set isStopped to true instead.")]
public extern void Stop();
- // Stop movement of this agent along its current path.
[Obsolete("Set isStopped to true instead.")]
public void Stop(bool stopUpdates) { Stop(); }
- // Resumes the movement along the current path.
+ ///Resumes the movement along the current path after a pause.
+ ///See for how to pause movement along the current path.
[Obsolete("Set isStopped to false instead.")]
public extern void Resume();
+ ///Use this property to set, or get, whether the NavMesh agent stops or continues its movement along the current path.
+ ///If set to true, the NavMesh agent's movement stops along its current path. If set to false after the NavMesh agent has stopped, the NavMesh agent resumes its movement along the current path.
public extern bool isStopped
{
[FreeFunction("NavMeshAgentScriptBindings::GetIsStopped", HasExplicitThis = true)]
@@ -150,13 +429,22 @@ public extern bool isStopped
set;
}
- // Clears the current path. Note that this agent will not start looking for a new path until SetDestination is called.
+ ///Clears the current path.
+ ///When the path is cleared, the agent will not start looking for a new path until SetDestination is called.
+ ///
+ ///Note that if the agent is on an OffMeshLink when this function is called, it will complete the link immediately.
public extern void ResetPath();
- // Assign path to this agent.
+ ///Assign a new path to this agent.
+ ///If you successfully assign the path, the agent resumes movement toward the new target.
+ ///If the path cannot be assigned, the path is cleared (see ).
+ ///A path that was calculated for a different agent type than this agent's is ignored: the method returns false and the agent keeps its current path. Use or with a NavMeshQueryFilter to obtain a path for this agent type.
+ ///New path to follow.
+ ///True if the path is successfully assigned.
public extern bool SetPath([NotNull] NavMeshPath path);
- // Set or get a copy of the current path.
+ ///Property to get and set the current path.
+ ///This property can be useful for GUI, debugging and other purposes to get the points of the path calculated by the navigation system. Additionally, a path created from user code can be set for the agent to follow in the usual way. An example of this might be a patrol route designed for coverage rather than optimal distance between two points.
public NavMeshPath path
{
get
@@ -176,14 +464,126 @@ public NavMeshPath path
[NativeMethod("CopyPath")]
internal extern void CopyPathTo([NotNull] NavMeshPath path);
- // Locate the closest NavMesh edge.
+ ///Locate the closest NavMesh edge.
+ ///The returned object contains the position
+ ///and details of the nearest point on the nearest edge of the
+ ///Navmesh. Since an edge typically corresponds to a wall or
+ ///other large object, this could be used to make a character
+ ///take cover as close to the wall as possible.
+ ///Holds the properties of the resulting location.
+ ///True if a nearest edge is found.
+ ///
+ /// ();
+ /// }
+ ///
+ /// void Update() {
+ /// if (Input.GetMouseButtonDown(0))
+ /// TakeCover();
+ /// }
+ ///
+ /// void TakeCover() {
+ /// NavMeshHit hit;
+ /// if (agent.FindClosestEdge(out hit))
+ /// agent.SetDestination(hit.position);
+ /// }
+ ///}
+ ///]]>
+ ///
[NativeName("DistanceToEdge")]
public extern bool FindClosestEdge(out NavMeshHit hit);
- // Trace movement towards a target position in the NavMesh. Without moving the agent.
+ ///Trace a straight path towards a target postion in the NavMesh without moving the agent.
+ ///This function follows the path of a "ray" between the agent's
+ ///position and the specified target position. If an obstruction is
+ ///encountered along the line then a true value is returned and
+ ///the position and other details of the obstructing object are stored
+ ///in the hit parameter. This can be used to check if there is a clear
+ ///shot or line of sight between a character and a target object.
+ ///This function is preferable to the similar
+ ///because the line tracing is performed in a simpler way using the navmesh
+ /// and has a lower processing overhead.
+ ///The desired end position of movement.
+ ///Properties of the obstacle detected by the ray (if any).
+ ///True if there is an obstacle between the agent and the target position, otherwise false.
+ ///
+ /// ();
+ /// }
+ ///
+ /// void Update()
+ /// {
+ /// NavMeshHit hit;
+ /// if (!agent.Raycast(target.position, out hit))
+ /// {
+ /// // Target is "visible" from our position.
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
public extern bool Raycast(Vector3 targetPosition, out NavMeshHit hit);
- // Calculate a path to a specified point and store the resulting path.
+ ///Calculate a path to a specified point and store the resulting path.
+ ///Use this function to avoid gameplay delays by planning a path before it is needed. You can also use this function to check if a target position is reachable before moving the agent. The function takes into account the agent's , and area costs properties when it searches for a matching path.
+ ///
+ ///This function is synchronous. It performs path finding immediately, which can adversely affect the frame rate when processing very long paths. It is recommended to only perform a few path finds per frame when, for example, evaluating distances to cover points.
+ ///
+ ///Use the returned path to set the path for this agent, or an agent of the same type, with . For SetPath to work, the agent must be close to the starting point and be allowed to move through the area type where the start point is.
+ ///The final position of the path requested.
+ ///The resulting path.
+ ///True if either a complete or partial path is found. False otherwise.
+ ///
+ /// ();
+ /// var path = new NavMeshPath();
+ /// agent.CalculatePath(target.position, path);
+ /// switch (path.status)
+ /// {
+ /// case NavMeshPathStatus.PathComplete:
+ /// Debug.Log($"{agent.name} will be able to reach {target.name}.");
+ /// break;
+ /// case NavMeshPathStatus.PathPartial:
+ /// Debug.LogWarning($"{agent.name} will only be able to move partway to {target.name}.");
+ /// break;
+ /// default:
+ /// Debug.LogError($"There is no valid path for {agent.name} to reach {target.name}.");
+ /// break;
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
public bool CalculatePath(Vector3 targetPosition, NavMeshPath path)
{
path.ClearCorners();
@@ -193,63 +593,152 @@ public bool CalculatePath(Vector3 targetPosition, NavMeshPath path)
[FreeFunction("NavMeshAgentScriptBindings::CalculatePathInternal", HasExplicitThis = true)]
extern bool CalculatePathInternal(Vector3 targetPosition, [NotNull] NavMeshPath path);
- // Sample a position along the current path.
+ ///Sample a position along the current path.
+ ///This function looks ahead the specified maxDistance along the current path, up to the third
+ /// corner. It returns details of the mesh
+ /// at that position in a object. You can use this
+ /// to check the type of surface that lies ahead before the character gets there. For example, characters could
+ /// raise their guns above their heads if they are about to wade through water.
+ ///
+ /// If the path sampling terminates on an outer edge, hit.mask is 0. If the path sampling terminates at an area not specified by areaMask, hit.mask contains the area mask of the blocking polygon. If the sampling reaches the end of the path, or the limit at the path's third corner, hit.mask contains the area mask at that position on the NavMesh.
+ ///A bitfield mask specifying which NavMesh areas can be passed when tracing the path.
+ ///Terminate scanning the path at this distance.
+ ///Holds the properties of the resulting location.
+ ///True if terminated before reaching the position at maxDistance, false otherwise.
+ ///
+ /// ();
+ /// waterMask = 1 << NavMesh.GetAreaFromName("Water");
+ /// agent.SetDestination(target.position);
+ /// }
+ ///
+ /// void Update()
+ /// {
+ /// NavMeshHit hit;
+ ///
+ /// // Check all areas one length unit ahead.
+ /// if (!agent.SamplePathPosition(NavMesh.AllAreas, 1.0F, out hit))
+ /// if ((hit.mask & waterMask) != 0)
+ /// {
+ /// // Water detected along the path...
+ /// }
+ /// }
+ ///}
+ ///]]>
+ ///
public extern bool SamplePathPosition(int areaMask, float maxDistance, out NavMeshHit hit);
+ ///Sets the cost for traversing over geometry of the layer type.
+ ///If you enable or disable the agent then the cost will be reset to the default layer cost.
+ ///Layer index.
+ ///New cost for the specified layer.
[Obsolete("Use SetAreaCost instead.")]
[NativeMethod("SetAreaCost")]
public extern void SetLayerCost(int layer, float cost);
+ ///Gets the cost for crossing ground of a particular type.
+ ///The cost of a path is the amount of "difficulty" involved in following it - the shortest path may not be the quickest if it passes over difficult ground, such as mud, snow, etc. Different types of ground are denoted by navmesh layers in Unity. The cost of a particular layer is given in cost units per distance unit. Note that the cost of a path applies to the pathfinding only and does not automatically affect the movement speed of the agent when following the path. Indeed, the path's cost may denote other factors such as danger (safe but long path through a minefield) or visibility (long path that keeps a character in the shadows).
+ ///Layer index.
+ ///Current cost of specified layer.
[Obsolete("Use GetAreaCost instead.")]
[NativeMethod("GetAreaCost")]
public extern float GetLayerCost(int layer);
+ ///Sets the cost for traversing over areas of the area type.
+ ///If you enable or disable the agent then the cost will be reset to the default layer cost.
+ ///Area cost.
+ ///New cost for the specified area index.
public extern void SetAreaCost(int areaIndex, float areaCost);
+ ///Gets the cost for path calculation when crossing area of a particular type.
+ ///The cost of a path is the amount of "difficulty" involved in calculating it - the shortest path may not be the best if it passes over difficult ground, such as mud, snow, etc. Different types of areas are denoted by navmesh areas in Unity. The cost of a particular area is given in cost units per distance unit. Note that the cost of a path applies to the pathfinding only and does not automatically affect the movement speed of the agent when following the path. Indeed, the path's cost may denote other factors such as danger (safe but long path through a minefield) or visibility (long path that keeps a character in the shadows).
+ ///Area Index.
+ ///Current cost for specified area index.
public extern float GetAreaCost(int areaIndex);
+ ///Returns the owning object of the NavMesh the agent is currently placed on.
+ ///If no owner is set for a NavMesh or link instance the return value is null.
+ ///
+ ///
public Object navMeshOwner => GetOwnerInternal();
+ ///The type ID for the agent.
+ ///This identifier determines which NavMeshes are available for the Agent to move on. See also . Changing this ID will reset the Agent's current path.
public extern int agentTypeID { get; set; }
[NativeName("GetCurrentPolygonOwner")]
extern Object GetOwnerInternal();
+ ///Specifies which NavMesh layers are passable (bitfield). Changing walkableMask will make the path stale (see ).
[Obsolete("Use areaMask instead.")]
public int walkableMask { get { return areaMask; } set { areaMask = value; } }
+ ///Specifies which NavMesh areas are passable. Changing areaMask will make the path stale (see ).
+ ///This is a bitfield.
public extern int areaMask { get; set; }
- // Maximum movement speed.
+ ///Maximum movement speed when following a path.
+ ///An agent will typically need to speed up and slow down as it follows a path (eg, it will slow down to make a tight turn). The speed is often limited by the length of a path segment and the time taken to accelerate and brake, but the speed will not exceed the value set by this property even on a long, straight path.
public extern float speed { get; set; }
- // Maximum rotation speed in (deg/s).
+ ///Maximum turning speed in (deg/s) while following a path.
+ ///This is the maximum rate at which the agent can turn as it rounds the "corner" defined by a waypoint. The actual turning circle is also influenced by the speed of the agent on approach and also the maximum acceleration.
public extern float angularSpeed { get; set; }
- // Maximum acceleration.
+ ///The maximum acceleration of an agent as it follows a path, given in units / sec^2.
+ ///An agent does not follow precisely the line segments of the path calculated by the navigation system but rather uses the waypoints along the path as intermediate destinations. This value is the maximum amount by which the agent can accelerate while moving towards the next waypoint.
public extern float acceleration { get; set; }
- // Should the agent update the transform position.
+ ///Gets or sets whether the transform position is synchronized with the simulated agent position. The default value is true.
+ ///When true: changing the transform position will affect the simulated position and vice-versa.
+ ///
+ ///When false: the simulated position will not be applied to the transform position and vice-versa.
+ ///
+ ///Setting to false can be used to enable explicit control of the transform position via script.
+ ///This allows you to use the agent's simulated position to drive another component, which in turn sets the transform position (eg. animation with root motion or physics).
+ ///
+ ///When enabling the (from previously being disabled), the transform will be moved to the simulated position. This way the agent stays constrained to the navmesh surface.
public extern bool updatePosition { get; set; }
- // Should the agent update the transform orientation.
+ ///Should the agent update the transform orientation?
public extern bool updateRotation { get; set; }
+ ///Allows you to specify whether the agent should be aligned to the up-axis of the NavMesh or link that it is placed on.
+ ///When this value is set to true, the agent will always be aligned to the local up-axis of the NavMesh or link that it is currently on. When set to false, the agent’s orientation is unaffected by the orientation of the NavMesh.
public extern bool updateUpAxis { get; set; }
- // Agent avoidance radius.
+ ///The avoidance radius for the agent.
+ ///This is the agent's "personal space" within which obstacles and other agents should not pass.
public extern float radius { get; set; }
- // Agent height.
+ ///The height of the agent for purposes of passing under obstacles, etc.
public extern float height { get; set; }
- // The level of quality of avoidance.
+ ///The level of quality of avoidance.
+ ///This property lets you trade off the precision of obstacle avoidance againt the processor load required to achieve it. The exact quality/performance values will depend heavily on the complexity of the Scene but as a general rule, faster performance can be achieved at the cost of quality and vice versa.
public extern ObstacleAvoidanceType obstacleAvoidanceType { get; set; }
- // The avoidance priority level.
+ ///The avoidance priority level.
+ ///When the agent is performing avoidance, agents of lower priority are ignored.
+ ///The valid range is from 0 to 99 where:
+ ///Most important = 0. Least important = 99. Default = 50.
public extern int avoidancePriority { get; set; }
- // Is agent mapped to navmesh
+ ///Is the agent currently bound to the navmesh?
+ ///This property is false if the agent, for some reason, could not bind to the navmesh. E.g. if Scene has no navmesh.
public extern bool isOnNavMesh
{
[NativeName("InCrowdSystem")]
diff --git a/Modules/AI/Components/NavMeshObstacle.bindings.cs b/Modules/AI/Components/NavMeshObstacle.bindings.cs
index 954da638c3..eae5967032 100644
--- a/Modules/AI/Components/NavMeshObstacle.bindings.cs
+++ b/Modules/AI/Components/NavMeshObstacle.bindings.cs
@@ -8,49 +8,148 @@
namespace UnityEngine.AI
{
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
+ ///Shape of the obstacle.
[MovedFrom("UnityEngine")]
public enum NavMeshObstacleShape
{
- // Capsule shaped obstacle.
+ ///Capsule shaped obstacle.
Capsule = 0,
- // Box shaped obstacle.
+ ///Box shaped obstacle.
Box = 1,
}
- // Navigation mesh obstacle.
+ ///An obstacle for NavMeshAgents to avoid.
+ ///A NavMeshObstacle is cylindrical in shape and can move around the surface of the NavMesh with a specified velocity. By default, the obstacle will only affect the agent's avoidance behaviour rather than the pathfinding. This means that the agent will ignore the obstacle when plotting a path but will sidestep around it while moving along the path. If carving is enabled, the obstacle will create a temporary "hole" in the NavMesh. The hole will be recognised by the pathfinding, so paths will be plotted to avoid the obstacle. This means that if, say, an obstacle blocks a narrow gap, the pathfinding will seek an alternative route to the target. Without carving, the agent will head for the gap but won't be able to pass until the obstacle is clear.
+ ///
[MovedFrom("UnityEngine")]
[NativeHeader("Modules/AI/Components/NavMeshObstacle.bindings.h")]
[HelpURL("https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/NavMeshObstacle.html")]
public sealed class NavMeshObstacle : Behaviour
{
- // Obstacle height.
+ ///Height of the obstacle's cylinder shape.
+ ///
public extern float height { get; set; }
- // Obstacle radius.
+ ///Radius of the obstacle's capsule shape.
+ ///
public extern float radius { get; set; }
- // Obstacle velocity.
+ ///Velocity at which the obstacle moves around the NavMesh.
+ ///
+ ///
+ /// /// Update the current GameObject's NavMesh Obstacle velocity according to its position changes.
+ /// /// Useful when the position of an object is controlled by script.
+ /// ///
+ /// public class ManualObstacleVelocityUpdater : MonoBehaviour
+ /// {
+ /// NavMeshObstacle m_Obstacle;
+ /// Vector3 m_LastPosition;
+ ///
+ /// void Start()
+ /// {
+ /// m_Obstacle = GetComponent();
+ /// m_LastPosition = transform.position;
+ /// }
+ ///
+ /// void Update()
+ /// {
+ /// var deltaTime = Time.deltaTime;
+ /// if (m_Obstacle && deltaTime > Mathf.Epsilon)
+ /// {
+ /// // Compute this frame's velocity
+ /// var newPosition = transform.position;
+ /// var velocity = (newPosition - m_LastPosition) / deltaTime;
+ /// m_Obstacle.velocity = velocity;
+ ///
+ /// // Keep track of the last considered position
+ /// m_LastPosition = newPosition;
+ /// }
+ /// }
+ /// }
+ ///]]>
+ ///
public extern Vector3 velocity { get; set; }
- // Enable carving
+ ///Should this obstacle make a cut-out in the navmesh.
+ ///When enabled, this changes the navmesh by cutting out a hole. The shape of the hole is based on the size and shape set on and the navmesh bake settings for radius and height.
+ ///
+ ///When the obstacle moves, the carved hole will also move but to reduce CPU overhead the hole is only recalculated when necessary. The recalculation logic has two options: 1) carve when stationary, 2) carve when moved.
+ ///
+ ///"Carve when stationary" is the default behavior and is used when is set to true. The obstacle is treated as moving when it has moved more than the distance set by . At this time, the carved hole is removed. When the obstacle has stopped moving, and has been stationary more than seconds, the obstacles is treated stationary and carving is updated again. While the obstacle is moving, the agents will avoid it using the collision avoidance, but will not plan paths around it. This mode is generally the best choice in terms of performance. It is good match when the game object is controlled by physics (i.e. crates and barrels).
+ ///
+ ///"Carve when moved" behavior is used when is set to false. In this mode the carved hole is updated when the obstacle has moved more than the distance set by . This mode is well suited for large slowly moving obstacles, for example a tank that is being avoided by infantry.
public extern bool carving { get; set; }
- // When carving enabled, carve only when obstacle is stationary, moving obstacles are avoided dynamically.
+ ///Should this obstacle be carved when it is constantly moving?
+ ///When this property is enabled, the obstacle will carve a hole only when it is stationary. There will be no hole carved when the object is moving. See for full description of different carving behaviors.
public extern bool carveOnlyStationary { get; set; }
- // Update carving if moved at least this distance, or if carveWhenStationary if moved at least this distance, the obstacle is considered moving.
+ ///Threshold distance for updating a moving carved hole (when carving is enabled).
+ ///If the has moved a distance shorter than the threshold since last carving then the navmesh will not be updated.
+ ///
[NativeProperty("MoveThreshold")]
public extern float carvingMoveThreshold { get; set; }
- // If carveWhenStationary is set, the obstacle is considered stationary if it has not moved during this long period.
+ ///Time to wait until obstacle is treated as stationary (when carving and carveOnlyStationary are enabled).
+ ///If the has been moving, and becomes still, We wait carvingTimeToStationary time until the obstacle is treated stationary by the carving system. See for full description of different carving behaviors.
[NativeProperty("TimeToStationary")]
public extern float carvingTimeToStationary { get; set; }
- // Shape of the obstacle, NavMeshObstacleShape.Box or NavMeshObstacleShape.Capsule.
+ ///The shape of the obstacle.
+ ///
+ /// Set or get the shape of the .
+ /// A newly created has a shape of the shape.
+ /// The obstacle shapes are listed in .
+ /// **Note:** When the shape is changed the is set back to zero.
+ ///
public extern NavMeshObstacleShape shape { get; set; }
+ ///The center of the obstacle, measured in the object's local space.
+ ///**Note:** When a is created the is set to zero.
+ ///
+ /// ();
+ /// Debug.Log(navMeshObstacle.center);
+ /// }
+ ///}
+ ///]]>
+ ///
public extern Vector3 center { get; set; }
+ ///The size of the obstacle, measured in the object's local space.
+ ///The size will be scaled by the transform's scale.
+ ///
+ /// ();
+ /// Mesh mesh = GetComponent().mesh;
+ /// obstacle.shape = NavMeshObstacleShape.Box;
+ /// obstacle.size = mesh.bounds.size;
+ /// }
+ ///}
+ ///]]>
+ ///
public extern Vector3 size
{
[FreeFunction("NavMeshObstacleScriptBindings::GetSize", HasExplicitThis = true)]
diff --git a/Modules/AI/Components/OffMeshLink.bindings.cs b/Modules/AI/Components/OffMeshLink.bindings.cs
index 6697143c69..a78dfec5d1 100644
--- a/Modules/AI/Components/OffMeshLink.bindings.cs
+++ b/Modules/AI/Components/OffMeshLink.bindings.cs
@@ -9,22 +9,24 @@
namespace UnityEngine.AI
{
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
- // Link type specifier.
+ ///Link type specifier.
[MovedFrom("UnityEngine")]
public enum OffMeshLinkType
{
- // Manually specified type of link.
+ ///Manually specified type of link.
LinkTypeManual = 0,
- // Vertical drop.
+ ///Vertical drop.
LinkTypeDropDown = 1,
- // Horizontal jump.
+ ///Horizontal jump.
LinkTypeJumpAcross = 2
}
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
- // State of OffMeshLink.
+ ///State of OffMeshLink.
+ ///
+ ///
[MovedFrom("UnityEngine")]
[NativeHeader("Modules/AI/Components/OffMeshLink.bindings.h")]
public partial struct OffMeshLinkData
@@ -36,22 +38,30 @@ public partial struct OffMeshLinkData
internal Vector3 m_StartPos;
internal Vector3 m_EndPos;
- // Is link valid (RO).
+ ///Is link valid (RO).
public bool valid => m_Valid != 0;
- // Is link active (RO).
+ ///Is link active (RO).
public bool activated => m_Activated != 0;
- // Link type specifier (RO).
+ ///Link type specifier (RO).
public OffMeshLinkType linkType => m_LinkType;
- // Link start world position (RO).
+ ///Link start world position (RO).
public Vector3 startPos => m_StartPos;
- // Link end world position (RO).
+ ///Link end world position (RO).
public Vector3 endPos => m_EndPos;
- // The object that created this link instance if the link type is a manually placed [[Offmeshlink]] or [[NavMeshLinkData]] (RO).
+ ///Get the object used to create the NavMesh link represented by the data in this struct.
+ ///If the link has been instantiated by a call to then this property returns the object that might have been associated to that instance with a call to . If that link instance has no owner assigned to it then this property returns null.
+ ///
+ ///If the link was instantiated by an component then the owner returns a reference to that component.
+ ///
+ ///To effectively use this property in your scripts you need to determine the exact type of the returned object. To do that cast the object to the types that you use in your project to create NavMesh links.
+ ///
+ ///For automatically-generated Jump or Drop links, this property returns null.
+ ///
public Object owner => GetLinkOwnerInternal(m_InstanceID);
[FreeFunction("OffMeshLinkScriptBindings::GetLinkOwnerInternal")]
diff --git a/Modules/AI/Components/OffMeshLink.deprecated.cs b/Modules/AI/Components/OffMeshLink.deprecated.cs
index 869fbb4517..09a32d9b13 100644
--- a/Modules/AI/Components/OffMeshLink.deprecated.cs
+++ b/Modules/AI/Components/OffMeshLink.deprecated.cs
@@ -10,7 +10,8 @@ namespace UnityEngine.AI
{
public partial struct OffMeshLinkData
{
- // The [[OffMeshLink]] if the link type is a manually placed Offmeshlink (RO).
+ ///The if the link type is a manually placed Offmeshlink (RO).
+ ///Automatically generated Jump and drop links will return null.
[Obsolete("offMeshLink has been deprecated. Use 'owner' instead.")]
public OffMeshLink offMeshLink => GetOffMeshLinkInternal(m_InstanceID);
@@ -20,42 +21,55 @@ public partial struct OffMeshLinkData
#pragma warning restore CS0618
}
- // Link allowing movement outside the planar navigation mesh.
+ ///Link allowing movement outside the planar navigation mesh.
[MovedFrom("UnityEngine")]
[Obsolete("The OffMeshLink component is no longer supported and will be removed. Use NavMeshLink instead.")]
[HelpURL("https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/OffMeshLink.html")]
public sealed class OffMeshLink : Behaviour
{
- // Is link active.
+ ///Is link active.
[Obsolete("activated has been deprecated together with the class. Declare the object as NavMeshLink and use activated as before.")]
public extern bool activated { get; set; }
- // Is link occupied. (RO)
+ ///Is link occupied. (RO)
[Obsolete("occupied has been deprecated together with the class. Declare the object as NavMeshLink and use occupied as before.")]
public extern bool occupied { get; }
- // Modify pathfinding cost for the link.
+ ///Modify pathfinding cost for the link.
+ ///When the costOverride value is non-negative the cost of moving over the OffMeshLink
+ ///is equivalent to the costOverride value times the Euclidean distance
+ ///between OffMeshLink end points.
[Obsolete("costOverride has been deprecated together with the class. Declare the object as NavMeshLink and use costModifier instead.")]
public extern float costOverride { get; set; }
+ ///Can link be traversed in both directions.
+ ///When false the link can only be traversed from start to end.
[Obsolete("biDirectional has been deprecated together with the class. Declare the object as NavMeshLink and use bidirectional instead.")]
public extern bool biDirectional { get; set; }
+ ///Explicitly update the link endpoints.
+ ///Updates the OffMeshLink endpoints to match the transforms specified by the start and end transforms.
[Obsolete("UpdatePositions() has been deprecated together with the class. Declare the object as NavMeshLink and use UpdateLink() instead.")]
public extern void UpdatePositions();
+ ///NavMeshLayer for this OffMeshLink component.
[Obsolete("navMeshLayer has been deprecated together with the class. Declare the object as NavMeshLink and use area instead. (UnityUpgradable) -> area")]
public int navMeshLayer { get { return area; } set { area = value; } }
+ ///NavMesh area index for this OffMeshLink component.
[Obsolete("area has been deprecated together with the class. Declare the object as NavMeshLink and use area as before.")]
public extern int area { get; set; }
+ ///Automatically update endpoints.
+ ///The OffMeshLink component will try to match endpoint transforms specified by and . See also .
[Obsolete("autoUpdatePositions has been deprecated together with the class. Declare the object as NavMeshLink and use autoUpdate instead.")]
public extern bool autoUpdatePositions { get; set; }
+ ///The transform representing link start position.
[Obsolete("startTransform has been deprecated together with the class. Declare the object as NavMeshLink and use startTransform as before.")]
public extern Transform startTransform { get; set; }
+ ///The transform representing link end position.
[Obsolete("endTransform has been deprecated together with the class. Declare the object as NavMeshLink and use endTransform as before.")]
public extern Transform endTransform { get; set; }
}
diff --git a/Modules/AI/LowLevel/Scripting/Bindings/NavLocation.bindings.cs b/Modules/AI/LowLevel/Scripting/Bindings/NavLocation.bindings.cs
index df3ef46251..ba756a2843 100644
--- a/Modules/AI/LowLevel/Scripting/Bindings/NavLocation.bindings.cs
+++ b/Modules/AI/LowLevel/Scripting/Bindings/NavLocation.bindings.cs
@@ -8,9 +8,13 @@
namespace Unity.AI.Navigation.LowLevel;
+///A position mapped to a navigation node.
+
public readonly struct NavLocation : IEquatable
{
+ ///
public NavNode node { get; }
+ ///
public Vector3 position { get; }
internal NavLocation(Vector3 position, NavNode node)
@@ -19,30 +23,35 @@ internal NavLocation(Vector3 position, NavNode node)
this.node = node;
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator ==(NavLocation left, NavLocation right)
{
return left.node.Equals(right.node) && left.position.Equals(right.position);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator !=(NavLocation left, NavLocation right)
{
return !left.node.Equals(right.node) || !left.position.Equals(right.position);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly bool Equals(NavLocation other)
{
return node.Equals(other.node) && position.Equals(other.position);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override bool Equals(object obj)
{
return obj is NavLocation other && node.Equals(other.node) && position.Equals(other.position);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override int GetHashCode()
{
diff --git a/Modules/AI/LowLevel/Scripting/Bindings/NavLowLevelTypes.bindings.cs b/Modules/AI/LowLevel/Scripting/Bindings/NavLowLevelTypes.bindings.cs
index e186a6cf00..11f1de0418 100644
--- a/Modules/AI/LowLevel/Scripting/Bindings/NavLowLevelTypes.bindings.cs
+++ b/Modules/AI/LowLevel/Scripting/Bindings/NavLowLevelTypes.bindings.cs
@@ -7,26 +7,41 @@
namespace Unity.AI.Navigation.LowLevel;
// Keep in sync with the values in NavMeshTypes.h
+///The state of a navigation query after running an operation.
+
[Flags]
public enum NavQueryStatus
{
// High level status.
+ ///
Failure = 1 << 31,
+ ///
Success = 1 << 30,
+ ///
InProgress = 1 << 29,
// Detail information for status.
+ ///
StatusDetailMask = 0x0ffffff,
+ ///
InvalidParameter = 1 << 3, // An input parameter was invalid.
+ ///
MoreDataAvailable = 1 << 4, // Result buffer for the query was too small to store all results.
+ ///
MaxNodesToVisitExceeded = 1 << 5, // Query ran out of nodes during search.
+ ///
PartialResult = 1 << 6 // Query did not reach the end location, returning best guess.
}
// Flags describing node properties. Keep in sync with the enum declared in NavMesh.h
+///Describes whether the navigation node is created by a NavMesh or a NavMeshLink.
+
public enum NavNodeType
{
+ ///
Undefined = -1,
+ ///
Polygon = 0, // Regular ground polygons.
+ ///
Link = 1 // Off-mesh connections.
}
diff --git a/Modules/AI/LowLevel/Scripting/Bindings/NavNode.bindings.cs b/Modules/AI/LowLevel/Scripting/Bindings/NavNode.bindings.cs
index dcd7133ebd..1aff230eca 100644
--- a/Modules/AI/LowLevel/Scripting/Bindings/NavNode.bindings.cs
+++ b/Modules/AI/LowLevel/Scripting/Bindings/NavNode.bindings.cs
@@ -8,28 +8,36 @@
namespace Unity.AI.Navigation.LowLevel;
+///Node in the navigation graph.
+
public struct NavNode : IEquatable
{
internal ulong m_PolyRef;
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator ==(NavNode left, NavNode right) { return left.m_PolyRef == right.m_PolyRef; }
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator !=(NavNode left, NavNode right) { return left.m_PolyRef != right.m_PolyRef; }
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly bool Equals(NavNode other) { return m_PolyRef == other.m_PolyRef; }
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override bool Equals(object obj)
{
return obj is NavNode other && m_PolyRef == other.m_PolyRef;
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override int GetHashCode() { return m_PolyRef.GetHashCode(); }
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly bool IsNull() { return m_PolyRef == 0; }
}
diff --git a/Modules/AI/LowLevel/Scripting/Bindings/NavQueryBuffer.bindings.cs b/Modules/AI/LowLevel/Scripting/Bindings/NavQueryBuffer.bindings.cs
index 41d9f2eea5..42f8a962f5 100644
--- a/Modules/AI/LowLevel/Scripting/Bindings/NavQueryBuffer.bindings.cs
+++ b/Modules/AI/LowLevel/Scripting/Bindings/NavQueryBuffer.bindings.cs
@@ -12,6 +12,8 @@
namespace Unity.AI.Navigation.LowLevel;
+///Object used for doing navigation operations in a .
+
[NativeContainer]
[StructLayout(LayoutKind.Sequential)]
[NativeHeader("Modules/AI/LowLevel/NavWorld.bindings.h")]
@@ -28,7 +30,7 @@ public struct NavQueryBuffer : IDisposable, IEquatable
internal readonly bool isNull => m_NavMeshQuery == IntPtr.Zero;
internal AtomicSafetyHandle m_Safety;
- internal uint m_SafetyOpenListId;
+ internal uint m_SafetyUniqueId;
internal static readonly int k_StaticSafetyId = AtomicSafetyHandle.NewStaticSafetyId();
@@ -44,6 +46,7 @@ public struct NavQueryBuffer : IDisposable, IEquatable
// Keep in sync with kMaxNavMeshNodePoolSize = USHRT_MAX from NavMeshNode.h
const int k_MaxNavMeshNodePoolSize = ushort.MaxValue;
+ ///
public NavQueryBuffer(NavWorld world, Allocator allocator, int maxNodesToVisit = 1024)
{
if (!world.IsValid())
@@ -80,12 +83,13 @@ public NavQueryBuffer(NavWorld world, Allocator allocator, int maxNodesToVisit =
AddQuerySafety(m_NavMeshQuery, m_Safety);
- m_SafetyOpenListId = GetOpenListId(m_NavMeshQuery);
- var brokenNodePoolInit = m_SafetyOpenListId == 0;
+ m_SafetyUniqueId = GetUniqueId(m_NavMeshQuery);
+ var brokenNodePoolInit = m_SafetyUniqueId == 0;
if (brokenNodePoolInit)
- m_SafetyOpenListId = uint.MaxValue;
+ m_SafetyUniqueId = uint.MaxValue;
}
+ ///
[WriteAccessRequired]
public void Dispose()
{
@@ -120,39 +124,44 @@ public void Dispose()
static extern void Destroy(IntPtr navMeshQuery);
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator ==(NavQueryBuffer left, NavQueryBuffer right)
{
return left.Equals(right);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator !=(NavQueryBuffer left, NavQueryBuffer right)
{
return !left.Equals(right);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly bool Equals(NavQueryBuffer other)
{
var pointersEqual = m_NavMeshQuery == other.m_NavMeshQuery && m_NavMeshUniqueId == other.m_NavMeshUniqueId;
- pointersEqual = pointersEqual && m_SafetyOpenListId == other.m_SafetyOpenListId;
+ pointersEqual = pointersEqual && m_SafetyUniqueId == other.m_SafetyUniqueId;
return pointersEqual;
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override bool Equals(object obj)
{
return obj is NavQueryBuffer other && Equals(other);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override int GetHashCode()
{
var hashCode = HashCode.Combine(m_NavMeshQuery, m_NavMeshUniqueId);
- hashCode = HashCode.Combine(hashCode, m_SafetyOpenListId);
+ hashCode = HashCode.Combine(hashCode, m_SafetyUniqueId);
return hashCode;
}
@@ -160,7 +169,7 @@ public readonly override int GetHashCode()
static extern void RemoveQuerySafety(IntPtr navMeshQuery, AtomicSafetyHandle handle);
[NativeMethod(IsThreadSafe = true)]
- static extern uint GetOpenListId(IntPtr navMeshQuery);
+ static extern uint GetUniqueId(IntPtr navMeshQuery);
[NativeMethod(IsThreadSafe = true)]
static extern bool HasNodePool(IntPtr navMeshQuery);
@@ -189,8 +198,8 @@ internal readonly void CheckValidAndThrow()
throw new ObjectDisposedException(k_NoInternalQueryAllocatedErrorMessage);
}
- var safetyIdAtKnownAddress = GetOpenListId(m_NavMeshQuery);
- if (safetyIdAtKnownAddress != m_SafetyOpenListId)
+ var currentUniqueId = GetUniqueId(m_NavMeshQuery);
+ if (currentUniqueId != m_SafetyUniqueId)
throw new ObjectDisposedException(k_NoInternalQueryAllocatedErrorMessage);
}
}
diff --git a/Modules/AI/LowLevel/Scripting/Bindings/NavWorld.bindings.cs b/Modules/AI/LowLevel/Scripting/Bindings/NavWorld.bindings.cs
index d8ba060157..402d2c4e5d 100644
--- a/Modules/AI/LowLevel/Scripting/Bindings/NavWorld.bindings.cs
+++ b/Modules/AI/LowLevel/Scripting/Bindings/NavWorld.bindings.cs
@@ -24,6 +24,8 @@ struct NavMeshPointers
public uint m_UniqueId;
}
+///Assembles together a collection of NavMesh surfaces and links that are used as a whole for performing navigation operations.
+
[NativeContainer]
[NativeContainerIsReadOnly]
[StructLayout(LayoutKind.Sequential)]
@@ -52,6 +54,7 @@ public struct NavWorld : IDisposable, IEquatable
[NativeMethod(IsThreadSafe = true)]
static extern bool IsValidWorldInternal(IntPtr navMesh, IntPtr immutableQuery, uint uniqueId);
+ ///
public readonly bool IsValid()
{
return m_NavMeshPtr != IntPtr.Zero
@@ -61,6 +64,7 @@ public readonly bool IsValid()
static extern NavMeshPointers GetDefaultWorldInternal();
+ ///
public static NavWorld GetDefaultWorld()
{
var pointers = GetDefaultWorldInternal();
@@ -85,6 +89,7 @@ public static NavWorld GetDefaultWorld()
// Explicit cleanup of the safety handle which is otherwise
// removed only when the underlying NavMesh is destroyed.
+ ///
public void Dispose()
{
if (AtomicSafetyHandle.IsValidNonDefaultHandle(m_Safety))
@@ -100,18 +105,21 @@ public void Dispose()
m_ImmutableQuery = IntPtr.Zero;
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator ==(NavWorld left, NavWorld right)
{
return left.Equals(right);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public static bool operator !=(NavWorld left, NavWorld right)
{
return !left.Equals(right);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly bool Equals(NavWorld other)
{
@@ -120,12 +128,14 @@ public readonly bool Equals(NavWorld other)
&& m_UniqueId == other.m_UniqueId;
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override bool Equals(object obj)
{
return obj is NavWorld other && Equals(other);
}
+ ///
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public readonly override int GetHashCode()
{
@@ -156,6 +166,7 @@ readonly void CheckBufferMatchAndThrow(NavQueryBuffer queryBuffer)
static extern void AddDependencyInternal(IntPtr navMesh, JobHandle handle);
+ ///
public readonly void AddDependency(JobHandle job)
{
CheckValidPtrAndThrow();
@@ -169,6 +180,7 @@ public readonly void AddDependency(JobHandle job)
static extern NavLocation MapLocation(IntPtr navMeshQuery, Vector3 position, Vector3 extents,
int agentTypeID, int areaMask = NavMesh.AllAreas);
+ ///
public readonly NavLocation MapLocation(Vector3 position, Vector3 extents, int agentTypeId,
int areaMask = NavMesh.AllAreas)
{
@@ -176,6 +188,7 @@ public readonly NavLocation MapLocation(Vector3 position, Vector3 extents, int a
return MapLocation(m_ImmutableQuery, position, extents, agentTypeId, areaMask);
}
+ ///
public readonly unsafe NavQueryStatus BeginFindPath(NavQueryBuffer queryBuffer,
NavLocation start, NavLocation end,
int areaMask = NavMesh.AllAreas, NativeArray costs = new())
@@ -229,6 +242,7 @@ public readonly unsafe NavQueryStatus BeginFindPath(NavQueryBuffer queryBuffer,
return BeginFindPath(queryBuffer.navMeshQueryPtr, start, end, areaMask, costsPtr);
}
+ ///
public readonly NavQueryStatus ContinueFindPath(NavQueryBuffer queryBuffer, int nodesToVisit, out int nodesVisited)
{
CheckValidPtrAndThrow();
@@ -246,6 +260,7 @@ public readonly NavQueryStatus ContinueFindPath(NavQueryBuffer queryBuffer, int
return ContinueFindPath(queryBuffer.navMeshQueryPtr, nodesToVisit, out nodesVisited);
}
+ ///
public readonly NavQueryStatus EndFindPath(NavQueryBuffer queryBuffer, out int pathSize)
{
CheckValidPtrAndThrow();
@@ -263,6 +278,7 @@ public readonly NavQueryStatus EndFindPath(NavQueryBuffer queryBuffer, out int p
return EndFindPath(queryBuffer.navMeshQueryPtr, out pathSize);
}
+ ///
public readonly unsafe int GetResultFromFindPath(NavQueryBuffer queryBuffer, NativeSlice path)
{
CheckValidPtrAndThrow();
@@ -293,12 +309,14 @@ static extern unsafe NavQueryStatus BeginFindPath(IntPtr navMeshQuery,
[NativeMethod(IsThreadSafe = true)]
static extern bool IsValidNode(IntPtr navMeshPtr, NavNode node);
+ ///
public readonly bool IsValid(NavNode node)
{
CheckValidPtrAndThrow();
return node.m_PolyRef != 0 && IsValidNode(m_NavMeshPtr, node);
}
+ ///
public readonly bool IsValid(NavLocation location)
{
return IsValid(location.node);
@@ -307,6 +325,7 @@ public readonly bool IsValid(NavLocation location)
[NativeMethod(IsThreadSafe = true)]
static extern int GetAgentTypeIdForNode(IntPtr navMeshPtr, NavNode node);
+ ///
public readonly int GetAgentTypeIdForNode(NavNode node)
{
CheckValidPtrAndThrow();
@@ -316,6 +335,7 @@ public readonly int GetAgentTypeIdForNode(NavNode node)
[NativeMethod(IsThreadSafe = true)]
static extern int GetAreaIndexForNode(IntPtr navMeshPtr, NavNode node);
+ ///
public readonly int GetAreaIndexForNode(NavNode node)
{
CheckValidPtrAndThrow();
@@ -326,6 +346,7 @@ public readonly int GetAreaIndexForNode(NavNode node)
static extern NavQueryStatus GetClosestPointOnPoly(IntPtr navMeshQuery, NavNode node, Vector3 position,
out Vector3 nearest);
+ ///
public readonly NavLocation CreateLocation(Vector3 position, NavNode node)
{
CheckValidPtrAndThrow();
@@ -339,6 +360,7 @@ public readonly NavLocation CreateLocation(Vector3 position, NavNode node)
static extern unsafe void MoveLocations(IntPtr navMeshQuery, void* locations, void* targets, void* areaMasks,
int count);
+ ///
public readonly unsafe void MoveLocations(NativeSlice locations, NativeSlice destinations,
NativeSlice areaMasks)
{
@@ -354,6 +376,7 @@ public readonly unsafe void MoveLocations(NativeSlice locations, Na
static extern unsafe void MoveLocationsInSameAreas(IntPtr navMeshQuery, void* locations, void* targets,
int count, int areaMask);
+ ///
public readonly unsafe void MoveLocations(NativeSlice locations,
NativeSlice destinations, int areaMask = NavMesh.AllAreas)
{
@@ -369,6 +392,7 @@ public readonly unsafe void MoveLocations(NativeSlice locations,
static extern NavLocation MoveLocation(IntPtr navMeshQuery, NavLocation location, Vector3 target,
int areaMask);
+ ///
public readonly NavLocation MoveLocation(NavLocation location, Vector3 destination, int areaMask = NavMesh.AllAreas)
{
CheckValidPtrAndThrow();
@@ -379,6 +403,7 @@ public readonly NavLocation MoveLocation(NavLocation location, Vector3 destinati
static extern bool GetPortalPoints(IntPtr navMeshQuery, NavNode node, NavNode neighbor,
out Vector3 left, out Vector3 right);
+ ///
public readonly bool GetPortalPoints(NavNode node, NavNode neighbor, out Vector3 left, out Vector3 right)
{
CheckValidPtrAndThrow();
@@ -389,6 +414,7 @@ public readonly bool GetPortalPoints(NavNode node, NavNode neighbor, out Vector3
static extern void GetInstanceTransform(IntPtr navMesh, NavNode node,
out Vector3 position, out Quaternion rotation);
+ ///
public readonly void GetInstanceTransform(NavNode node, out Vector3 position, out Quaternion rotation)
{
CheckValidPtrAndThrow();
@@ -400,6 +426,7 @@ public readonly void GetInstanceTransform(NavNode node, out Vector3 position, ou
[NativeName("DecodePolyIdType")]
static extern int GetNodeTypeInternal(NavNode node);
+ ///
public readonly NavNodeType GetNodeType(NavNode node)
{
CheckValidPtrAndThrow();
@@ -414,6 +441,7 @@ public readonly NavNodeType GetNodeType(NavNode node)
[NativeName("GetLinkPolyRef")]
static extern NavNode GetLinkNode(int linkInstance);
+ ///
public readonly NavNode GetLinkNode(NavMeshLinkInstance linkInstance)
{
CheckValidPtrAndThrow();
@@ -425,6 +453,7 @@ public readonly NavNode GetLinkNode(NavMeshLinkInstance linkInstance)
static extern unsafe NavQueryStatus Raycast(IntPtr navMeshQuery, NavLocation start, Vector3 targetPosition,
int areaMask, void* costs, out NavMeshHit hit, void* path, out int pathCount, int maxPath);
+ ///
public readonly unsafe NavQueryStatus Raycast(out NavMeshHit hit, NavLocation start, Vector3 targetPosition,
int areaMask = NavMesh.AllAreas, NativeArray costs = new())
{
@@ -444,6 +473,7 @@ public readonly unsafe NavQueryStatus Raycast(out NavMeshHit hit, NavLocation st
return status;
}
+ ///
public readonly unsafe NavQueryStatus Raycast(out NavMeshHit hit, NativeSlice path, out int pathCount,
NavLocation start, Vector3 targetPosition,
int areaMask = NavMesh.AllAreas, NativeArray costs = new())
@@ -472,6 +502,7 @@ static extern unsafe NavQueryStatus GetEdgesAndNeighbors(IntPtr navMeshPtr, NavN
void* vertices, void* neighbors, void* edgeIndices,
out int vertCount, out int neighborsCount);
+ ///
public readonly unsafe NavQueryStatus GetEdgesAndNeighbors(NavNode node,
NativeSlice edgeVertices, NativeSlice neighbors, NativeSlice edgeIndices,
out int verticesCount, out int neighborsCount)
@@ -501,6 +532,7 @@ public readonly unsafe NavQueryStatus GetEdgesAndNeighbors(NavNode node,
static extern unsafe int GetGeneratedLinkNodes(int navMeshDataInstance, void* nodes, int nodesLength,
int start, int size);
+ ///
public readonly unsafe int GetGeneratedLinkNodes(NavMeshDataInstance navMeshInstance,
NativeSlice linkNodes, int start = 0, int length = int.MaxValue)
{
@@ -515,6 +547,7 @@ public readonly unsafe int GetGeneratedLinkNodes(NavMeshDataInstance navMeshInst
[NativeName("GetGeneratedLinksCount")]
static extern int GetGeneratedLinksCountInternal(int navMeshDataInstanceId);
+ ///
public readonly int GetGeneratedLinksCount(NavMeshDataInstance navMeshInstance)
{
CheckValidPtrAndThrow();
diff --git a/Modules/AI/NavMesh/NavMesh.bindings.cs b/Modules/AI/NavMesh/NavMesh.bindings.cs
index d8f3828b70..95ff25ffa0 100644
--- a/Modules/AI/NavMesh/NavMesh.bindings.cs
+++ b/Modules/AI/NavMesh/NavMesh.bindings.cs
@@ -3,6 +3,7 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEngine.Scripting.APIUpdating;
@@ -10,7 +11,22 @@
namespace UnityEngine.AI
{
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
- // Result information for NavMesh queries.
+ ///Information about a position that is the result of a query ran on the NavMesh.
+ ///
+ /// The object represents a valid result if the distance and position properties have finite values. Otherwise, the object represents a result that could not be calculated from the input data provided to the query. Refer to the documentation of each query method for details about the situations that produce invalid results.
+ ///
+ ///**Note:** You can use float.isFinite() to determine whether a value is finite.
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
[MovedFrom("UnityEngine")]
public struct NavMeshHit
{
@@ -20,32 +36,60 @@ public struct NavMeshHit
int m_Mask;
int m_Hit;
- // Position of hit.
+ ///Position of hit.
+ ///It is a position that a **NavMesh Agent** can move to, if it has a agentTypeID value that matches the agentTypeID of the NavMesh at that position. The position lies inside a NavMesh polygon. When the NavMesh also contains HeightMesh data, the position aligns to the HeightMesh polygon that is closest on the vertical axis.
+ ///
+ ///If the position coordinates are not finite, the entire NavMeshHit object represents the result of an invalid query.
+ ///
+ ///
+ ///
public Vector3 position { get => m_Position; set => m_Position = value; }
- // Normal at the point of hit.
+ ///Normal of the polygon edge where the query terminates.
+ ///The vector points towards the inner side of the last NavMesh polygon that the query traverses.
+ ///
+ ///If the query terminates inside a polygon, and is therefore not blocked by an edge, the normal is .
+ ///
+ ///**Note:** None of the query methods returns the normal of the polygon itself.
public Vector3 normal { get => m_Normal; set => m_Normal = value; }
- // Distance to the point of hit.
+ ///Distance to the point of hit.
+ ///If the value is not finite, the entire NavMeshHit object represents the result of an invalid query.
public float distance { get => m_Distance; set => m_Distance = value; }
- // Mask specifying NavMesh area index at point of hit.
+ ///Bitmask that specifies the NavMesh area type at the point of hit.
+ ///The index at which the binary representation of the integer contains a bit turned on is the number of the area type.
+ ///
+ /// If the query proceeds uninterrupted to the target position, the mask represents the area type of the NavMesh polygon where the resulting lies.
+ ///
+ /// When the query terminates at the edge of a NavMesh polygon that is of a different type than the ones allowed by the input parameters, the mask represents the area type of the polygon that blocks the query.
+ ///
+ /// When the query terminates at an edge of the NavMesh the mask is 0, to signify that there is no polygon beyond that position.
public int mask { get => m_Mask; set => m_Mask = value; }
- // Flag set when hit.
+ ///Flag set when the query encounters a particular valid situation.
+ ///The queries set this flag differently. reports hit as true every time it returns a valid position on the NavMesh. The rest of the methods report hit as true when the edge of a NavMesh polygon blocks the query before it can reach the target position. In all other cases hit is false.
public bool hit { get => m_Hit != 0; set => m_Hit = value ? 1 : 0; }
}
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
- // Contains data describing a triangulation of the navmesh
+ ///Contains data describing a triangulation of a navmesh.
[UsedByNativeCode]
[MovedFrom("UnityEngine")]
public struct NavMeshTriangulation
{
+ ///Vertices for the navmesh triangulation.
+ ///Vertices are referenced by the indices.
public Vector3[] vertices;
+ ///Triangle indices for the navmesh triangulation.
+ ///Contains 3 integers for each triangle. These integers refer to the vertices array.
public int[] indices;
+ ///NavMesh area indices for the navmesh triangulation.
+ ///Contains one element for each triangle.
public int[] areas;
+ ///NavMeshLayer values for the navmesh triangulation.
+ ///Contains one element for each triangle.
[Obsolete("Use areas instead.")]
public int[] layers => areas;
}
@@ -53,14 +97,20 @@ public struct NavMeshTriangulation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stub class for NavMeshData passing
+ ///Contains and represents NavMesh data.
+ ///An object of this class can be used for creating instances of NavMeshes. See . The contained NavMesh can be built and updated using the build API. See and methods therein.
[NativeHeader("Modules/AI/NavMesh/NavMesh.bindings.h")]
public sealed class NavMeshData : Object
{
+ ///Constructs a new object for representing a NavMesh for the default agent type.
+ ///At construction this NavMesh is empty, i.e. there are no polygons. You can use this class to create, build and add a NavMesh at runtime.
public NavMeshData()
{
Internal_Create(this, 0);
}
+ ///Constructs a new object representing a NavMesh for the specified agent type.
+ ///The agent type ID to create a NavMesh for.
public NavMeshData(int agentTypeID)
{
Internal_Create(this, agentTypeID);
@@ -69,24 +119,41 @@ public NavMeshData(int agentTypeID)
[StaticAccessor("NavMeshDataBindings", StaticAccessorType.DoubleColon)]
static extern void Internal_Create([Writable] NavMeshData mono, int agentTypeID);
+ ///Returns the bounding volume of the input geometry used to build this NavMesh (RO).
+ ///If the NavMesh data has not been built, the bounds will have zero values.
public extern Bounds sourceBounds { get; }
+ ///Gets or sets the world space position of the NavMesh data.
+ ///The default value is zero - that is, the world space origin.
public extern Vector3 position { get; set; }
+ ///Gets or sets the orientation of the NavMesh data.
+ ///The default value is - that is, the NavMesh up axis is the same as the world space y-axis.
public extern Quaternion rotation { get; set; }
internal extern bool hasHeightMeshData { [NativeMethod("HasHeightMeshData")] get; }
internal extern NavMeshBuildSettings buildSettings { get; }
}
+ ///The instance is returned when adding NavMesh data.
+ ///A valid NavMesh data instance is available to the navigation system. This means you can calculate paths etc. using that instance. You also need the instance if you want to remove the NavMesh data at a later time.
+ ///
+ ///
+ ///
public struct NavMeshDataInstance
{
+ ///True if the NavMesh data is added to the navigation system - otherwise false (RO).
public bool valid => id != 0 && NavMesh.IsValidNavMeshDataHandle(id);
internal int id { get; set; }
+ ///Removes this instance from the NavMesh system.
+ ///An identical but convenient alternative to calling . If the instance is not valid, e.g. has been removed before, the call has no effect.
public void Remove()
{
NavMesh.RemoveNavMeshDataInternal(id);
}
+ ///Get or set the owning Object.
+ ///If the instance is invalid: setting the owner has no effect and getting it will return null.
+ ///
public Object owner
{
get => NavMesh.InternalGetOwner(id);
@@ -109,6 +176,8 @@ internal void FlagAsInSelectionHierarchy()
}
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
+ ///Used for runtime manipulation of links connecting polygons of the NavMesh.
+ ///A typical use case is to connect different navigation meshes. Use the method to instantiate a link with these properties in the navigation system. The NavMesh Link component creates its runtime data in this way.
public struct NavMeshLinkData
{
Vector3 m_StartPosition;
@@ -119,29 +188,59 @@ public struct NavMeshLinkData
int m_Area;
int m_AgentTypeID;
+ ///Start position of the link.
+ ///If the is positive, this position specifies the midpoint of the starting edge.
public Vector3 startPosition { get => m_StartPosition; set => m_StartPosition = value; }
+ ///End position of the link.
+ ///If the is positive, this position specifies the midpoint of the ending edge.
public Vector3 endPosition { get => m_EndPosition; set => m_EndPosition = value; }
+ ///If positive, overrides the pathfinder cost to traverse the link.
+ ///When searching for a path this cost multiplies the Euclidean distance between the link end points when scoring the link. If the value is negative, the default cost based on area type is used. The value must be >= 1.0.
public float costModifier { get => m_CostModifier; set => m_CostModifier = value; }
+ ///If true, the link can be traversed in both directions, otherwise only from start to end position.
public bool bidirectional { get => m_Bidirectional != 0; set => m_Bidirectional = value ? 1 : 0; }
+ ///If positive, the link will be rectangle aligned along the line from start to end.
+ ///This allows paths to enter the link at any location along the end sides. If not positive, the link endpoints will be represented as points.
public float width { get => m_Width; set => m_Width = value; }
+ ///Area type of the link.
+ ///Areas And Costs
public int area { get => m_Area; set => m_Area = value; }
+ ///Specifies which agent type this link is available for.
public int agentTypeID { get => m_AgentTypeID; set => m_AgentTypeID = value; }
}
+ ///Represents a link available for pathfinding.
+ ///You obtain a valid object when you call to create one specific link in the navigation system. Conversely, you need to pass it into to remove that instance of the link from the system. Use this object to check or modify the state of the link instance by calling the following methods: , , , , and .
+ ///
+ ///
+ ///
+ /// Empty objects created when you instantiate this struct do not represent any link that exists in the navigation system. The and methods return a value of false for objects created in this manner.
public partial struct NavMeshLinkInstance
{
internal int id { get; set; }
}
+ ///Specifies which agent type and areas to consider when searching the NavMesh.
+ ///This struct is used with the NavMesh query methods overloaded with the query filter argument.
+ ///
+ ///
+ ///
+ ///
public struct NavMeshQueryFilter
{
const int k_AreaCostElementCount = 32;
internal float[] costs { get; private set; }
+ ///A bitmask representing the traversable area types.
public int areaMask { get; set; }
+ ///The agent type ID, specifying which navigation meshes to consider for the query functions.
public int agentTypeID { get; set; }
+ ///Returns the area cost multiplier for the given area type for this filter.
+ ///The default value is 1.
+ ///Index to retrieve the cost for.
+ ///The cost multiplier for the supplied area index.
public float GetAreaCost(int areaIndex)
{
if (costs == null)
@@ -156,6 +255,10 @@ public float GetAreaCost(int areaIndex)
return costs[areaIndex];
}
+ ///Sets the pathfinding cost multiplier for this filter for a given area type.
+ ///Calling SetAreaCost the first time on a NavMeshQueryFilter object causes an internal allocation of the maximum 32 cost modifiers.
+ ///The area index to set the cost for.
+ ///The cost for the supplied area index.
public void SetAreaCost(int areaIndex, float cost)
{
if (costs == null)
@@ -168,15 +271,63 @@ public void SetAreaCost(int areaIndex, float cost)
}
}
+ ///Singleton class to access the baked NavMesh.
+ ///Use the NavMesh class to perform spatial queries such as pathfinding and walkability tests. This class also lets you set the pathfinding cost for specific area types, and tweak the global behavior of pathfinding and avoidance.
+ ///
+ ///Before you can use spatial queries, you must first bake the NavMesh to your scene.
+ ///
+ ///See also:
+ ///
+ ///• <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/CreateNavMesh.html">Create a NavMesh</a> – for more information on how to setup and bake NavMesh
+ ///• <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/AreasAndCosts.html">Areas and Costs</a> – to learn how to use different Area types.
+ ///• – to learn how to control and move NavMesh Agents.
+ ///• – to learn how to control NavMesh Obstacles using scripting.
+ ///• <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a> – to learn how to control Off-Mesh Links using scripting.
[NativeHeader("Modules/AI/NavMeshManager.h")]
[NativeHeader("Modules/AI/NavMesh/NavMesh.bindings.h")]
[StaticAccessor("NavMeshBindings", StaticAccessorType.DoubleColon)]
[MovedFrom("UnityEngine")]
- public static class NavMesh
+ public static partial class NavMesh
{
+ ///Area mask constant that includes all NavMesh areas.
+ ///
+ /// Use the mask in query functions, such as , to indicate that all NavMesh area types are accepted.
+ ///
+ /// See Areas and Costs to learn how to use different Area types.
+ ///
+ ///
+ ///
+ ///
public const int AllAreas = ~0;
+ ///Registers callback methods to be invoked before the NavMesh system updates.
+ ///This is useful for updating the NavMesh and links before the agents are simulated during the update cycle.
+ ///
public delegate void OnNavMeshPreUpdate();
+ ///Set a function to be called before the NavMesh is updated during the frame update execution.
+ ///This lets you set a delegate function to be called every frame, right before the NavMesh system gets updated.
+ ///
+ [AutoStaticsCleanupOnCodeReload] // holds user-registered pre-update callbacks
public static OnNavMeshPreUpdate onPreUpdate;
[RequiredByNativeCode]
@@ -192,10 +343,88 @@ static void Internal_CallPreUpdateListeners()
onPreUpdate();
}
- // Trace a ray between two points on the NavMesh.
+ ///Trace a line between two points on the NavMesh.
+ ///
+ /// The source and destination points are first mapped on the NavMesh, then a ray is traced from the source point towards the target. If the ray hits a NavMesh boundary, the function returns true and the hit data is filled. If the path from the source to target is unobstructed, the function returns false.
+ ///
+ ///If the raycast terminates on an outer edge, hit.mask is 0; otherwise it contains the area mask of the blocking polygon.
+ ///
+ ///This function can be used to check if an agent can walk unobstructed between two points on the NavMesh. For example if your character has an evasive dodge move which needs space, you can shoot a ray from the characters location to multiple directions to find a spot where the character can dodge to.
+ ///
+ ///The Raycast is different from physics ray cast because it works on “2.5D”, on the NavMesh. The difference to physics ray casts is that NavMesh ray casts can detect all kinds of navigation obstructions, such as holes in the ground, and it can also climb up slopes, if the area is navigable.
+ /// If you want to find the nearest point on the NavMesh, use physics ray cast to find a point in the world. For more information, refer to the Move an Agent to a Position Clicked by the Mouse example.
+ ///
+ ///The origin of the ray.
+ ///The end of the ray.
+ ///Holds the properties of the ray cast resulting location.
+ ///A bitfield mask specifying which NavMesh areas can be passed when tracing the ray.
+ ///True if the ray is terminated before reaching target position. Otherwise returns false.
+ ///
+ ///
+ ///
public static extern bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int areaMask);
- // Calculate a path between two points and store the resulting path.
+ ///Calculate a path between two points and store the resulting path.
+ ///Use this function to avoid gameplay delays by planning a path before it is needed. You can also use this function to check if a target position is reachable before moving the agent.
+ ///
+ ///This function is synchronous. It performs path finding immediately which can adversely affect the frame rate when processing very long paths. It is recommended to only perform a few path finds per frame when, for example, evaluating distances to cover points.
+ ///
+ ///Use the returned path to set the path for an agent with . For SetPath to work, the agent must be close to the starting point.
+ ///The initial position of the path requested.
+ ///The final position of the path requested.
+ ///A bitfield mask specifying which NavMesh areas can be passed when calculating a path.
+ ///The resulting path.
+ ///True if either a complete or partial path is found. False otherwise.
+ ///
+ /// 1.0f)
+ /// {
+ /// elapsed -= 1.0f;
+ /// NavMesh.CalculatePath(transform.position, target.position, NavMesh.AllAreas, path);
+ /// }
+ /// for (int i = 0; i < path.corners.Length - 1; i++)
+ /// Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.red);
+ /// }
+ ///}
+ ///]]>
+ ///
public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path)
{
path.ClearCorners();
@@ -204,46 +433,206 @@ public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition,
static extern bool CalculatePathInternal(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path);
- // Locate the closest NavMesh edge from a point on the NavMesh.
+ ///Locate the closest NavMesh edge from a point on the NavMesh.
+ ///The returned object contains the position
+ ///and details of the nearest point on the nearest edge of the
+ ///navmesh. This can be used to query how much extra space there is around the agent.
+ ///The origin of the distance query.
+ ///Holds the properties of the resulting location.
+ ///A bitfield mask specifying which NavMesh areas can be passed when finding the nearest edge.
+ ///True if the nearest edge is found.
+ ///
+ ///
+ ///
public static extern bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, int areaMask);
- // Sample the NavMesh closest to the point specified.
+ ///Finds the nearest point based on the NavMesh within a specified range.
+ ///The nearest point is found by projecting the input point onto nearby NavMesh instances along the vertical axis. This vertical axis has been chosen for each instance at the time of creation. If this step does not find a projected point within the specified distance, then sampling is extended to surrounding NavMesh positions.
+ ///
+ ///Finds the nearest point based on the distance to the query point. This function does not consider obstructions. For example, in a two-story structure, if the sourcePosition is set to a point on the ceiling on the first floor, the nearest point might be found on the second floor rather than the first floor. The ceiling is not considered as an obstruction.
+ ///
+ ///This function may reduce the frame rate if a large search radius is specified. To avoid frame rate issues, it is recommended that you specify a maxDistance of twice the agent height.
+ ///
+ ///If you are trying to find a random point on the NavMesh, you should use the recommended radius and perform the find multiple times instead of using a very large radius.
+ ///The origin of the sample query.
+ ///Holds the properties of the resulting location. The value of hit.normal is never computed. It is always (0,0,0).
+ ///Sample within this distance from sourcePosition.
+ ///A mask that specifies the NavMesh areas allowed when finding the nearest point.
+ ///True if the nearest point is found.
+ ///
+ ///
+ ///
public static extern bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask);
+ ///Sets the cost for traversing over geometry of the layer type on all agents.
+ ///This will replace any custom layer costs on all agents.
[Obsolete("Use SetAreaCost instead.")]
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("SetAreaCost")]
public static extern void SetLayerCost(int layer, float cost);
+ ///Gets the cost for traversing over geometry of the layer type on all agents.
[Obsolete("Use GetAreaCost instead.")]
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaCost")]
public static extern float GetLayerCost(int layer);
+ ///Returns the layer index for a named layer.
+ ///If the named layer does not exist returns -1.
[Obsolete("Use GetAreaFromName instead.")]
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaFromName")]
public static extern int GetNavMeshLayerFromName(string layerName);
+ ///Sets the cost for finding path over geometry of the area type on all agents.
+ ///
+ /// This will replace any custom area costs on all agents, and set the default cost for new agents that are created after calling the function. The cost must be larger than 1.0.
+ ///
+ ///Use to find the area index based on the name of the NavMesh area type.
+ ///
+ ///
+ ///Index of the area to set.
+ ///New cost.
+ ///
+ ///
+ ///
+ ///Areas and Costs
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("SetAreaCost")]
public static extern void SetAreaCost(int areaIndex, float cost);
+ ///Gets the cost for path finding over geometry of the area type.
+ ///The value applies to all agents unless the value has been customized per agent by calling .
+ ///
+ ///Use to find the area index based on the name of the area type.
+ ///Index of the area to get.
+ ///Areas and Costs
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaCost")]
public static extern float GetAreaCost(int areaIndex);
+ ///Returns the area index for a named NavMesh area type.
+ ///Name of the area to look up.
+ ///Index if the specified area name exists, or -1 if no area type has the specified name.
+ ///
+ ///
+ ///
+ ///Areas and Costs
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaFromName")]
public static extern int GetAreaFromName(string areaName);
+ ///Get all the NavMesh area names.
+ ///Names of all the NavMesh areas.
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaNames")]
public static extern string[] GetAreaNames();
+ ///Calculates a triangulation of all the NavMeshes that are present in the scene at the time of the call.
+ ///Calculates and returns a simple triangulation of all the NavMeshes that are currently active. The resulting object contains vertices, triangle indices and NavMesh area types. The triangles from each NavMesh instance are grouped together in the array. These triangle groups are further sorted in the array based on the agent types that their originating NavMeshes were built for.
+ ///
+ ///The triangulation captures the current shape of the NavMeshes, which can include temporary holes carved by NavMeshObstacles.
+ ///
+ ///
+ ///The returned mesh contains only the triangles used for pathfinding. It does not contain the detail that is used to place the agents on the walkable surface. This is noticeable on locations with curved surfaces.
+ ///Object that contains a list of vertices and a list of indices that describe the triangles of the active NavMeshes.
+ ///Areas and Costs
public static extern NavMeshTriangulation CalculateTriangulation();
- //*undocumented* DEPRECATED
+ ///
[Obsolete("use NavMesh.CalculateTriangulation() instead.")]
public static void Triangulate(out Vector3[] vertices, out int[] indices)
{
@@ -252,20 +641,38 @@ public static void Triangulate(out Vector3[] vertices, out int[] indices)
indices = results.indices;
}
+ ///
[Obsolete("AddOffMeshLinks has no effect and is deprecated.")]
public static void AddOffMeshLinks() {}
+ ///
[Obsolete("RestoreNavMesh has no effect and is deprecated.")]
public static void RestoreNavMesh() {}
+ ///Describes how far in the future the agents predict collisions for avoidance.
+ ///The larger the value, the earlier the agents will start to avoid each other if they are on collision course. The value is measured in seconds. Default value is 2.0, a good range for tuning is between 0.5 and 5.0.
[StaticAccessor("GetNavMeshManager()")]
public static extern float avoidancePredictionTime { get; set; }
+ ///The maximum number of nodes processed for each frame during the asynchronous pathfinding process.
+ ///During the pathfinding process, the pathfinder expands only a certain number of nodes (NavMesh polygons) for each frame. This allows for smoother gameplay when processing long paths or when processing a large number of requests concurrently. However, the path request might take many frames to process.
+ ///
+ ///The iteration count only affects asynchronous pathfinding. This method of pathfinding is used when the NavMesh Agent destination is set with or .
+ ///
+ ///Increasing this value causes faster path processing but it might also cause frame rate issues. The default value is 100. An ideal value is between 50 and 500.
[StaticAccessor("GetNavMeshManager()")]
public static extern int pathfindingIterationsPerFrame { get; set; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ ///Adds the specified NavMeshData to the game.
+ ///This makes the NavMesh data available for agents and NavMesh queries. Returns an instance for later removing the NavMesh data from the runtime.
+ ///
+ ///The instance returned will be valid unless the NavMesh data could not be added - e.g. due to running out of memory or navmesh data being loaded from a corrupted file.
+ ///Contains the data for the navmesh.
+ ///Representing the added navmesh.
+ ///
+ ///
public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData)
{
if (navMeshData == null) throw new ArgumentNullException(nameof(navMeshData));
@@ -275,6 +682,39 @@ public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData)
return handle;
}
+ ///Adds the specified NavMeshData to the game.
+ ///This function is similar to above, but the position and rotation specified is applied in addition to the position and rotation where the NavMesh data was baked.
+ ///Contains the data for the navmesh.
+ ///Translate the navmesh to this position.
+ ///Rotate the navmesh to this orientation.
+ ///Representing the added navmesh.
+ ///
+ ///
+ ///
public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData, Vector3 position, Quaternion rotation)
{
if (navMeshData == null) throw new ArgumentNullException(nameof(navMeshData));
@@ -284,6 +724,11 @@ public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData, Vector
return handle;
}
+ ///Removes the specified from the game, making it unavailable for agents and queries.
+ ///Use the instance returned by to remove the corresponding NavMesh data. If the instance is not valid, e.g. has been removed before, the call has no effect.
+ ///The instance of a NavMesh to remove.
+ ///
+ ///
public static void RemoveNavMeshData(NavMeshDataInstance handle)
{
RemoveNavMeshDataInternal(handle.id);
@@ -320,6 +765,16 @@ public static void RemoveNavMeshData(NavMeshDataInstance handle)
[NativeName("UnloadData")]
internal static extern void RemoveNavMeshDataInternal(int handle);
+ ///Adds a link to the NavMesh. The link is described by the NavMeshLinkData struct.
+ ///Returns an instance identifier for the added link.
+ ///
+ ///The returned instance is valid if the link was successfully added. The instance can be used to later remove the link using RemoveLink().
+ ///
+ ///**Note:** If the area is set to Not Walkable, or if adding a link would exceed the maximum number of active links (65535) the link will fail to be added – and the valid property will be false.
+ ///Object that describes the properties of the link.
+ ///Object that identifies the added link.
+ ///
+ ///
public static NavMeshLinkInstance AddLink(NavMeshLinkData link)
{
var handle = new NavMeshLinkInstance();
@@ -327,6 +782,16 @@ public static NavMeshLinkInstance AddLink(NavMeshLinkData link)
return handle;
}
+ ///Adds a link to the NavMesh. The link is described by the NavMeshLinkData struct.
+ ///Returns an instance identifier for the added link.
+ ///
+ ///This function is similar to AddLink above, but the position and rotation specified is applied to the start and end positions of the link. The rotation also specifies the local up-axis of the link.
+ ///Object that describes the properties of the link.
+ ///Translate the link to this position.
+ ///Rotate the link to this orientation.
+ ///Object that identifies the added link.
+ ///
+ ///
public static NavMeshLinkInstance AddLink(NavMeshLinkData link, Vector3 position, Quaternion rotation)
{
var handle = new NavMeshLinkInstance();
@@ -334,36 +799,92 @@ public static NavMeshLinkInstance AddLink(NavMeshLinkData link, Vector3 position
return handle;
}
+ ///Removes a link from the NavMesh.
+ ///Use the instance returned by to remove the corresponding link.
+ ///The instance of a link to remove.
+ ///
public static void RemoveLink(NavMeshLinkInstance handle)
{
RemoveLinkInternal(handle.id);
}
+ ///Determines whether the instance of the link can be used to calculate paths, and if NavMesh agents can move over it.
+ ///Use this method to determine if paths for the assigned agent type can traverse this link or not.
+ ///
+ ///A link instance is active by default regardless of whether the ends connect to NavMesh surfaces or not. To change the link's state, call . After you remove the link from the running navigation system this method always returns false.
+ ///
+ ///
+ ///
+ ///This method is available as of 2023.2.
+ ///The link instance whose state to query.
+ ///True if agents can plan paths through, and traverse, this instance of the link, otherwise false.
+ ///
public static bool IsLinkActive(NavMeshLinkInstance handle)
{
return IsOffMeshConnectionActive(handle.id);
}
+ ///Activates or deactivates the link instance. An active link instance can be traversed by agents and used to plan paths, but a deactivated link cannot.
+ ///This method changes the state of the link instance immediately. Any path that you calculate afterwards takes into account the new state of the link. When you disable the link instance any paths that have already been calculated through it get a status value of invalid.
+ ///
+ ///You can call this method at any time to deactivate the link and prevent agents from moving through a section of the game level, for example through a door that connects two rooms. Conversely, you can activate the link and allow the agents to move between the respective game level sections.
+ ///
+ ///Deactivated links remain connected to the NavMesh surfaces and they do not need to find the connection points again when they are reactivated.
+ ///
+ ///Any link instance created with the method is active by default.
+ ///
+ ///
+ ///
+ ///This method is available as of 2023.2.
+ ///The link instance whose active state to modify.
+ ///Whether agents can plan paths through, and traverse, the link. When the value is true, agents can plan paths through, and traverse, the link. Otherwise, no paths can use the link instance.
+ ///
public static void SetLinkActive(NavMeshLinkInstance handle, bool value)
{
SetOffMeshConnectionActive(handle.id, value);
}
+ ///Determines whether or not a NavMesh agent is currently using this link.
+ ///Use this method to determine if your NavMesh agent can move onto the specified NavMesh link instance. Only one NavMesh agent can traverse a NavMesh link instance at any one time, so your agent can't move onto a NavMesh link instance that is already occupied. A NavMesh link instance is occupied when any NavMesh agent moves onto the link as part of the path the agent has calculated to the destination. When the agent moves off of the link, either automatically or through a call to , the link instance is no longer occupied.
+ ///
+ ///This method is available as of 2023.2.
+ ///The link instance whose state to query.
+ ///True if an agent is currently traversing the link, otherwise false.
+ ///
public static bool IsLinkOccupied(NavMeshLinkInstance handle)
{
return IsOffMeshConnectionOccupied(handle.id);
}
+ ///Determines whether the link instance is part of the current data used for navigation.
+ ///The identifier of the link instance to check.
+ ///True if the NavMesh link is added to the navigation system - otherwise false.
public static bool IsLinkValid(NavMeshLinkInstance handle)
{
return IsValidLinkHandle(handle.id);
}
+ ///Gets the object, if any, that is associated with the link instance.
+ ///Use this method to obtain a reference to the component that created the link, or more generally, to any object that contains useful information about this specific link that is active in the navigation system. We refer to that object as the "owner". The owner is null for any new link instance created with . Therefore you need to first call in order to retrieve the same object later. This "owner" is also referenced by the property when you query for the next link on a NavMesh agent's path.
+ ///
+ ///When the link instance is removed the owner property returns null once again.
+ ///The identifier of the link instance whose owner needs to be retrieved.
+ ///The object that was passed into for the specified link instance.
+ ///
+ ///Returns null when no owner object has been assigned or when the link instance is not valid.
+ ///
public static Object GetLinkOwner(NavMeshLinkInstance handle)
{
return InternalGetLinkOwner(handle.id);
}
+ ///Associates an object with the instance of a link.
+ ///Call to retrieve a reference to the assigned object. The property obtained from the path of an agent also points to the object that has been assigned to the link.
+ ///
+ ///If the instance of the link is not valid, setting the owner has no effect and getting it returns null.
+ ///The identifier of the link instance for which you assign an owner.
+ ///An object that carries useful information in relation to the instance of the link.
+ ///
public static void SetLinkOwner(NavMeshLinkInstance handle, Object owner)
{
var ownerID = owner != null ? owner.GetEntityId() : EntityId.None;
@@ -388,6 +909,14 @@ public static void SetLinkOwner(NavMeshLinkInstance handle, Object owner)
[StaticAccessor("GetNavMeshManager()")]
internal static extern void SetOffMeshConnectionActive(int linkHandle, bool activated);
+ ///Samples the position nearest the sourcePosition on any NavMesh built for the agent type specified by the filter.
+ ///Consider only positions on areas defined in the .
+ ///A maximum search radius is set by maxDistance. The information of any found position is returned in the hit argument.
+ ///The origin of the sample query.
+ ///Holds the properties of the resulting location. The value of hit.normal is never computed. It is always (0,0,0).
+ ///Sample within this distance from sourcePosition.
+ ///A filter specifying which NavMesh areas are allowed when finding the nearest point.
+ ///True if the nearest point is found.
public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, NavMeshQueryFilter filter)
{
return SamplePositionFilter(sourcePosition, out hit, maxDistance, filter.agentTypeID, filter.areaMask);
@@ -396,6 +925,12 @@ public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, fl
// a CUSTOM "SamplePosition" exists elsewhere. We need to pick unique name here to compile generated code in batch-builds
static extern bool SamplePositionFilter(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int type, int mask);
+ ///Locate the closest NavMesh edge from a point on the NavMesh, subject to the constraints of the filter argument.
+ ///The returned NavMeshHit object contains the position and details of the nearest point on the nearest edge of the NavMesh. This can be used to query how much extra space there is around the agent.
+ ///The origin of the distance query.
+ ///Holds the properties of the resulting location.
+ ///A filter specifying which NavMesh areas can be passed when finding the nearest edge.
+ ///True if the nearest edge is found.
public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, NavMeshQueryFilter filter)
{
return FindClosestEdgeFilter(sourcePosition, out hit, filter.agentTypeID, filter.areaMask);
@@ -404,6 +939,13 @@ public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, N
// a CUSTOM "FindClosestEdge" exists elsewhere. We need to pick unique name here to compile generated code in batch-builds
static extern bool FindClosestEdgeFilter(Vector3 sourcePosition, out NavMeshHit hit, int type, int mask);
+ ///Traces a line between two positions on the NavMesh, subject to the constraints defined by the filter argument.
+ ///The line is terminated on outer edges or a non-passable area.
+ ///The origin of the ray.
+ ///The end of the ray.
+ ///Holds the properties of the ray cast resulting location.
+ ///A filter specifying which NavMesh areas can be passed when tracing the ray.
+ ///True if the ray is terminated before reaching target position. Otherwise returns false.
public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, NavMeshQueryFilter filter)
{
return RaycastFilter(sourcePosition, targetPosition, out hit, filter.agentTypeID, filter.areaMask);
@@ -412,6 +954,12 @@ public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out N
// a CUSTOM "Raycast" exists elsewhere. We need to pick unique name here to compile generated code in batch-builds
static extern bool RaycastFilter(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int type, int mask);
+ ///Calculates a path between two positions mapped to the NavMesh, subject to the constraints and costs defined by the filter argument.
+ ///The initial position of the path requested.
+ ///The final position of the path requested.
+ ///A filter specifying the cost of NavMesh areas that can be passed when calculating a path.
+ ///The resulting path.
+ ///True if a either a complete or partial path is found and false otherwise.
public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, NavMeshQueryFilter filter, NavMeshPath path)
{
path.ClearCorners();
@@ -420,24 +968,59 @@ public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition,
static extern bool CalculatePathFilterInternal(Vector3 sourcePosition, Vector3 targetPosition, NavMeshPath path, int type, int mask, float[] costs);
+ ///Creates and returns a new entry of NavMesh build settings available for runtime NavMesh building.
+ ///This is useful for creating and storing settings to use for building NavMeshes for different sized characters.
+ ///
+ ///
+ ///
+ ///The will be positive and unique for the created settings.
+ ///The created settings.
+ ///
[StaticAccessor("GetNavMeshProjectSettings()")]
public static extern NavMeshBuildSettings CreateSettings();
//[StaticAccessor("GetNavMeshProjectSettings()")]
//public static extern void UpdateSettings(NavMeshBuildSettings buildSettings);
+ ///Removes the build settings matching the agent type ID.
+ ///If no matching settings are found or the agentTypeID is the default value 0, nothing is removed.
+ ///The ID of the entry to remove.
[StaticAccessor("GetNavMeshProjectSettings()")]
public static extern void RemoveSettings(int agentTypeID);
+ ///Returns an existing entry of NavMesh build settings.
+ ///If no previously-created settings match the provided agent type ID, the returned struct will have the agentTypeID set to -1. See also: .
+ ///
+ ///**Note:** A default entry will always exist for the agentTypeID being 0.
+ ///The ID to look for.
+ ///The settings found.
public static extern NavMeshBuildSettings GetSettingsByID(int agentTypeID);
+ ///Returns the number of registered NavMesh build settings.
+ ///This will always be at least one available, namely the default setting.
+ ///The number of registered entries.
+ ///
[StaticAccessor("GetNavMeshProjectSettings()")]
public static extern int GetSettingsCount();
+ ///Returns an existing entry of NavMesh build settings by its ordered index.
+ ///If the index is outside the valid range (0, GetSettingsCount-1), the returned NavMeshBuildSettings struct will have the agentTypeID set to -1.
+ ///The index to retrieve from.
+ ///The found settings.
+ ///
+ ///
public static extern NavMeshBuildSettings GetSettingsByIndex(int index);
+ ///Returns the name associated with the NavMesh build settings matching the provided agent type ID.
+ ///If no settings are found, the result is an empty string.
+ ///The ID to look for.
+ ///The name associated with the ID found.
public static extern string GetSettingsNameFromID(int agentTypeID);
+ ///Removes all NavMesh surfaces and links from the game.
+ ///Unloads all surfaces and links that have been loaded from the Scene or added with or and frees all the internal resources associated with the NavMesh.
+ ///
+ ///
[StaticAccessor("GetNavMeshManager()")]
[NativeName("CleanupAfterCarving")]
public static extern void RemoveAllNavMeshData();
diff --git a/Modules/AI/NavMesh/NavMesh.deprecated.cs b/Modules/AI/NavMesh/NavMesh.deprecated.cs
index f72a3fe649..5c0642de85 100644
--- a/Modules/AI/NavMesh/NavMesh.deprecated.cs
+++ b/Modules/AI/NavMesh/NavMesh.deprecated.cs
@@ -8,15 +8,30 @@ namespace UnityEngine.AI;
public partial struct NavMeshLinkInstance
{
+ ///True if the NavMesh link is added to the navigation system - otherwise false (RO).
+ ///
[Obsolete("valid has been deprecated. Use NavMesh.IsLinkValid() instead.")]
public bool valid => NavMesh.IsValidLinkHandle(id);
+ ///Removes this instance from the game.
+ ///This method is an identical but convenient alternative to . If the instance is not valid, e.g. has already been removed, the call has no effect.
+ ///
+ ///
[Obsolete("Remove() has been deprecated. Use NavMesh.RemoveLink() instead.")]
public void Remove()
{
NavMesh.RemoveLinkInternal(id);
}
+ ///Get or set the owning .
+ ///If the instance is not valid, setting the owner has no effect and getting it returns null.
+ ///
+ ///Use this property to reference the component that created the link, or more generally, any object that contains useful information about this specific link active in the navigation system. The owner is null for any new link instance created with . You can, at any time, assign any Object to this property and retrieve that reference later.
+ ///
+ ///When the link instance is removed the owner property returns null once again.
+ ///
+ ///
+ ///
[Obsolete("owner has been deprecated. Use NavMesh.GetLinkOwner() and NavMesh.SetLinkOwner() instead.")]
public Object owner
{
diff --git a/Modules/AI/NavMeshExperimental.bindings.cs b/Modules/AI/NavMeshExperimental.bindings.cs
index cdf403758a..fe3a4ab34b 100644
--- a/Modules/AI/NavMeshExperimental.bindings.cs
+++ b/Modules/AI/NavMeshExperimental.bindings.cs
@@ -13,18 +13,32 @@
namespace UnityEngine.Experimental.AI
{
+ ///Represents a compact identifier for the data of a NavMesh node.
+ ///It is used in operations for pinpointing and getting access to relevant nodes in the NavMesh. Each node can be used by only one type of agent.
+ ///
+ ///This identifier becomes invalid once the node gets removed from the NavMesh, either by completely removing the surface or by modifying the surface in the node's immediate vicinity.
+ ///
+ ///
[Obsolete("The experimental PolygonId struct has been deprecated. Use NavNode instead.")]
public struct PolygonId : IEquatable
{
internal ulong polyRef;
+ ///Returns true if the has been created empty and has never pointed to any node in the NavMesh.
public bool IsNull() { return polyRef == 0; }
+ ///Returns true if two objects refer to the same NavMesh node or if they are both null.
+ ///
public static bool operator==(PolygonId x, PolygonId y) { return x.polyRef == y.polyRef; }
+ ///Returns true if two objects refer to different NavMesh nodes or if only one of them is null.
+ ///
public static bool operator!=(PolygonId x, PolygonId y) { return x.polyRef != y.polyRef; }
+ ///Returns the hash code for use in collections.
public override int GetHashCode() { return polyRef.GetHashCode(); }
+ ///Returns true if two objects refer to the same NavMesh node.
public bool Equals(PolygonId rhs) { return rhs == this; }
+ ///Returns true if two objects refer to the same NavMesh node.
public override bool Equals(object obj)
{
if (obj == null || !(obj is PolygonId))
@@ -34,10 +48,24 @@ public override bool Equals(object obj)
}
}
+ ///A world position that is guaranteed to be on the surface of the NavMesh.
+ ///The NavMeshLocation stores the position on the NavMesh surface together with the of the NavMesh node containing that position. Using NavMeshLocations with operations remove the need to project the desired world position onto the NavMesh at the beginning of each and every operation.
+ ///
+ ///A NavMeshLocation can be invalid in two situations:
+ ///1. When it has been created empty, instead of being the result of a operation.
+ ///2. When the NavMesh has been removed or modified at the indicated position or in its close vicinity.
+ ///
+ ///If a NavMeshLocation is made invalid by a carving the NavMesh in its vicinity the NavMeshLocation returns to a valid state if the is removed. This is because removing a restores the NavMesh to its original form without regenerating it.
+ ///
+ ///
+ ///
[Obsolete("The experimental NavMeshLocation struct has been deprecated. Use NavLocation instead.")]
public struct NavMeshLocation
{
+ ///Unique identifier for the node in the NavMesh to which the world position has been mapped.
+ ///
public PolygonId polygon { get; }
+ ///A world position that sits precisely on the surface of the NavMesh or along its links.
public Vector3 position { get; }
internal NavMeshLocation(Vector3 position, PolygonId polygon)
@@ -73,34 +101,72 @@ internal NavMeshLocation(Vector3 position, PolygonId polygon)
//}
// Keep in sync with the values in NavMeshTypes.h
+ ///Bit flags representing the resulting state of operations.
+ ///The main values are Success, Failure and InProgress. A status will usually have only one of these main flags set. The secondary flags (details) are set when specific issues have been encountered during the operation. StatusDetailMask is a bit mask that can be used to filter out these secondary flags.
+ ///
+ ///**Note:** Issues highlighted by the presence of certain detail flags in certain situations might refer to internal structures outside the control of users, thus they will not always be able to mitigate them by taking the necessary actions in their code. Ways for handling these situations will be made available in the future.
[Obsolete("The experimental PathQueryStatus enum has been deprecated. Use NavQueryStatus instead.")]
[Flags]
public enum PathQueryStatus
{
// High level status.
+ ///The operation has failed.
+ ///Check the status for secondary flags that might provide more details about the issue causing the failure.
Failure = 1 << 31,
+ ///The operation was successful.
Success = 1 << 30,
+ ///The operation is in progress.
InProgress = 1 << 29,
// Detail information for status.
+ ///Bitmask that has 0 set for the Success, Failure and InProgress bits and 1 set for all the other flags.
+ ///It can be used to separate the detail flags from the main status flags.
StatusDetailMask = 0x0ffffff,
- WrongMagic = 1 << 0, // Input data is not recognized.
- WrongVersion = 1 << 1, // Input data is in wrong version.
- OutOfMemory = 1 << 2, // Operation ran out of memory.
- InvalidParam = 1 << 3, // An input parameter was invalid.
- BufferTooSmall = 1 << 4, // Result buffer for the query was too small to store all results.
- OutOfNodes = 1 << 5, // Query ran out of nodes during search.
- PartialResult = 1 << 6 // Query did not reach the end location, returning best guess.
+ ///Data in the NavMesh cannot be recognized and used.
+ WrongMagic = 1 << 0,
+ ///Data in the NavMesh world has a wrong version.
+ WrongVersion = 1 << 1,
+ ///Operation ran out of memory.
+ ///**Known issue, will be fixed:** This flag is not currently reported when memory fails to be allocated because the is created with a pathNodePoolSize value too large. The NavMeshQuery will then be silently defective and might produce a crash.
+ OutOfMemory = 1 << 2,
+ ///A parameter did not contain valid information, useful for carring out the NavMesh query.
+ InvalidParam = 1 << 3,
+ ///The node buffer of the query was too small to store all results.
+ ///Creating a different with a larger pathNodePoolSize parameter might solve the issue.
+ BufferTooSmall = 1 << 4,
+ ///Query ran out of node stack space during a search.
+ ///This happens when the query has visited more nodes than there is room in the . To fix this issue try a larger value for the pathNodePoolSize parameter when creating the .
+ OutOfNodes = 1 << 5,
+ ///Query did not reach the end location, returning best guess.
+ PartialResult = 1 << 6
}
// Flags describing polygon properties. Keep in sync with the enum declared in NavMesh.h
+ ///The types of nodes in the navigation data.
+ ///Navigation data is comprised geometrically of polygons and segments connected together.
+ ///
+ ///NavMeshSurface
+ ///NavMeshLink
+ ///Off-mesh Link
[Obsolete("The experimental NavMeshPolyTypes enum has been deprecated. Use NavNodeType instead.")]
public enum NavMeshPolyTypes
{
- Ground = 0, // Regular ground polygons.
- OffMeshConnection = 1 // Off-mesh connections.
+ ///Type of node in the NavMesh representing one surface polygon.
+ ///NavMeshSurface
+ Ground = 0,
+ ///Type of node in the NavMesh representing a point-to-point connection between two positions on the NavMesh surface.
+ ///NavMeshLink
+ ///Off-mesh Link
+ OffMeshConnection = 1
}
+ ///Assembles together a collection of NavMesh surfaces and links that are used as a whole for performing navigation operations.
+ ///Operations are initialized against one world, can use only the NavMeshes inside that world and are not aware of the existence of any other NavMeshWorld.
+ ///
+ ///Copying this object only produces a new reference to the same NavMesh data, it does not duplicate the data in memory.
+ ///
+ ///**Important note:** Currently only a single NavMesh world can be used and a reference to it can be obtained through the method. In the future, multiple NavMesh worlds will be able to be created and any two of them will be completely isolated from each other.
+ ///
[Obsolete("The experimental NavMeshWorld struct has been deprecated. Use NavWorld instead.")]
[StaticAccessor("NavMeshWorldBindingsExperimental", StaticAccessorType.DoubleColon)]
[NativeHeader("Modules/AI/NavMeshExperimental.bindings.h")]
@@ -109,12 +175,16 @@ public struct NavMeshWorld
{
internal IntPtr world;
+ ///Returns true if the NavMeshWorld has been properly initialized.
+ ///Currently the only way to obtain the single possible valid NavMesh world is through a call to .
public bool IsValid()
{
return world != IntPtr.Zero;
}
static extern NavMeshWorld GetDefaultWorldExp();
+ ///Returns a reference to the single that can currently exist and be used in Unity.
+ ///The returned world comprises of all the NavMeshes and connections that are also used through the -related structures.
public static NavMeshWorld GetDefaultWorld()
{
return GetDefaultWorldExp();
@@ -122,6 +192,11 @@ public static NavMeshWorld GetDefaultWorld()
static extern void AddDependencyInternalExp(IntPtr navmesh, JobHandle handle);
+ ///Tells the NavMesh world to halt any changes until the specified job is completed.
+ ///When jobs process operations, it is essential that the NavMesh data does not change. Thus, every time a job of that type is scheduled its must be passed to the NavMeshWorld using this method. Otherwise, an exception will be thrown when the project is running in the Editor.
+ ///The job that needs to be completed before the NavMesh world can be modified in any way.
+ ///
+ ///
public void AddDependency(JobHandle job)
{
if (!IsValid())
@@ -130,6 +205,14 @@ public void AddDependency(JobHandle job)
}
}
+ ///Object used for doing navigation operations in a .
+ ///NavMeshQuery operations can be executed inside jobs (, ), as opposed to the operations in the -related structures.
+ ///
+ ///To obtain a path between two locations on the NavMesh, you must create a NavMeshQuery with a pathNodePoolSize value in the range from 1 to 65,535. After creating a NavMeshQuery, you must call the following methods in this order: BeginFindPath, UpdateFindPath (can be repeated), EndFindPath, GetPathResult. These methods store state data within the NavMeshQuery. Other methods can be called in any order since they do not change state data.
+ ///
+ ///All methods throw exceptions if any of their parameters are not valid when executed in the Editor.
+ ///
+ ///**Note:** The intended feature set for NavMeshQuery is not yet fully complete.
[Obsolete("The experimental NavMeshQuery struct has been deprecated. Use NavWorld instead.")]
[NativeContainer]
[StructLayout(LayoutKind.Sequential)]
@@ -137,7 +220,7 @@ public void AddDependency(JobHandle job)
[NativeHeader("Modules/AI/Public/NavMeshBindingTypes.h")]
[NativeHeader("Runtime/Math/Matrix4x4.h")]
[StaticAccessor("NavMeshQueryBindingsExperimental", StaticAccessorType.DoubleColon)]
- [NativeType(CodegenOptions.Auto, "NavMeshQueryExp")]
+ [NativeType(CodegenOptions.Auto, "NavMeshQueryExp")]
public struct NavMeshQuery : IDisposable
{
[NativeDisableUnsafePtrRestriction]
@@ -152,6 +235,11 @@ public struct NavMeshQuery : IDisposable
// Keep in sync with kMaxNavMeshNodePoolSize = USHRT_MAX from NavMeshNode.h
const int k_MaxNavMeshNodePoolSize = ushort.MaxValue;
+ ///Creates the object and allocates memory to store NavMesh node information, if required.
+ ///You must specify a pathNodePoolSize greater than 0 to use the NavMeshQuery object for pathfinding methods (BeginFindPath, UpdateFindPath, EndFindPath, GetPathResult ). If the node pool size for the NavMeshQuery object is too small, the pathfinding method returns a status. The range of pathNodePoolSize is 0 through 65,535.
+ ///NavMeshWorld object used as an entry point to the collection of NavMesh objects. This object that can be used by query operations.
+ ///Label indicating the desired life time of the object. (**Known issue:** Currently allocator has no effect).
+ ///The number of nodes temporarily stored in the query during search operations. The maximum number of nodes is 65,535. By default, if unspecified, the number of nodes is set to 0.
public NavMeshQuery(NavMeshWorld world, Allocator allocator, int pathNodePoolSize = 0)
{
if (!world.IsValid())
@@ -168,6 +256,7 @@ public NavMeshQuery(NavMeshWorld world, Allocator allocator, int pathNodePoolSiz
AddQuerySafetyExp(m_NavMeshQuery, m_Safety);
}
+ ///Destroys the NavMeshQuery and deallocates all memory used by it.
public void Dispose()
{
@@ -196,6 +285,23 @@ public void Dispose()
[NativeMethod(IsThreadSafe = true)]
static extern bool HasNodePoolExp(IntPtr navMeshQuery);
+ ///Initiates a pathfinding operation between two locations on the NavMesh.
+ ///The path always begins at the specified location. If the desired end location is not directly accessible, the search algorithm tries to find a valid location nearby.
+ ///
+ ///Calling this method overrides the progress made by this in the previous pathfinding operation.
+ ///
+ /// should be called after this method to process the path search.
+ ///Array of custom cost values for all of the 32 possible area types. Each value must be at least 1.0f. This parameter is optional and defaults to the area costs configured in the project settings.
+ ///Bitmask with values of 1 set at the indices for areas that can be traversed, and values of 0 for areas that are not traversable. This parameter is optional and defaults to , if omitted.
+ ///The start location on the NavMesh for the path.
+ ///The location on the NavMesh where the path ends.
+ ///
+ /// InProgress if the operation was successful and the query is ready to search for a path.
+ ///
+ ///Failure if the query's NavMeshWorld or any of the received parameters are no longer valid.
+ ///
+ ///
+ ///Areas and Costs
public unsafe PathQueryStatus BeginFindPath(NavMeshLocation start, NavMeshLocation end,
int areaMask = NavMesh.AllAreas, NativeArray costs = new NativeArray())
{
@@ -237,6 +343,21 @@ public unsafe PathQueryStatus BeginFindPath(NavMeshLocation start, NavMeshLocati
return BeginFindPathExp(m_NavMeshQuery, start, end, areaMask, costsPtr);
}
+ ///Continues a path search that is in progress.
+ ///The operation needs to have been initialized previously with and it will run until the entire route is found or the specified number of iterations have been executed.
+ ///
+ ///As long as the previous call returned a state of InProgress this method can be called repeatedly, across different frames, until the operation is successful. Use afterwards to prepare the path data for retrieval, along with the number of contained nodes.
+ ///Maximum number of nodes to be traversed by the search algorithm during this call.
+ ///Outputs the actual number of nodes that have been traversed during this call.
+ ///
+ /// InProgress if the search needs to continue further by calling UpdateFindPath again.
+ ///
+ ///Success if the search is completed and a path has been found or not.
+ ///
+ ///Failure if the search for the desired position could not be completed because the NavMesh has changed significantly since the search was initiated.
+ ///
+ ///Additionally the returned value can contain the OutOfNodes flag when the pathNodePoolSize parameter for the NavMeshQuery initialization was not large enough to accommodate the search space.
+ ///
public PathQueryStatus UpdateFindPath(int iterations, out int iterationsPerformed)
{
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
@@ -246,6 +367,18 @@ public PathQueryStatus UpdateFindPath(int iterations, out int iterationsPerforme
return UpdateFindPathExp(m_NavMeshQuery, iterations, out iterationsPerformed);
}
+ ///Obtains the number of nodes in the path that has been computed during a successful operation.
+ ///This method prepares the path data so that can be used afterward to retrieve the actual array of values that make up the path.
+ ///
+ ///**Important:** This method should only be called once at the end of the pathfinding operation. Calling it multiple times may ruin the stored path.
+ ///A reference to an int which will be set to the number of NavMesh nodes in the found path.
+ ///
+ /// Success when the number of nodes in the path was retrieved correctly.
+ ///
+ ///PartialPath when a path was found but it falls short of the desired end location.
+ ///
+ ///Failure when the path size can not be evaluated because the preceding call to UpdateFindPath was not successful.
+ ///
public PathQueryStatus EndFindPath(out int pathSize)
{
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
@@ -255,6 +388,16 @@ public PathQueryStatus EndFindPath(out int pathSize)
return EndFindPathExp(m_NavMeshQuery, out pathSize);
}
+ ///Copies into the provided array the list of NavMesh nodes that form the path found by the NavMeshQuery operation.
+ ///Must be called at the end of a successful - - sequence in order to obtain the resulting path.
+ ///
+ ///Can be called multiple times as long as has not been called for that same query.
+ ///
+ ///If the resulting path, stored in the query, is longer than the length of the provided array, the nodes are still copied (from the beginning of the path up to the array's length).
+ ///
+ ///**Important:** If the start NavMesh node of the path has been removed by a NavMesh modification since the initial BeginFindPath call of the pathfinding operation, the returned path will be empty.
+ ///Data array to be filled with the sequence of NavMesh nodes that comprises the found path.
+ ///Number of path nodes successfully copied into the provided array.
public unsafe int GetPathResult(NativeSlice path)
{
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
@@ -285,12 +428,17 @@ public unsafe int GetPathResult(NativeSlice path)
[NativeMethod(IsThreadSafe = true)]
static extern bool IsValidPolygonExp(IntPtr navMeshQuery, PolygonId polygon);
+ ///Returns true if the node referenced by the specified is active in the NavMesh.
+ ///You can make NavMesh nodes invalid when you remove the NavMesh surface or the links they belong to, or when you modify the NavMesh in their region, replacing them. You can remove the NavMesh surface and links with calls to , . To modify the NavMesh, call or use a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/NavMeshObstacle.html">NavMeshObstacle</a> to carve it.
+ ///Identifier of the NavMesh node to be checked.
public bool IsValid(PolygonId polygon)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
return polygon.polyRef != 0 && IsValidPolygonExp(m_NavMeshQuery, polygon);
}
+ ///Returns true if the node referenced by the contained in the is active in the NavMesh.
+ ///Location on the NavMesh to be checked. Same as checking location.polygon directly.
public bool IsValid(NavMeshLocation location)
{
return IsValid(location.polygon);
@@ -298,6 +446,10 @@ public bool IsValid(NavMeshLocation location)
[NativeMethod(IsThreadSafe = true)]
static extern int GetAgentTypeIdForPolygonExp(IntPtr navMeshQuery, PolygonId polygon);
+ ///Returns the identifier of the agent type the NavMesh was baked for or for which the link has been configured.
+ ///When NavMesh surfaces are baked or links are configured the **Agent Type** allowed to use them needs to be specified. Each **Agent Type** is identified by a unique integer. Operations such as , , , , and all require an agent type to be specified to distinguish between NavMeshes built for different agent configurations.
+ ///Identifier of a node from a NavMesh surface or link.
+ ///Agent type identifier.
public int GetAgentTypeIdForPolygon(PolygonId polygon)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -310,6 +462,13 @@ public int GetAgentTypeIdForPolygon(PolygonId polygon)
[NativeMethod(IsThreadSafe = true)]
static extern PathQueryStatus GetClosestPointOnPolyExp(IntPtr navMeshQuery, PolygonId polygon, Vector3 position, out Vector3 nearest);
+ ///Returns a valid for a position and a polygon provided by the user.
+ ///The returned position will be the point on the surface of the required NavMesh polygon that is closest to the specified position.
+ ///
+ ///Other methods for obtaining reliable positions on the NavMesh are: , and .
+ ///World position of the to be created.
+ ///Valid identifier for the NavMesh node.
+ ///Object containing the desired position and NavMesh node.
public NavMeshLocation CreateLocation(Vector3 position, PolygonId polygon)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -320,6 +479,20 @@ public NavMeshLocation CreateLocation(Vector3 position, PolygonId polygon)
[NativeMethod(IsThreadSafe = true)]
static extern NavMeshLocation MapLocationExp(IntPtr navMeshQuery, Vector3 position, Vector3 extents, int agentTypeID, int areaMask = NavMesh.AllAreas);
+ ///Finds the closest point and on the NavMesh for a given world position.
+ ///The search only applies to the specified type of NavMesh surface, for one or more desired area types and is limited to within the specified search area. It does not search for positions on <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLinks</a> or OffMeshLinks.
+ ///
+ ///Nearby NavMesh surfaces directly above or below the specified position are preferred. When there are none up or down within the specified search extents the surfaces closest sideways are sampled.
+ ///World position for which the closest point on the NavMesh needs to be found.
+ ///Maximum distance, from the specified position, expanding along all three axes, within which NavMesh surfaces are searched.
+ ///Identifier for the agent type whose NavMesh surfaces should be selected for this operation. The Humanoid agent type exists for all NavMeshes and has an ID of 0. Other agent types can be defined manually through the Editor. A separate NavMesh surface needs to be baked for each agent type.
+ ///Bitmask used to represent areas of the NavMesh that should (value of 1) or shouldn't (values of 0) be sampled. This parameter is optional and defaults to if unspecified.
+ ///An object with position and valid - when a point on the NavMesh has been found.
+ ///
+ ///An invalid object - when no NavMesh surface with the desired features has been found within the search area.
+ ///
+ ///
+ ///Areas and Costs
public NavMeshLocation MapLocation(Vector3 position, Vector3 extents, int agentTypeID, int areaMask = NavMesh.AllAreas)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -328,6 +501,15 @@ public NavMeshLocation MapLocation(Vector3 position, Vector3 extents, int agentT
[NativeMethod(IsThreadSafe = true)]
static extern unsafe void MoveLocationsExp(IntPtr navMeshQuery, void* locations, void* targets, void* areaMasks, int count);
+ ///Translates a series of NavMesh locations to other positions without losing contact with the surface.
+ ///Does the exact same thing as only it acts sequentially on a batch of locations, given their respective targets and area filters. All three array parameters must have the same length.
+ ///
+ ///The results are returned in-place in the locations array.
+ ///Array of positions to be moved across the NavMesh surface. At the end of the method call this array contains the resulting locations.
+ ///World positions to be used as movement targets by the agent.
+ ///Filters for the areas which can be traversed during the movement to each of the locations.
+ ///
+ ///
public unsafe void MoveLocations(NativeSlice locations, NativeSlice targets, NativeSlice areaMasks)
{
if (locations.Length != targets.Length || locations.Length != areaMasks.Length)
@@ -339,6 +521,13 @@ public unsafe void MoveLocations(NativeSlice locations, NativeS
[NativeMethod(IsThreadSafe = true)]
static extern unsafe void MoveLocationsInSameAreasExp(IntPtr navMeshQuery, void* locations, void* targets, int count, int areaMask);
+ ///Translates a series of NavMesh locations to other positions without losing contact with the surface, given one common area filter for all of them.
+ ///Does the exact same thing as only it applies the same area filter to all the movements.
+ ///Array of positions to be moved across the NavMesh surface. At the end of the method call this array contains the resulting locations.
+ ///World positions you want the agent to reach when moving to each of the locations.
+ ///Filters for the areas which can be traversed during the movement to each of the locations.
+ ///
+ ///
public unsafe void MoveLocationsInSameAreas(NativeSlice locations, NativeSlice targets, int areaMask = NavMesh.AllAreas)
{
if (locations.Length != targets.Length)
@@ -350,6 +539,21 @@ public unsafe void MoveLocationsInSameAreas(NativeSlice locatio
[NativeMethod(IsThreadSafe = true)]
static extern NavMeshLocation MoveLocationExp(IntPtr navMeshQuery, NavMeshLocation location, Vector3 target, int areaMask);
+ ///Translates a NavMesh location to another position without losing contact with the surface.
+ ///Returns the location on the NavMesh that is closest to the target position and that also has a continuous connection on the NavMesh surface through the allowed area types all the way to the start position specified by the location parameter. If the target position is outside the edges of the surface or of its allowed areas, a position at the edge is returned.
+ ///
+ ///The movement does not cross <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLinks</a> or OffMeshLinks.
+ ///
+ ///The result might not be accurate (the closest) if the pathNodePoolSize value in the NavMeshQuery initialization was not large enough to accommodate all the nodes that needed to be traversed in order to find a connection between location.position and target.
+ ///Position to be moved across the NavMesh surface.
+ ///World position you require the agent to move to.
+ ///Bitmask with values of 1 set at the indices corresponding to areas that can be traversed, and with values of 0 for areas that should not be traversed. This parameter can be omitted, in which case it defaults to .
+ ///A new location on the NavMesh placed as closely as possible to the specified target position.
+ ///
+ ///The start location is returned when that start is inside an area which is not allowed by the areaMask.
+ ///
+ ///
+ ///Areas and Costs
public NavMeshLocation MoveLocation(NavMeshLocation location, Vector3 target, int areaMask = NavMesh.AllAreas)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -358,6 +562,20 @@ public NavMeshLocation MoveLocation(NavMeshLocation location, Vector3 target, in
[NativeMethod(IsThreadSafe = true)]
static extern bool GetPortalPointsExp(IntPtr navMeshQuery, PolygonId polygon, PolygonId neighbourPolygon, out Vector3 left, out Vector3 right);
+ ///Obtains the end points of the line segment common to two adjacent NavMesh nodes.
+ ///For two polygons that are part of a NavMesh surface, this method returns the edge where both polygons meet. If the two polygons are in different NavMesh tiles the connected edges can be of different length or have different start and end positions from each other. If this happens the resulting separation edge is the overlapping part of the edges, which may be shorter than either of the individual edges.
+ ///
+ ///When one node is a link and the other is a polygon, the returned points are placed where the link intersects the polygon.
+ ///
+ ///The resulting positions are expressed in world space and can be transformed into a NavMesh's local space by the use of .
+ ///First NavMesh node.
+ ///Second NavMesh node.
+ ///One of the world points for the resulting separation edge which must be passed through when traversing between the two specified nodes. This point is the left side of the edge when traversing from the first node to the second.
+ ///One of the world points for the resulting separation edge which must be passed through when traversing between the two specified nodes. This point is the right side of the edge when traversing from the first node to the second.
+ ///
+ /// True if a connection exists between the two NavMesh nodes.
+ ///False if no connection exists between the two NavMesh nodes.
+ ///
public bool GetPortalPoints(PolygonId polygon, PolygonId neighbourPolygon, out Vector3 left, out Vector3 right)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -366,6 +584,21 @@ public bool GetPortalPoints(PolygonId polygon, PolygonId neighbourPolygon, out V
[NativeMethod(IsThreadSafe = true)]
static extern Matrix4x4 PolygonLocalToWorldMatrixExp(IntPtr navMeshQuery, PolygonId polygon);
+ ///Returns the transformation matrix of the NavMesh surface that contains the specified NavMesh node.
+ ///
+ /// surfaces have their transforms defined by the position and rotation values declared at the moment when they were baked with , or as part of a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/NavMeshSurface.html">NavMeshSurface</a>, or by explicitly setting the values for and .
+ ///
+ ///Custom transforms for s can further be specified when they are created with explicit position and rotation values passed to the (data, position, rotation) method.
+ ///
+ ///**Important:** This method does not return the position and orientation of a single NavMesh polygon. It returns the position of the surface that owns the polygon.
+ ///
+ ///**Known issue:** Identity matrix is returned instead of the actual transform for NavMeshLinks that have been instantiated with a call to (link, position, rotation).
+ ///NavMesh node for which its owner's transform must be determined.
+ ///Transformation matrix for the surface owning the specified polygon.
+ ///
+ /// when the NavMesh node is a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a> or an .
+ ///
+ ///
public Matrix4x4 PolygonLocalToWorldMatrix(PolygonId polygon)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -374,6 +607,17 @@ public Matrix4x4 PolygonLocalToWorldMatrix(PolygonId polygon)
[NativeMethod(IsThreadSafe = true)]
static extern Matrix4x4 PolygonWorldToLocalMatrixExp(IntPtr navMeshQuery, PolygonId polygon);
+ ///Returns the inverse transformation matrix of the NavMesh surface that contains the specified NavMesh node.
+ ///In contrast to the returned matrix can be used for transforming a world-coordinates position into the local coordinate system of the NavMesh surface owning the specified polygon.
+ ///
+ ///**Important:** This method does not return the inverse position and orientation of a single NavMesh polygon. It returns the inverse position and orientation of the surface that owns the polygon.
+ ///
+ ///**Known issue:** Identity matrix is returned instead of the actual inverse transform for NavMeshLinks that have been instantiated with a call to (linkData, position, rotation).
+ ///NavMesh node for which its owner's inverse transform must be determined.
+ ///Inverse transformation matrix of the surface owning the specified polygon.
+ ///
+ /// when the NavMesh node is a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a> or an .
+ ///
public Matrix4x4 PolygonWorldToLocalMatrix(PolygonId polygon)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -382,6 +626,18 @@ public Matrix4x4 PolygonWorldToLocalMatrix(PolygonId polygon)
[NativeMethod(IsThreadSafe = true)]
static extern NavMeshPolyTypes GetPolygonTypeExp(IntPtr navMeshQuery, PolygonId polygon);
+ ///Returns whether the NavMesh node is a polygon or a link.
+ ///The type can be determined even after the specified node has become invalid in the query's NavMeshWorld.
+ ///
+ ///**Known issue, to be fixed:** If the query's is invalid for any reason, the method returns .
+ ///Identifier of a node from a NavMesh surface or link.
+ ///
+ /// Ground when the node is a polygon on a NavMesh surface.
+ ///
+ ///OffMeshConnection when the node is a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a> or an .
+ ///
+ ///
+ ///
public NavMeshPolyTypes GetPolygonType(PolygonId polygon)
{
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
@@ -396,6 +652,84 @@ public NavMeshPolyTypes GetPolygonType(PolygonId polygon)
static extern unsafe PathQueryStatus RaycastExp(IntPtr navMeshQuery, NavMeshLocation start, Vector3 targetPosition,
int areaMask, void* costs, out NavMeshHit hit, void* path, out int pathCount, int maxPath);
+ ///Trace a line between two points on the NavMesh.
+ ///This method is similar to , both of them sharing the same underlying implementation.
+ ///
+ ///The properties that make this one different are:
+ ///
+ ///- it can be used in parallel [jobs](xref:JobSystem);
+ ///
+ ///- it returns status flags indicating whether the operation succeeded or failed;
+ ///
+ ///- the reported hit.distance is affected by the area costs;
+ ///
+ ///- the resulting hit.position is not adjusted on the vertical axis according to the <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/HeightMesh.html">HeightMesh</a>, if that exists;
+ ///
+ ///- it has the variant described below that returns also the list of polygons through which the ray passes.
+ ///
+ ///
+ ///
+ ///The returned hit.distance represents the straight line between the start and termination point. It also takes into account the list of the provided area costs. It is the result of summing up all the distances covered by the ray over each separate area, multiplied by the cost of that respective area.
+ ///
+ ///
+ ///
+ ///First, the start location is verified to be valid in the NavMeshWorld, and the target point is mapped on the NavMesh. Then, a ray is traced from the start point towards the target. If the computation is successful, the hit data is filled with information about the furthest point that the ray has reached. This happens regardless of whether the path from the source to target has been obstructed.
+ ///
+ ///If the computation fails, the returned hit is filled with invalid data. Most notably, the hit.distance field gets the value positiveInfinity.
+ ///
+ ///If the raycast terminates on an outer edge, hit.mask is 0; otherwise it contains the area mask of the blocking polygon.
+ ///
+ ///You can use this function to check if an agent can walk unobstructed between two points on the NavMesh. For example, if your character has an evasive dodge move that needs space, you can shoot a ray from the character's location to multiple directions. This finds a spot where the character can dodge to.
+ ///
+ ///The is different from the Physics raycast. The NavMeshQuery.Raycast can detect all kinds of navigation obstructions, for example holes in the ground. It can also climb up slopes, if the area is navigable.
+ ///Holds the properties of the raycast resulting location.
+ ///The start location of the ray on the NavMesh. start.polygon must be of the type .
+ ///The desired end of the ray, in world coordinates.
+ ///Bitmask that correlates index positions with area types. The index goes from 0 to 31. In each relevant index position, you have to set the value to either 1 or 0. 1 indicates area types that the ray can pass through. 0 indicates area types that block the ray. This parameter is optional. If you leave out this parameter, it defaults to . To learn more, see: <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/AreasAndCosts.html">Areas and Costs</a>.
+ ///Array of custom cost values for all of the 32 possible area types. They act as multipliers to the distance reported by the ray when crossing various areas. This parameter is optional. If you omit it, it defaults to the area costs that you configured in the Project settings. To learn more, see .
+ ///
+ /// Success if the ray can be correctly traced using the provided arguments.
+ ///
+ ///Failure if the start location is not valid in the query's NavMeshWorld, or if it is inside an area not permitted by the areaMask argument, or when it is on a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a>/.
+ ///
+ /// ());
+ /// if ((status & PathQueryStatus.Success) != 0)
+ /// {
+ /// Debug.DrawLine(transform.position, target.position, m_Hit.hit ? Color.red : Color.green);
+ ///
+ /// if (m_Hit.hit)
+ /// Debug.DrawRay(m_Hit.position, Vector3.up, Color.red);
+ /// }
+ /// }
+ ///
+ /// void OnDisable()
+ /// {
+ /// m_NavQuery.Dispose();
+ /// }
+ ///}
+ ///]]>
+ ///
public unsafe PathQueryStatus Raycast(out NavMeshHit hit, NavMeshLocation start, Vector3 targetPosition,
int areaMask = NavMesh.AllAreas, NativeArray costs = new NativeArray())
{
@@ -415,6 +749,66 @@ public unsafe PathQueryStatus Raycast(out NavMeshHit hit, NavMeshLocation start,
return status;
}
+ ///Trace a line between two points on the NavMesh, and return the list of polygons through which it passed.
+ ///Even if the path buffer is too small it will still hold as many polygons as it has room for, starting from the ray's origin location.
+ ///Holds the properties of the raycast resulting location.
+ ///A buffer that will be filled with the sequence of polygons through which the ray passes.
+ ///The reported number of polygons through which the ray has passed, all stored in the path buffer. It will not be greater than path.Length.
+ ///The start location of the ray on the NavMesh. start.polygon must be of the type .
+ ///The desired end of the ray, in world coordinates.
+ ///A bitfield that specifies which NavMesh areas can be traversed when the ray is traced. This parameter is optional. If you do not fill out this parameter, it defaults to .
+ ///Cost multipliers that affect the distance reported by the ray over different area types. This parameter is optional. If you omit it, it defaults to the area costs that you configured in the Project settings.
+ ///
+ /// Success if the ray can be correctly traced using the provided arguments.
+ ///
+ ///Failure if the start location is not valid in the query's NavMeshWorld, or if it is inside an area not permitted by the areaMask argument, or when it is on a <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a>/.
+ ///
+ ///BufferTooSmall is part of the returned flags when the provided path buffer is not large enough to hold all the polygons that the ray passed through.
+ ///
+ /// m_Path;
+ /// int m_PathCount;
+ ///
+ /// void OnEnable()
+ /// {
+ /// m_Path = new NativeArray(3, Allocator.Persistent);
+ /// m_NavQuery = new NavMeshQuery(NavMeshWorld.GetDefaultWorld(), Allocator.Persistent);
+ /// }
+ ///
+ /// void Update()
+ /// {
+ /// var startLocation = m_NavQuery.MapLocation(transform.position, Vector3.one, 0);
+ /// PathQueryStatus status = m_NavQuery.Raycast(out m_Hit, m_Path, out m_PathCount, startLocation, target.position, NavMesh.AllAreas, new NativeArray());
+ /// if ((status & PathQueryStatus.Success) != 0)
+ /// {
+ /// var bufferTooSmall = (status & PathQueryStatus.BufferTooSmall) != 0;
+ /// Debug.DrawLine(transform.position, m_Hit.position, bufferTooSmall ? Color.black : Color.green);
+ ///
+ /// if (m_Hit.hit)
+ /// Debug.DrawRay(m_Hit.position, Vector3.up, Color.red);
+ /// }
+ /// }
+ ///
+ /// void OnDisable()
+ /// {
+ /// m_NavQuery.Dispose();
+ /// m_Path.Dispose();
+ /// }
+ ///}
+ ///]]>
+ ///
+ ///
public unsafe PathQueryStatus Raycast(out NavMeshHit hit, NativeSlice path, out int pathCount,
NavMeshLocation start, Vector3 targetPosition,
int areaMask = NavMesh.AllAreas, NativeArray costs = new NativeArray())
@@ -440,6 +834,116 @@ static extern unsafe PathQueryStatus GetEdgesAndNeighborsExp(IntPtr navMeshQuery
void* verts, void* neighbors, void* edgeIndices,
out int vertCount, out int neighborsCount);
+ ///Retrieves the vertices of a given node and the identifiers of all the navigation nodes to which it connects.
+ ///A polygon of a NavMesh surface connects to all other neighboring polygons with which it shares an edge as well as all the OffMeshLinks or NavMeshLinks that leave from anywhere on its surface. The polygon does not connect to other polygons with which it shares only a vertex.
+ ///
+ ///Each point returned in the edgeVertices array represents the start of a node's edge and the subsequent element in the array is the end point of that edge. All vertices form a closed polygonal line. The last and first elements define the last edge.
+ ///
+ ///
+ ///
+ ///An off-mesh link connects to all the NavMesh polygons that each end of the link intersects with, regardless of whether the link is unidirectional.
+ ///
+ ///For link nodes the returned edgeVertices array contains two pairs of points at indices [0]-[1] and [2]-[3] that define the end points of the start and end edges of the link, in this order. These are the world positions established at the moment when the link is instantiated in the NavMesh world. For nodes added through <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/NavMeshLink.html">NavMesh Link</a> or <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/OffMeshLink.html">OffMesh Link</a> components the pairs contain the same value in both of their elements.
+ ///
+ ///
+ ///
+ ///A node from the neighbors array lies at the edge returned in edgeIndices at the same index.
+ ///
+ ///If both the given node and its neighbor are NavMesh polygons, then the corresponding edgeIndices value represents the index of the polygon edge that leads from node to the neighbor. E.g. edgeVertices[edgeIndices[2]] represents the start point of the edge that is common between node and the neighbors[2] node, and edgeVertices[edgeIndices[2] + 1] is the end point of that edge.
+ ///
+ ///A NavMesh polygon can have a maximum of 6 edges. This means the edgeIndices value corresponding to a polygon-polygon connection is between 0 and 5, inclusive. An edge usually connects only the two polygons that share it, but edges that sit at a tile border can connect one polygon in the first tile to multiple polygons in the second tile. In this case, edgeIndices report the same value for all of those neighbors.
+ ///
+ ///If either the given node or the neighbor is a link, then the corresponding edgeIndices value represents the side on the link where the connection is made: 0 for start and 2 for end. When the node is a polygon and the neighbor is a link the value acts only as information about the side of the link where the two nodes connect and should not be used as an index in the edgeVertices array.
+ ///
+ ///When the neighbors and edgeIndices buffers both have positive capacity, they must be the same size, otherwise you will encounter an ArgumentException when this method executes in the Editor.
+ ///
+ ///
+ ///
+ ///You can set any of the buffers to have zero capacity for the cases when you do not need the results.
+ ///
+ ///
+ ///
+ ///The returned verticesCount and neighborsCount values express the number of elements that comprise the result in the output buffers of sufficient size. Buffers that are not large enough are still filled with valid nodes up to their full capacity.
+ ///
+ ///
+ ///
+ ///The five result parameters (edgeVertices, neighbors, edgeIndices, verticesCount and neighborsCount) do not act as input and do not change the internal navigation data in any way. Unity only modifies them in the case when the operation returns a Success status.
+ ///Identifier of a node from a NavMesh surface, <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a> or for which the vertices and neighbors need to be retrieved.
+ ///The result buffer that contains the world positions describing the geometry of the input navigation node. It can have zero capacity.
+ ///
+ ///Polygonal nodes of the NavMesh have a minimum of 3 and a maximum of 6 vertices.
+ ///
+ ///OffMeshConnection nodes are always represented by 4 vertices, regardless of their width.
+ ///The result buffer that holds the identifiers of all the navigation nodes immediately reachable from the given node. It can have zero capacity.
+ ///The helper result buffer that maps each neighbor node to an edge of the given node. It can have zero capacity.
+ ///
+ ///The index of an element in edgeIndices is also an index in the neighbors array and the value of that edgeIndices element is an index in the edgeVertices array.
+ ///The total number of vertices that describe the geometry of the input node. This is independent of the capacity of the vertices result buffer.
+ ///The total number of navigation nodes the input node connects to. This is independent of the capacity of the result buffers (neighbors and edgeIndices).
+ ///
+ /// Success if Unity can evaluate the neighbors and vertices of the specified node, regardless of the result. The verticesCount and neighborsCount are always valid in this case.
+ ///
+ ///Failure if Unity can not use the node identifier to retrieve the neighbors or geometry information. Unity does not modify any of the five result parameters (edgeVertices, neighbors, edgeIndices, verticesCount or neighborsCount) in this case.
+ ///
+ ///InvalidParam is part of the returned flags if the specified navigation node is not valid in the query's NavMeshWorld.
+ ///
+ ///BufferTooSmall is part of the PathQueryStatus flags, that Unity returns from this function, when any of the result buffers you provide are not large enough to hold all the neighbor nodes the input node connects to or all of its edge vertices.
+ ///
+ /// (6, Allocator.Temp);
+ /// var neighbors = new NativeArray(10, Allocator.Temp);
+ /// var edgeIndices = new NativeArray(neighbors.Length, Allocator.Temp);
+ /// int totalVertices;
+ /// int totalNeighbors;
+ ///
+ /// var location = query.MapLocation(transform.position, Vector3.one, 0);
+ ///
+ /// var queryStatus = query.GetEdgesAndNeighbors(
+ /// location.polygon, vertices, neighbors, edgeIndices,
+ /// out totalVertices, out totalNeighbors);
+ ///
+ /// var color = (queryStatus & PathQueryStatus.Success) != 0 ? Color.green : Color.red;
+ /// Debug.DrawLine(transform.position - Vector3.up, transform.position + Vector3.up, color);
+ ///
+ /// for (int i = 0, j = totalVertices - 1; i < totalVertices; j = i++)
+ /// {
+ /// Debug.DrawLine(vertices[i], vertices[j], Color.grey);
+ /// }
+ ///
+ /// for (var i = 0; i < totalNeighbors; i++)
+ /// {
+ /// if (query.GetPolygonType(neighbors[i]) == NavMeshPolyTypes.OffMeshConnection)
+ /// {
+ /// // The link neighbor is not connected through any of the polygon's edges.
+ /// // Call GetEdgesAndNeighbors() on this specific neighbor in order to retrieve its edges.
+ /// continue;
+ /// }
+ ///
+ /// var start = edgeIndices[i];
+ /// var end = (start + 1) % totalVertices;
+ /// var neighborColor = Color.Lerp(Color.yellow, Color.magenta, 1f * start / (totalVertices - 1));
+ /// Debug.DrawLine(vertices[start], vertices[end], neighborColor);
+ /// }
+ ///
+ /// query.Dispose();
+ /// vertices.Dispose();
+ /// neighbors.Dispose();
+ /// edgeIndices.Dispose();
+ /// }
+ ///}
+ ///]]>
+ ///
+ ///
+ ///
public unsafe PathQueryStatus GetEdgesAndNeighbors(PolygonId node,
NativeSlice edgeVertices, NativeSlice neighbors, NativeSlice edgeIndices,
out int verticesCount, out int neighborsCount)
diff --git a/Modules/AI/NavMeshPath.bindings.cs b/Modules/AI/NavMeshPath.bindings.cs
index ebd79f7705..008158ae84 100644
--- a/Modules/AI/NavMeshPath.bindings.cs
+++ b/Modules/AI/NavMeshPath.bindings.cs
@@ -10,16 +10,22 @@
namespace UnityEngine.AI
{
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
- // Status of path.
+ ///Status of path.
[MovedFrom("UnityEngine")]
public enum NavMeshPathStatus
{
- PathComplete = 0, // The path terminates at the destination.
- PathPartial = 1, // The path cannot reach the destination.
- PathInvalid = 2 // The path is invalid.
+ ///The path terminates at the destination.
+ PathComplete = 0,
+ ///The path cannot reach the destination.
+ PathPartial = 1,
+ ///The path is not valid.
+ ///Refer to the documentation of the returning method or property for more information. , .
+ ///
+ PathInvalid = 2
}
- // Path navigation.
+ ///A path as calculated by the navigation system.
+ ///The path is represented as a list of waypoints stored in the array. These points are not set directly from user scripts but a NavMeshPath with points correctly assigned is returned by the function and the property.
[NativeHeader("Modules/AI/NavMeshPath.bindings.h")]
[StructLayout(LayoutKind.Sequential)]
[MovedFrom("UnityEngine")]
@@ -28,6 +34,7 @@ public sealed class NavMeshPath
internal IntPtr m_Ptr;
internal Vector3[] m_Corners;
+ ///NavMeshPath constructor.
public NavMeshPath()
{
m_Ptr = InitializeNavMeshPath();
@@ -45,6 +52,12 @@ public NavMeshPath()
[FreeFunction("NavMeshPathScriptBindings::DestroyNavMeshPath", IsThreadSafe = true)]
static extern void DestroyNavMeshPath(IntPtr ptr);
+ ///Calculate the corners for the path.
+ ///This function is similar to the property except that the results are returned in the supplied array.
+ ///
+ ///Note that this function expects the supplied array to have at least 2 elements.
+ ///Array to store path corners.
+ ///The number of corners along the path - including start and end points.
[FreeFunction("NavMeshPathScriptBindings::GetCornersNonAlloc", HasExplicitThis = true)]
public extern int GetCornersNonAlloc([Out] Vector3[] results);
@@ -54,7 +67,7 @@ public NavMeshPath()
[FreeFunction("NavMeshPathScriptBindings::ClearCornersInternal", HasExplicitThis = true)]
extern void ClearCornersInternal();
- // Erase all corner points from path.
+ ///Erase all corner points from path.
public void ClearCorners()
{
ClearCornersInternal();
@@ -67,10 +80,32 @@ void CalculateCorners()
m_Corners = CalculateCornersInternal();
}
- // Corner points of path. (RO)
+ ///Corner points of the path.
+ ///Also known as "waypoints", the corners define the places along a path where it changes direction (ie, the path consists of a number of straight-line moves between corners).
+ ///
+ ///
+ ///
public Vector3[] corners { get { CalculateCorners(); return m_Corners; } }
- // Status of the path. (RO)
+ ///Status of the path.
+ ///This reports whether the path reaches the target, reaches part of the way to the target, or is just not valid. Among other reasons, a path returns if it can't determine the nearest polygon of the source or target position, or if the path would have been a partial result, but the point closest to the target on the final polygon could not be determined. These situations are rare, and may arise if the navigation mesh is being changed while a path is being calculated.
public extern NavMeshPathStatus status { get; }
internal static class BindingsMarshaller
diff --git a/Modules/AI/Public/NavMeshBindingTypes.bindings.cs b/Modules/AI/Public/NavMeshBindingTypes.bindings.cs
index 5e5cde5d0e..b187070e40 100644
--- a/Modules/AI/Public/NavMeshBindingTypes.bindings.cs
+++ b/Modules/AI/Public/NavMeshBindingTypes.bindings.cs
@@ -9,49 +9,141 @@
namespace UnityEngine.AI
{
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
+ ///Bitmask used for operating with debug data from the NavMesh build process.
+ ///Used in two situations:
+ ///
+ ///- within to specify which debug data to retain after the build process has completed, preserving the world position and orientation;
+ ///
+ ///- as a parameter of to control which of the available debug data types to display for a specified NavMesh.
+ ///
[Flags]
public enum NavMeshBuildDebugFlags
{
+ ///No debug data from the NavMesh build process is taken into consideration.
+ ///
+ ///
None = 0,
+ ///The triangles of all the geometry that is used as a base for computing the new NavMesh.
+ ///
+ ///
+ ///
+ ///
InputGeometry = 1 << 0,
+ ///The voxels produced by rasterizing the source geometry into walkable and unwalkable areas.
+ ///
+ ///
+ ///
Voxels = 1 << 1,
+ ///The segmentation of the traversable surfaces into smaller areas necessary for producing simple polygons.
+ ///
+ ///
Regions = 1 << 2,
+ ///The contours that follow precisely the edges of each surface region.
+ ///
+ ///
RawContours = 1 << 3,
+ ///Contours bounding each of the surface regions, described through fewer vertices and straighter edges compared to .
+ ///
+ ///
SimplifiedContours = 1 << 4,
+ ///Meshes of convex polygons constructed within the unified contours of adjacent regions.
+ ///
+ ///
PolygonMeshes = 1 << 5,
+ ///The triangulated meshes with height details that better approximate the source geometry.
+ ///
+ ///
PolygonMeshesDetail = 1 << 6,
+ ///All debug data from the NavMesh build process is taken into consideration.
+ ///
+ ///
All = unchecked((int)(~(~0U << 7)))
}
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
+ ///Used with to define the shape for building NavMesh.
public enum NavMeshBuildSourceShape
{
+ ///Describes a Mesh source for use with . Mesh sources must be positioned within 100,000 units of the world origin and must not exceed 100,000 units in any axis-aligned dimension.
Mesh = 0,
+ ///Describes a source for use with .
Terrain = 1,
+ ///Describes a box primitive for use with .
Box = 2,
+ ///Describes a sphere primitive for use with .
Sphere = 3,
+ ///Describes a capsule primitive for use with .
Capsule = 4,
+ ///Describes a ModifierBox source for use with .
+ ///This shape changes the area type of the walkable surface inside the box. Because this modification happens in a voxel representation of the scene, NavMesh does not follow the outline of the box precisely. If several ModifierBoxes overlap, and have different area types, the area type with the highest index takes precedence. A ModifierBox that you set to Not Walkable takes precedence over any other ModifierBoxes, regardless of their area type. This is useful when you need to block out an area.
+ ///Areas and Costs
ModifierBox = 5
}
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
+ ///Used for specifying the type of geometry to collect. Used with .
public enum NavMeshCollectGeometry
{
+ ///Collect meshes form the rendered geometry.
RenderMeshes = 0,
+ ///Collect geometry from the 3D physics collision representation.
PhysicsColliders = 1
}
- // Struct containing source geometry data and annotation for runtime navmesh building
+ ///The input to the NavMesh builder is a list of NavMesh build sources.
+ ///Their shape can be one of the following: mesh, terrain, box, sphere, or capsule. Each of them is described by a NavMeshBuildSource struct.
+ ///
+ ///You can specify a build source by filling a NavMeshBuildSource struct and adding that to the list of sources that are passed to the bake function. Alternatively, you can use the collect API to quickly create NavMesh build sources from available render meshes or physics colliders. See .
+ ///
+ ///If you use this function at runtime, any meshes with read/write access disabled will not be processed or included in the final NavMesh. See .
+ ///
+ ///
+ ///
[UsedByNativeCode]
[NativeHeader("Modules/AI/Public/NavMeshBindingTypes.h")]
public struct NavMeshBuildSource
{
+ ///Describes the local to world transformation matrix of the build source. That is, position and orientation and scale of the shape.
public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } }
+ ///Describes the dimensions of the shape.
+ ///Used only for the primitive shapes: Sphere, Capsule, Box.
+ ///
+ ///• Sphere: size is the dimensions of a box enclosing the sphere (i.e., x, y, and z are all equal to the diameter).
+ ///
+ ///• Box: size is the dimensions of the box.
+ ///
+ ///• Capsule: size is the dimensions of a box enclosing the capsule (i.e., x and z are equal to the diameter of the capsule and y is the height).
public Vector3 size { get { return m_Size; } set { m_Size = value; } }
+ ///The type of the shape this source describes.
+ ///
public NavMeshBuildSourceShape shape { get { return m_Shape; } set { m_Shape = value; } }
+ ///Describes the area type of the NavMesh surface for this object.
public int area { get { return m_Area; } set { m_Area = value; } }
+ ///Enables the links generation for this object.
+ ///When build sources are obtained using , this value can be affected by using . If this value is true and links parameters are valid in this source will be considered during links generation.
public bool generateLinks { get { return m_GenerateLinks != 0; } set { m_GenerateLinks = value ? 1 : 0; } }
+ ///Describes the object referenced for Mesh and Terrain types of input sources.
+ ///Used only for the types: and .
public Object sourceObject { get { return InternalGetObject(m_EntityId); } set { m_EntityId = value != null ? value.GetEntityId() : EntityId.None; } }
+ ///Points to the owning component - if available, otherwise null.
+ ///When build sources are obtained using , this value typically refers to a mesh or collider component - however for shared meshes it will be null.
+ ///
public Component component { get { return InternalGetComponent(m_ComponentID); } set { m_ComponentID = value != null ? value.GetEntityId() : EntityId.None; } }
Matrix4x4 m_Transform;
@@ -69,17 +161,34 @@ public struct NavMeshBuildSource
static extern Object InternalGetObject(EntityId instanceID);
}
- // Struct containing source geometry data and annotation for runtime navmesh building
+ ///The NavMesh build markup allows you to control how certain objects are treated during the NavMesh build process, specifically when collecting sources for building.
+ ///You can override the area type or specify that certain objects should be excluded from collected sources. The markup can be applied hierarchically or to only the specified object.
+ ///
[NativeHeader("Modules/AI/Public/NavMeshBindingTypes.h")]
public struct NavMeshBuildMarkup
{
+ ///Use this to specify whether the area type of the GameObject and its children should be overridden by the area type specified in this struct.
public bool overrideArea { get { return m_OverrideArea != 0; } set { m_OverrideArea = value ? 1 : 0; } }
+ ///The area type to use when override area is enabled.
public int area { get { return m_Area; } set { m_Area = value; } }
+ ///Set this to true in order to enable the property.
+ ///In the case when a NavMeshBuildMarkup is used to change only the area type of an object, overrideIgnore should be set to false so that the ignoreFromBuild property will not have any effect.
+ ///
+ /// If none of the objects in a hierarchy are marked with ignoreFromBuild set to true then no objects in that hierarchy will be ignored while building the NavMesh.
public bool overrideIgnore { get { return m_InheritIgnoreFromBuild == 0; } set { m_InheritIgnoreFromBuild = value ? 0: 1; } }
+ ///Use this to specify whether the GameObject and its children should be ignored.
+ ///If you set this to true, the GameObject and its children will not be included as part of the NavMesh.
+ ///
+ /// Set to true in order for this property to have the intended effect. When overrideIgnore is false this property inherits the value from the markup of a parent object, if that exists, otherwise it is set to false.
public bool ignoreFromBuild { get { return m_IgnoreFromBuild != 0; } set { m_IgnoreFromBuild = value ? 1 : 0; } }
+ ///Use this to specify whether the default links generation condition for the GameObject and its children should be overridden by the generateLinks option specified in this struct.
public bool overrideGenerateLinks { get { return m_OverrideGenerateLinks != 0; } set { m_OverrideGenerateLinks = value ? 1 : 0; } }
+ ///Use this to specify whether the GameObject and its children should be included in the link generation process.
public bool generateLinks { get { return m_GenerateLinks != 0; } set { m_GenerateLinks = value ? 1 : 0; } }
+ ///Use this to specify if the GameObject's children also use these markup settings.
public bool applyToChildren { get { return m_IgnoreChildren == 0; } set { m_IgnoreChildren = value ? 0 : 1; } }
+ ///Use this to specify which GameObject (including the GameObject’s children) the markup should be applied to.
+ ///This markup will be shared with the children of the root GameObject only if is set to true.
public Transform root { get { return InternalGetRootGO(m_EntityId); } set { m_EntityId = value != null ? value.GetEntityId() : EntityId.None; } }
int m_OverrideArea;
diff --git a/Modules/AI/Public/NavMeshBuildSettings.bindings.cs b/Modules/AI/Public/NavMeshBuildSettings.bindings.cs
index 06b57d6fbb..8fd3c6e91c 100644
--- a/Modules/AI/Public/NavMeshBuildSettings.bindings.cs
+++ b/Modules/AI/Public/NavMeshBuildSettings.bindings.cs
@@ -9,25 +9,108 @@
namespace UnityEngine.AI
{
// Keep this struct in sync with the one defined in "NavMeshBuildSettings.h"
+ ///The NavMeshBuildSettings struct allows you to specify a collection of settings which describe the dimensions and limitations of a particular agent type.
+ ///You might want to define multiple NavMeshBuildSettings if your game involves characters with large differences in height, width or climbing ability.
+ ///
+ ///You can also use this struct to control the precision and granularity of the build process, by setting the voxel and tile sizes. Some of the values are coupled, meaning there are constraints on the values based on other values. For example, it’s not valid for to be larger than .
+ ///To help diagnose violations of these rules, a special method can be evaluated.
[StructLayout(LayoutKind.Sequential)]
[NativeHeader("Modules/AI/Public/NavMeshBuildSettings.h")]
public struct NavMeshBuildSettings
{
+ ///The agent type ID the NavMesh will be baked for.
+ ///Each or can only use a NavMesh which is built for its agent type; it is the ID that is matched.
public int agentTypeID { get { return m_AgentTypeID; } set { m_AgentTypeID = value; } }
+ ///The radius of the agent for baking in world units.
+ ///The resulting NavMesh will be shrunk by this radius to make sure that agents do not clip to walls when close to obstacles, in some scenarios it can be useful to reduce this radius.
public float agentRadius { get { return m_AgentRadius; } set { m_AgentRadius = value; } }
+ ///The height of the agent for baking in world units.
+ ///NavMesh will be removed from areas with a ceiling lower than this height. The build process does some quantization, so make sure that spaces you intend to be walkable have some extra head room.
public float agentHeight { get { return m_AgentHeight; } set { m_AgentHeight = value; } }
+ ///The maximum slope angle which is walkable (angle in degrees).
+ ///The valid range is 0–60 degrees. Steep slopes will be excluded from the resulting NavMesh. Please note that setting the slope higher than 45 can give artifacts due to the voxelization process - i.e. a steep slope cannot be distinguished from a wall.
public float agentSlope { get { return m_AgentSlope; } set { m_AgentSlope = value; } }
+ ///The maximum vertical step size an agent can take.
+ ///Must be less than agent height. This parameter is used to detect sharp discontinuities in the level (i.e. stairs, steps), and allow the agent to pass them.
public float agentClimb { get { return m_AgentClimb; } set { m_AgentClimb = value; } }
+ ///Maximum agent drop height.
+ ///Drop-Down link generation is controlled by the Drop Height parameter. The parameter controls what is the highest drop that will be connected, setting the value to 0 will disable the generation.
+ ///
+ ///The trajectory of the drop-down link is defined so that the horizontal travel is: 2 x agentRadius + 4 x voxelSize. That is, the drop will land just beyond the edge of the platform. In addition the vertical travel needs to be more than bake settings’ Step Height (otherwise we could just step down) and less than Drop Height. The adjustment by voxel size is done so that any round off errors during voxelization does not prevent the links being generated. You should set the Drop Height to a bit larger value than what you measure in your level, so that the links will connect properly.
public float ledgeDropHeight { get { return m_LedgeDropHeight; } set { m_LedgeDropHeight = value; } }
+ ///Maximum agent jump distance.
+ ///Jump-Across link generation is controlled by the Jump Distance parameter. The parameter controls what is the furthest distance that will be connected. Setting the value to 0 will disable the generation.
+ ///
+ ///The trajectory of the jump-across link is defined so that the horizontal travel is more than 2 x agentRadius and less than Jump Distance. In addition the landing location must not be further than voxelSize from the level of the start location.
public float maxJumpAcrossDistance { get { return m_MaxJumpAcrossDistance; } set { m_MaxJumpAcrossDistance = value; } }
+ ///The approximate minimum area of individual NavMesh regions.
+ ///This property allows you to cull away small non-connected NavMesh regions. NavMesh regions whose surface area is smaller than the specified value, will be removed.
+ ///
+ ///Note: some regions may not get removed. The NavMesh is built in parallel as a grid of tiles. If a region straddles a tile boundary, the region is not removed. The reason for this is that the region pruning happens at a stage in the build process where surrounding tiles are not available.
public float minRegionArea { get { return m_MinRegionArea; } set { m_MinRegionArea = value; } }
+ ///Enables overriding the default voxel size.
+ ///
public bool overrideVoxelSize { get { return m_OverrideVoxelSize != 0; } set { m_OverrideVoxelSize = value ? 1 : 0; } }
+ ///Sets the voxel size in world length units.
+ ///The NavMesh is built by first voxelizing the Scene, and then figuring out walkable spaces from the voxelized representation of the Scene. The voxel size controls how closely the NavMesh fits the geometry of your Scene, and is defined in world units.
+ ///
+ ///If you require a more detail so that the NavMesh more closely fits your Scene’s geometry, you can reduce the voxel size. An increase in detail will also cause your game to consume more memory and take more time to calculate the NavMesh data. The scaling is roughly quadratic, so doubling the resolution will result in an approximate quadrupling of the build time.
+ ///
+ ///In general you should aim to have 4-6 voxels per character diameter. For example, if you have a Scene with characters that have a radius of 0.3, a good voxel size is 0.1. The default value is set to a third of the agentRadius.
+ ///
+ ///Note: If you want to use this setting, you must also set to true.
public float voxelSize { get { return m_VoxelSize; } set { m_VoxelSize = value; } }
+ ///Enables overriding the default tile size.
+ ///
public bool overrideTileSize { get { return m_OverrideTileSize != 0; } set { m_OverrideTileSize = value ? 1 : 0; } }
+ ///Sets the tile size in voxel units.
+ ///The NavMesh is built in square tiles in order to build the mesh in parallel and to control maximum memory usage. It also helps to make the carving changes more local. If you plan to update NavMesh at runtime, a good tile size is around 32–128 voxels (roughly 5 to 20 meters for human size characters). 64 is good value to start, and you can use the [profiler window](xref:Profiler) to find a good trade off. Default value is 256, which is good for static baking. If you use a lot of carving obstacles you can try a smaller size if you see in the profiler that a lot of time is being spent on carving.
+ ///
+ ///The tile size is specified in units of voxels per tile side length.
+ ///
+ ///Note: if you want to use this setting, you must also set to true.
public int tileSize { get { return m_TileSize; } set { m_TileSize = value; } }
+ ///The maximum number of worker threads that the build process can utilize when building a NavMesh with these settings.
+ ///A value between 1 and (inclusive) causes the build process to schedule all of the work within that number of jobs when building a NavMesh. Each job computes as many NavMesh tiles as it can grab, after it has finished computing the previous tiles.
+ ///
+ ///A value of 0 or higher than JobsUtility.JobWorkerCount causes the build process to use all of the available worker threads. In this case, it computes each tile in its own separate job. The build process also computes each tile in a separate job when the number of tiles that need computing is less than the number of worker threads.
+ ///
+ ///The default value is 0.
+ ///
public uint maxJobWorkers { get { return m_MaxJobWorkers; } set { m_MaxJobWorkers = value; } }
+ ///Specifies whether to keep the NavMesh unchanged in the sections outside the build bounds during a NavMesh update.
+ ///With this property enabled, a NavMesh update recomputes only the NavMesh tiles that fall completely inside the specified local bounds. All other tiles, such as those fully outside the bounds or those that only partially intersect them, remain unchanged. Unity rebuilds the recomputed tiles as usual from the provided objects.
+ ///
+ ///The default value is false, which means all tiles are rebuilt during a NavMesh update regardless of whether they fall inside the bounds.
+ ///
+ ///This property is useful when you need to update the NavMesh in a limited volume at runtime without affecting the rest of the NavMesh. Use this property to clear tiles in a specific area. Unity removes any tile inside the bounds that has no overlapping sources.
+ ///
+ ///The spatial dimensions of a NavMesh tile equal multiplied by . The world position of the tile grid origin depends on the positions and rotations used to build and then to instantiate the . The bounds passed to or are in local space relative to that origin.
+ ///
+ ///When this property is true, a NavMesh update has the following additional effects:
+ ///
+ ///- Unity doesn't create the height mesh, and if one already exists, Unity removes it.
+ ///- Unity removes all automatically generated off-mesh links and doesn't regenerate them. This is because generated links cannot be modified for only one section of the NavMesh. Manually placed <a href="https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/api/Unity.AI.Navigation.NavMeshLink.html">NavMeshLink</a> components are unaffected.
+ ///- The NavMesh builder carries over most build settings from the existing in order to preserve consistency. The exceptions are , , , and , which are taken from the settings you provide. Unity ignores changes to other settings such as or . The values already stored in the are used instead.
+ ///
+ ///Known issue: If you call a second time for the same object, the first operation is canceled. Therefore, you can't start operations with preserveTilesOutsideBounds in parallel to affect different parts of the NavMesh. Each call must wait for the previous operation's to be true before starting.
+ ///
+ ///This property is available as of Unity 2020.1.
public bool preserveTilesOutsideBounds { get { return m_PreserveTilesOutsideBounds != 0; } set { m_PreserveTilesOutsideBounds = value ? 1 : 0; } }
+ ///Enables the creation of additional data needed to determine the height at any position on the NavMesh more accurately.
+ ///The NavMesh Agent is constrained to the surface of the NavMesh as it navigates. Since the NavMesh is an approximation of the walkable space, some features are evened out when the NavMesh is built. For example, stairs may appear as a slope in the NavMesh. If you need accurate placement of the agent for your game, enable height mesh building when you build the NavMesh. Note that building the height mesh will take up memory and processing at runtime, and it increases the time needed to bake the NavMesh.
+ ///
+ ///The current implementation of the height mesh has the following limitations:
+ ///
+ ///- It can construct height data for a Terrain only when its horizontal plane is parallel to the XZ plane of the NavMesh.
+ ///- During a NavMesh update, if the build setting "preserveTilesOutsideBounds" is true the height mesh will not be created and if it already exists, will be removed.
+ ///
+ ///This property is available as of Unity 2022.2. It will be correctly compiled in scripts when the UNITY_2022_2_OR_NEWER symbol is [defined by the engine](xref:platform-dependent-compilation).
+ ///NavMeshSurface Advanced Settings
public bool buildHeightMesh { get { return m_BuildHeightMesh != 0; } set { m_BuildHeightMesh = value ? 1 : 0; } }
+ ///Options for collecting debug data during the build process.
+ ///
+ ///
public NavMeshBuildDebugSettings debug { get { return m_Debug; } set { m_Debug = value; } }
int m_AgentTypeID;
@@ -48,6 +131,18 @@ public struct NavMeshBuildSettings
NavMeshBuildDebugSettings m_Debug;
+ ///Validates the properties of NavMeshBuildSettings.
+ ///Returns a string of violated constraints. - and suggestions for changes for the current values in the build settings and the provided bounds for building the NavMesh.
+ ///
+ ///An empty array is returned if all internal constraints are satisfied.
+ ///
+ ///Some of the settings which you can specify in the struct are coupled to each other, meaning there are constraints on the values based on other values. For example, it’s not valid for to be larger than . Another invalid case is when the vertical size of the buildBounds exceeds the height of 65535 voxel units.
+ ///
+ ///You can use this function to check if the values in violate any of the constraints, before starting the NavMesh building process.
+ ///
+ ///Ignoring the violated constraints might give unexpected results when building a NavMesh, but will still produce a NavMesh.
+ ///Describes the volume to build NavMesh for.
+ ///The list of violated constraints.
public String[] ValidationReport(Bounds buildBounds)
{
return InternalValidationReport(this, buildBounds);
@@ -60,10 +155,50 @@ public String[] ValidationReport(Bounds buildBounds)
// Consider exposing a "Validate" method to modify the BuildSettings in-place
}
+ ///Specify which of the temporary data generated while building the NavMesh should be retained in memory after the process has completed.
+ ///It is possible to collect and display in the Editor the intermediate data used in the process of building the navigation mesh using the . This can help with diagnosing those situations when the resulting NavMesh isn’t of the expected shape.
+ ///
+ ///
+ ///
+ ///Input Geometry, Regions, Polygonal Mesh Detail and Raw Contours shown after building the NavMesh with debug options
+ ///
+ ///The process for computing a NavMesh comprises of several sequential steps:
+ ///
+ ///i. decomposing the Scene's terrain and meshes into triangles;
+ ///
+ ///ii. rasterizing the input triangles into a 3D voxel representation and finding ledges;
+ ///
+ ///iii. partitioning the voxels lying at the surface into simpler horizontal regions;
+ ///
+ ///iv. finding a tight-fitting contour for each of these regions;
+ ///
+ ///v. simplifying the contours into polygonal shapes;
+ ///
+ ///vi. creating a mesh of convex polygons based on all the contours combined;
+ ///
+ ///vii. refining the polygonal mesh into a triangulated version that approximates better the Scene's original geometry.
+ ///
+ ///Through the use of the debug functionality the results from each stage can be captured and displayed separately, whereas normally they would get discarded when the NavMesh construction is completed.
+ ///
+ ///Depending on the Scene composition this debug data can be considerably large in size. It is stored in memory in a compressed manner but gets further expanded when being displayed.
+ ///
+ ///**Notes: **
+ ///
+ ///1. Unity does not save Debug visualizations - they are only available during the session in which Unity is building the NavMesh.
+ ///
+ ///2. Debug data is neither displayed nor collected when the system recomputes local patches of the NavMesh due to the presence of NavMesh Obstacles.
+ ///
+ ///
+ ///
[StructLayout(LayoutKind.Sequential)]
[NativeHeader("Modules/AI/Public/NavMeshBuildDebugSettings.h")]
public struct NavMeshBuildDebugSettings
{
+ ///Specify which types of debug data to collect when building the NavMesh.
+ ///Default value is .
+ ///
+ ///
+ ///
public NavMeshBuildDebugFlags flags { get { return (NavMeshBuildDebugFlags)m_Flags; } set { m_Flags = (byte)value; } }
byte m_Flags;
diff --git a/Modules/AIEditor/Utilities/NavMeshEditorHelpers.cs b/Modules/AIEditor/Utilities/NavMeshEditorHelpers.cs
index e746353a39..921f0ad290 100644
--- a/Modules/AIEditor/Utilities/NavMeshEditorHelpers.cs
+++ b/Modules/AIEditor/Utilities/NavMeshEditorHelpers.cs
@@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.SceneManagement;
@@ -15,19 +16,22 @@ public static partial class NavMeshEditorHelpers
{
const string k_OpenAgentSettings = "NavMeshAgentInspector-OpenAgentSettings";
- internal static readonly bool isPackageInstalled;
+ [AutoStaticsCleanupOnCodeReload] // lazy cache; reset to null on reload so File.Exists re-runs on next access
+ static bool? s_IsPackageInstalled;
+ internal static bool isPackageInstalled =>
+ s_IsPackageInstalled ??= File.Exists(
+ FileUtil.PathToAbsolutePath("Packages/com.unity.ai.navigation/package.json"));
+ [AutoStaticsCleanupOnCodeReload] // holds user-registered event handlers for agent settings navigation
internal static event Action agentTypeSettingsClicked;
+ [AutoStaticsCleanupOnCodeReload] // holds user-registered event handlers for area settings navigation
internal static event Action areaSettingsClicked;
- static NavMeshEditorHelpers()
+ // If OpenAgentSettings() prompted the user to install the package, the install triggers a domain reload;
+ // a SessionState flag tells us to reopen the settings once the editor is ready again.
+ [OnCodeLoaded]
+ static void HandlePostInstallOpenAgentSettings()
{
- var packagePath = FileUtil.PathToAbsolutePath("Packages/com.unity.ai.navigation/package.json");
- isPackageInstalled = File.Exists(packagePath);
-
- // open the agent settings if the package was just installed via the dialog box in OpenAgentSettings()
- // there will have just been a domain reload, so a session state var is the only way to know the installation occurred from that user action
- // use a delay call to ensure SessionState API is called on the main thread, regardless of which thread NavMeshEditorHelpers is called on the first time
EditorApplication.delayCall += () =>
{
if (SessionState.GetBool(k_OpenAgentSettings, false))
diff --git a/Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.cs b/Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.cs
index d75dd5866a..67f118a962 100644
--- a/Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.cs
+++ b/Modules/AIEditor/Visualization/NavMeshVisualizationSettings.bindings.cs
@@ -4,6 +4,7 @@
using System;
using System.Runtime.CompilerServices;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Scripting.APIUpdating;
@@ -20,6 +21,7 @@ namespace UnityEditor.AI
public sealed class NavMeshVisualizationSettings
{
[Obsolete("showNavigation is no longer supported and will be removed.")]
+ [NoAutoStaticsCleanup] // obsolete infrastructure property; value does not affect runtime behavior
public static int showNavigation { get; set; }
internal static extern bool showOnlySelectedSurfaces { get; set; }
@@ -59,8 +61,11 @@ public static partial class NavMeshEditorHelpers
[StaticAccessor("GetNavMeshManager()", StaticAccessorType.Dot)]
internal static extern void GetAgentsDebugInfoRejectedRequestsCount(out int rejected, out int allowed);
+ [AutoStaticsCleanupOnCodeReload] // holds user-registered debug event handlers
internal static event Action agentRejectedDebugInfoRequestsCountChanged;
+ [AutoStaticsCleanupOnCodeReload] // holds user-registered debug event handlers
internal static event Action agentDebugRequestsPending;
+ [AutoStaticsCleanupOnCodeReload] // holds user-registered debug event handlers
internal static event Action agentDebugRequestsProcessed;
[RequiredByNativeCode]
diff --git a/Modules/Accessibility/Bindings/AccessibilityManager.bindings.cs b/Modules/Accessibility/Bindings/AccessibilityManager.bindings.cs
index 4d7225e98b..423ff69ab7 100644
--- a/Modules/Accessibility/Bindings/AccessibilityManager.bindings.cs
+++ b/Modules/Accessibility/Bindings/AccessibilityManager.bindings.cs
@@ -263,7 +263,8 @@ internal static void Internal_LateUpdate()
if (instance.m_RefreshNodeFramesRequested)
{
instance.m_RefreshNodeFramesRequested = false;
- AssistiveSupport.activeHierarchy?.RefreshNodeFrames();
+
+ AssistiveSupport.activeHierarchy?.RefreshNodeFramesWithoutResetting();
}
}
@@ -289,7 +290,7 @@ internal static int[] Internal_GetRootNodeIds()
}
[NativeHeader("Modules/Accessibility/Native/AccessibilityManager.h")]
- [FreeFunction("SetAccessibilityNodeDataPtr")]
+ [FreeFunction("SetAccessibilityNodeDataPtr", IsThreadSafe = true)]
internal extern static void SetAccessibilityNodeDataPtr(IntPtr destNodeDataPtr, AccessibilityNodeData sourceNodeData);
///
diff --git a/Modules/Accessibility/Bindings/AccessibilityNodeData.bindings.cs b/Modules/Accessibility/Bindings/AccessibilityNodeData.bindings.cs
index 2436e1fe69..a9dcb7ec56 100644
--- a/Modules/Accessibility/Bindings/AccessibilityNodeData.bindings.cs
+++ b/Modules/Accessibility/Bindings/AccessibilityNodeData.bindings.cs
@@ -105,6 +105,9 @@ public enum AccessibilityRole : byte
///- **macOS**: If this role is set on a node, the screen reader announces the node as a "search text field".
///- **Windows**: If this role is set on a node, the screen reader announces the node as "edit". The resulting behavior of this role is identical to that of .
///\\
+ /// On Android, subscribe to the event to put the search field into edit
+ /// mode when the user activates it, so that it can receive hardware keyboard input.
+ ///\\
/// On Windows and macOS, subscribe to the event to select the
/// search field represented by the node when the user navigates to it, so that it can receive keyboard input.
///
@@ -200,9 +203,9 @@ public enum AccessibilityRole : byte
/// events to perform an appropriate action when the user increases
/// or decreases the node's value, such as changing the value of the slider represented by the node. On Windows,
/// these events are only triggered for nodes whose contains a number.
- /// \\
- /// On Windows, subscribe to the event to select the slider
- /// represented by the node when the user navigates to it, so that it can receive keyboard input.
+ ///\\
+ /// On Android and Windows, subscribe to the event to select the
+ /// slider represented by the node when the user navigates to it, so that it can receive keyboard input.
///
Slider,
@@ -245,7 +248,6 @@ public enum AccessibilityRole : byte
///\\
/// This role is especially useful in:
///\\
- ///\\
///- Tab groups or sections of a user interface that need distinct boundaries.
///- Navigation bars or toolbars that contain buttons or other controls.
///- Popups, dialogs, or other temporary views.
@@ -258,7 +260,6 @@ public enum AccessibilityRole : byte
/// Container nodes themselves are not directly focusable, but they do provide the screen reader with key
/// information that enhances navigation:
///\\
- ///\\
///- They enable container navigation, which can be activated through the "Containers" <a href="https://support.google.com/accessibility/android/answer/6006598?hl=en#:~:text=Choose%20reading%20controls" >reading control</a> in TalkBack. In this navigation mode, users can move from one container to the next without having to navigate through all the nodes in between.
///- Starting with Android 14 (API level 34), the screen reader may announce when the user enters or exits a container.
///\\
@@ -274,7 +275,6 @@ public enum AccessibilityRole : byte
/// Container nodes are not directly focusable during standard screen reader navigation (called flat navigation
/// on iOS), but they provide essential context for the screen reader:
///\\
- ///\\
///- They enable container navigation, which can be activated through the "Containers" control in the <a href="https://support.apple.com/en-us/111796" >VoiceOver rotor</a>. As on Android, this navigation mode allows users to navigate efficiently between containers.
///- They enable <a href="https://support.apple.com/en-us/guide/iphone/iphfa3d32c50/ios#:~:text=Use%20flat%20or%20grouped%20navigation" >grouped navigation</a>, which can be accessed through the "Navigation Style" control in the VoiceOver rotor. In grouped navigation, container nodes are focusable. When navigating sequentially, the screen reader focuses on the container node directly instead of focusing on its child nodes. To navigate through the container's child nodes, the user must move into the container by performing a dedicated gesture. Once in a container, the user must first move out of it to navigate to nodes outside of the container. This navigation style is particularly useful in complex interfaces, where it simplifies and speeds up navigation.
///- In flat navigation, the screen reader announces the container node's label when the user enters the container by focusing on any of its child nodes. In grouped navigation, the screen reader announces the container node both when entering and when exiting it.
@@ -349,6 +349,9 @@ public enum AccessibilityRole : byte
///- **macOS**: If this role is set on a node, the screen reader announces the node as a "text".
///- **Windows**: If this role is set on a node, the screen reader announces the node as "edit".
///\\
+ /// On Android, subscribe to the event to put the text field into edit
+ /// mode when the user activates it, so that it can receive hardware keyboard input.
+ ///\\
/// On Windows and macOS, subscribe to the event to select the text
/// field represented by the node when the user navigates to it, so that it can receive keyboard input.
///
@@ -360,8 +363,7 @@ public enum AccessibilityRole : byte
///
/// **Platform-specific behavior**
///\\
- ///\\
- ///- **Android**: If this role is set on a node, the screen reader announces the node as a "dropdown list". After a short pause, it provides instructions on how to open it.
+ ///- **Android**: If this role is set on a node, the screen reader announces the node as a "button". After a short pause, it provides instructions on how to open it. If the node has set, the screen reader reads "expanded" before announcing the node's label. Otherwise, it reads "collapsed".
///- **iOS**: This role has no effect.
///- **macOS**: If this role is set on a node, the screen reader announces the node as a "pop up button". After a short pause, it provides instructions on how to open it. If the node has set, the screen reader reads "expanded" after announcing the node's label. Otherwise, it reads "collapsed".
///- **Windows**: If this role is set on a node, the screen reader announces the node as a "combo box". If the node has set, the screen reader reads "expanded" after announcing the node's label. Otherwise, it reads "collapsed".
@@ -386,7 +388,6 @@ public enum AccessibilityRole : byte
///
/// **Platform-specific behavior**
///\\
- ///\\
///- **Android**: If this role is set on a node, the screen reader announces the node as a "button". After a short pause, it provides instructions on how to activate the node.
///- **iOS**: If this role is set on a node and the node's parent has set, the screen reader announces the node as a "tab". Otherwise, it announces the node as a "button".
///- **macOS**: If this role is set on a node, the screen reader announces the node as a "tab". After a short pause, it provides instructions on how to select the node. If the node's parent has set, the screen reader also announces the tab's position in the tab bar and the total number of tabs in it.
@@ -416,7 +417,6 @@ public enum AccessibilityRole : byte
///\\
/// **Platform behavior specific to this role**
///\\
- ///\\
///- **Android**: This role does not affect the node's announcement but provides the screen reader with semantic information about the node.
///- **iOS**: This role does not have any additional effect compared to .
///- **macOS**: If this role is set on a node, the screen reader announces the node as a "scroll area".
@@ -522,11 +522,10 @@ public enum AccessibilityState : byte
///\\
/// **Notes**
///\\
- ///\\
///- This state is only supported for nodes with the role .
///- On macOS, if the role is unset from a node, the screen reader continues to announce the expanded/collapsed state of the node if its new role is compatible with this state. This is a platform limitation.
///\\
- /// **Platform support**: This state has no effect on mobile platforms.
+ /// **Platform support**: This state has no effect on iOS.
///
Expanded = 1 << 2,
}
diff --git a/Modules/Accessibility/Managed/AssistiveSupport.cs b/Modules/Accessibility/Managed/AssistiveSupport.cs
index dbd7965223..b61ec4b193 100644
--- a/Modules/Accessibility/Managed/AssistiveSupport.cs
+++ b/Modules/Accessibility/Managed/AssistiveSupport.cs
@@ -113,15 +113,7 @@ public enum ScreenReaderStatusOverride : byte
/// You can also use to determine whether the screen reader
/// is turned on or off.
///
- ///
- /// **Platform support**: This event is not supported by Narrator, the Windows built-in screen reader.
- ///
///
- ///
- /// The following example demonstrates a potential workaround for polling the status of Narrator and sending a
- /// custom event.
- ///
- ///
public static event Action screenReaderStatusChanged;
static event Action s_ActiveHierarchyChanged;
@@ -167,6 +159,17 @@ internal static event Action activeHierarchyChanged
/// When this property is set, Unity notifies the screen reader of the new hierarchy by calling
/// (with a @@null@@ parameter).
///
+ ///
+ /// **Note**: Only the accessibility hierarchy for the application's main window is supported. Content displayed
+ /// on additional windows, such as on secondary displays, is not exposed to screen readers.
+ ///
+ ///
+ /// **Warning**: Assigning a hierarchy builds its native representation, and setting this property to @@null@@
+ /// tears it down. This has a non-trivial cost on the following platforms:
+ ///\\
+ ///- **iOS**: Switching the active hierarchy has a high cost that scales with the size of the hierarchy. Avoid setting this property frequently in performance-sensitive code.
+ ///- **macOS**: Switching the active hierarchy has a moderate cost that scales with the size of the hierarchy. Doing so frequently can affect performance.
+ ///
///
public static AccessibilityHierarchy activeHierarchy
{
diff --git a/Modules/Accessibility/Managed/Hierarchy/AccessibilityHierarchy.cs b/Modules/Accessibility/Managed/Hierarchy/AccessibilityHierarchy.cs
index d75386c114..15a35a97e1 100644
--- a/Modules/Accessibility/Managed/Hierarchy/AccessibilityHierarchy.cs
+++ b/Modules/Accessibility/Managed/Hierarchy/AccessibilityHierarchy.cs
@@ -60,6 +60,9 @@ namespace UnityEngine.Accessibility
///-
///-
///
+ /// **Note**: Only the accessibility hierarchy for the application's main window is supported. Content displayed on
+ /// additional windows, such as on secondary displays, is not exposed to screen readers.
+ ///
/// SA:
///
///- [[wiki:accessibility|Accessibility for mobile applications]]
@@ -111,27 +114,21 @@ internal event Action changed
internal static int nextUniqueNodeId;
///
- /// The set of all node IDs currently in use across all instances of .
- /// Used to guarantee global ID uniqueness even after wraps around
- /// .
+ /// Weak references to every that has been created and not yet garbage
+ /// collected. The live hierarchies are the source of truth for which node IDs are currently in use, which lets
+ /// guarantee global ID uniqueness even after wraps
+ /// around . Using weak references means a hierarchy that is simply dropped (for
+ /// example during a scene transition) frees its IDs as soon as it is collected, with no finalizer or explicit
+ /// cleanup required.
///
- internal static readonly HashSet usedNodeIds = new();
+ static readonly List> s_LiveHierarchies = new();
///
- /// Finalizer that releases all node IDs back to the global pool when this hierarchy is garbage collected
- /// without having been explicitly cleared. Without this, IDs would accumulate in
- /// permanently for every hierarchy that is created and then simply dropped (e.g. during scene transitions or
- /// in tests), eventually exhausting all available IDs.
+ /// Initializes and returns an empty .
///
- ~AccessibilityHierarchy()
+ public AccessibilityHierarchy()
{
- lock (usedNodeIds)
- {
- foreach (var id in nodes.Keys)
- {
- usedNodeIds.Remove(id);
- }
- }
+ s_LiveHierarchies.Add(new WeakReference(this));
}
///
@@ -245,8 +242,13 @@ public AccessibilityNode InsertNode(int childIndex, string label = null, Accessi
/// different position in the parent's child list.
///
///
- /// **Warning**: The moving operation is costly because many checks have to be executed to guarantee the
- /// integrity of the hierarchy. If this method is called excessively, it might negatively affect performance.
+ /// **Warning**: When this hierarchy is the , this method has a
+ /// non-trivial cost on the following platforms:
+ ///\\
+ ///- **iOS**: Moving a node has a high cost that scales with the size of the subtree being moved. Avoid calling this method frequently in performance-sensitive code.
+ ///- **macOS**: Moving a node has a moderate cost. Calling this method frequently can affect performance.
+ ///\\
+ /// Moving a node in an inactive hierarchy has no native cost.
///
/// The node to move.
/// The new parent of the node, or @@null@@ if the node should be placed at the root
@@ -313,6 +315,15 @@ public bool MoveNode(AccessibilityNode node, AccessibilityNode newParent, int ne
///
/// Removes the node from the accessibility hierarchy and removes or re-parents its descendants.
///
+ ///
+ /// **Warning**: When this hierarchy is the , this method has a
+ /// non-trivial cost on the following platforms:
+ ///\\
+ ///- **iOS**: Removing a node has a high cost that scales with the size of the affected subtree. Avoid calling this method frequently in performance-sensitive code.
+ ///- **macOS**: Removing a node has a moderate cost that scales with the size of the affected subtree. Calling this method frequently can affect performance.
+ ///\\
+ /// Removing a node from an inactive hierarchy has no native cost.
+ ///
/// The node to remove.
/// @@true@@ if the node's descendants should also be removed, or @@false@@ if they
/// should be moved under the node's parent. Defaults to @@true@@.
@@ -333,12 +344,9 @@ public void RemoveNode(AccessibilityNode node, bool removeChildren = true)
if (removeChildren)
{
- var nodeIdsToRemove = new List();
-
void RemoveFromNodes(AccessibilityNode child)
{
nodes.Remove(child.id);
- nodeIdsToRemove.Add(child.id);
foreach (var descendant in child.children)
{
@@ -347,23 +355,10 @@ void RemoveFromNodes(AccessibilityNode child)
}
RemoveFromNodes(node);
-
- lock (usedNodeIds)
- {
- foreach (var nodeId in nodeIdsToRemove)
- {
- usedNodeIds.Remove(nodeId);
- }
- }
}
else
{
nodes.Remove(node.id);
-
- lock (usedNodeIds)
- {
- usedNodeIds.Remove(node.id);
- }
}
if (m_RootNodes.Contains(node))
@@ -385,6 +380,15 @@ void RemoveFromNodes(AccessibilityNode child)
///
/// Resets the hierarchy to an empty state, removing all nodes and the screen reader focus.
///
+ ///
+ /// **Warning**: When this hierarchy is the , this method has a
+ /// non-trivial cost on the following platforms:
+ ///\\
+ ///- **iOS**: Clearing the hierarchy has a high cost that scales with its size. Avoid calling this method frequently in performance-sensitive code.
+ ///- **macOS**: Clearing the hierarchy has a moderate cost that scales with its size. Calling this method frequently can affect performance.
+ ///\\
+ /// Clearing an inactive hierarchy has no native cost.
+ ///
public void Clear()
{
for (var i = m_RootNodes.Count - 1; i >= 0; i--)
@@ -399,14 +403,18 @@ public void Clear()
///
///
/// This is a convenience method that updates the of all nodes in the
- /// accessibility hierarchy (based on ) and notifies the screen
- /// reader of these updates by calling
+ /// accessibility hierarchy based on and notifies the screen reader
+ /// of these updates by calling
/// (with a @@null@@ parameter).
///
///
/// Call this method when most or all of the nodes on the screen require a layout update. For example, when the
/// user scrolls the application's interface, or when the orientation of the screen changes.
///
+ ///
+ /// **Note**: For nodes with no set, this method resets their
+ /// to .
+ ///
///
public void RefreshNodeFrames()
{
@@ -421,6 +429,21 @@ public void RefreshNodeFrames()
}
}
+ internal void RefreshNodeFramesWithoutResetting()
+ {
+ foreach (var node in nodes.Values)
+ {
+ // Set the frame even if it is the same, because it needs to be converted to screen coordinates on the
+ // native side, which could be different if the app window was moved, for example.
+ node.frame = node.frameGetter?.Invoke() ?? node.frame;
+ }
+
+ if (AssistiveSupport.activeHierarchy == this)
+ {
+ AssistiveSupport.notificationDispatcher.SendLayoutChanged();
+ }
+ }
+
///
/// Retrieves the lowest common ancestor of two nodes in the accessibility hierarchy.
///
@@ -503,37 +526,56 @@ void BuildNodeIdStack(AccessibilityNode node, ref Stack nodeS
/// The new node.
AccessibilityNode CreateNode()
{
- // Guard and select the next free ID. Both the count check and the Contains loop must run inside
- // the lock so that a concurrent finalizer Remove() cannot corrupt the HashSet while we read it.
- int nodeId;
+ var startId = nextUniqueNodeId;
- lock (usedNodeIds)
+ // Skip over any IDs that are still in use by a node in a live hierarchy. This is important after
+ // nextUniqueNodeId wraps around int.MaxValue.
+ while (IsNodeIdInUse(nextUniqueNodeId))
{
- if (usedNodeIds.Count >= int.MaxValue)
+ nextUniqueNodeId = nextUniqueNodeId == int.MaxValue ? 0 : nextUniqueNodeId + 1;
+
+ // If we cycle all the way back to where we started, every possible ID is in use and we cannot create
+ // a new node.
+ if (nextUniqueNodeId == startId)
{
throw new InvalidOperationException("Could not create a new accessibility node. A maximum of " +
$"{int.MaxValue} nodes can exist at a time across all hierarchies. Try clearing unused " +
"hierarchies or removing unused nodes.");
}
+ }
- // Skip over any IDs that are still in use by nodes in any hierarchy. This is important after
- // nextUniqueNodeId wraps around int.MaxValue.
- while (usedNodeIds.Contains(nextUniqueNodeId))
- {
- nextUniqueNodeId = nextUniqueNodeId == int.MaxValue ? 0 : nextUniqueNodeId + 1;
- }
+ // Reserve the ID.
+ var nodeId = nextUniqueNodeId;
- // Reserve the ID.
- nodeId = nextUniqueNodeId;
+ // Loop the counter. We do not expect to have that many accessibility nodes at the same time.
+ nextUniqueNodeId = nodeId == int.MaxValue ? 0 : nodeId + 1;
- // Mark this ID as in use.
- usedNodeIds.Add(nodeId);
+ return new AccessibilityNode(nodeId, this);
+ }
- // Loop the counter. We do not expect to have that many accessibility nodes at the same time.
- nextUniqueNodeId = nodeId == int.MaxValue ? 0 : nodeId + 1;
+ ///
+ /// Determines whether the given node ID is currently in use by a node in any live hierarchy. Dead weak
+ /// references encountered along the way are pruned from .
+ ///
+ static bool IsNodeIdInUse(int id)
+ {
+ for (var i = s_LiveHierarchies.Count - 1; i >= 0; i--)
+ {
+ if (s_LiveHierarchies[i].TryGetTarget(out var hierarchy))
+ {
+ if (hierarchy.nodes.ContainsKey(id))
+ {
+ return true;
+ }
+ }
+ else
+ {
+ // The hierarchy has been garbage collected, so its IDs are free again. Prune the dead reference.
+ s_LiveHierarchies.RemoveAt(i);
+ }
}
- return new AccessibilityNode(nodeId, this);
+ return false;
}
AccessibilityNode CreateNodeAndSetParent(int childIndex, string label, AccessibilityNode parent)
diff --git a/Modules/Accessibility/Managed/Hierarchy/AccessibilityNode.cs b/Modules/Accessibility/Managed/Hierarchy/AccessibilityNode.cs
index 2d3ed9aeca..73d450e50d 100644
--- a/Modules/Accessibility/Managed/Hierarchy/AccessibilityNode.cs
+++ b/Modules/Accessibility/Managed/Hierarchy/AccessibilityNode.cs
@@ -341,11 +341,11 @@ public string label
///-
///-
///
- /// On Windows, nodes with the role must have
- /// a value containing a number between 0 and 100 to accurately communicate the scroll percentage
- /// to the screen reader. For scroll views that support both vertical and horizontal scrolling, the value
- /// must contain two numbers, with the vertical scroll percentage listed first.
- /// For example, a value of `50, 75` indicates that the scroll view represented by the node is scrolled 50% vertically and 75% horizontally.
+ /// On Windows, nodes with the role must have a value containing a
+ /// number between 0 and 100 to accurately communicate the scroll percentage to the screen reader. For scroll
+ /// views that support both vertical and horizontal scrolling, the value must contain two numbers, with the
+ /// vertical scroll percentage listed first. For example, a value of `50, 75` indicates that the scroll view
+ /// represented by the node is scrolled 50% vertically and 75% horizontally.
///
///
public string value
diff --git a/Modules/AdaptivePerformance/AssemblyInfo.cs b/Modules/AdaptivePerformance/AssemblyInfo.cs
index e42ce3fa86..e3540765ad 100644
--- a/Modules/AdaptivePerformance/AssemblyInfo.cs
+++ b/Modules/AdaptivePerformance/AssemblyInfo.cs
@@ -10,4 +10,8 @@
[assembly: InternalsVisibleTo("Unity.Modules.AdaptivePerformanceEditor.Tests.TestPackage.Editor")]
[assembly: InternalsVisibleTo("Unity.Modules.AdaptivePerformanceEditor.Tests.Playmode")]
+// Lets the Adaptive Performance package's Visual Scripting bridge forward internal events
+// (e.g. AdaptivePerformanceIndexer.ScalerLevelChanged) to the Visual Scripting EventBus.
+[assembly: InternalsVisibleTo("Unity.AdaptivePerformance")]
+
diff --git a/Modules/AdaptivePerformance/Core/AdaptivePerformanceInit.cs b/Modules/AdaptivePerformance/Core/AdaptivePerformanceInit.cs
index b19b3bad0e..68446dab0b 100644
--- a/Modules/AdaptivePerformance/Core/AdaptivePerformanceInit.cs
+++ b/Modules/AdaptivePerformance/Core/AdaptivePerformanceInit.cs
@@ -2,12 +2,14 @@
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.Scripting;
namespace UnityEngine.AdaptivePerformance
{
- internal static class AdaptivePerformanceInitializer
+ internal static partial class AdaptivePerformanceInitializer
{
+ [AutoStaticsCleanupOnCodeReload]
static AdaptivePerformanceManagerSpawner s_Spawner;
[RequiredByNativeCode(optional: false)]
diff --git a/Modules/AdaptivePerformance/Core/AdaptiverPerformanceLog.cs b/Modules/AdaptivePerformance/Core/AdaptiverPerformanceLog.cs
index 9fc45a97b2..ca7187607d 100644
--- a/Modules/AdaptivePerformance/Core/AdaptiverPerformanceLog.cs
+++ b/Modules/AdaptivePerformance/Core/AdaptiverPerformanceLog.cs
@@ -3,12 +3,15 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Text;
+using Unity.Scripting.LifecycleManagement;
namespace UnityEngine.AdaptivePerformance
{
internal static class APLog
{
+ [NoAutoStaticsCleanup] // logging toggle, set externally
public static bool enabled = false;
+ [NoAutoStaticsCleanup] // reusable string-building buffer, populated fresh each log call
public static readonly StringBuilder s_LogBuilder = new StringBuilder(512);
static readonly string s_AdaptivePerformancePrefix = "[Adaptive Performance] ";
public static void Debug(string format, params object[] args)
diff --git a/Modules/AdaptivePerformance/IAdaptivePerformance.cs b/Modules/AdaptivePerformance/IAdaptivePerformance.cs
index 348bd25add..67a804a8b3 100644
--- a/Modules/AdaptivePerformance/IAdaptivePerformance.cs
+++ b/Modules/AdaptivePerformance/IAdaptivePerformance.cs
@@ -3,6 +3,7 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.ComponentModel;
+using Unity.Scripting.LifecycleManagement;
namespace UnityEngine.AdaptivePerformance
{
@@ -197,8 +198,9 @@ public interface IAdaptivePerformance
/// }
/// ]]>
///
- public static class Holder
+ public static partial class Holder
{
+ [AutoStaticsCleanupOnCodeReload]
static IAdaptivePerformance m_Instance;
///
@@ -371,6 +373,7 @@ public static void Deinitialize()
/// }
///
///
+ [AutoStaticsCleanupOnCodeReload]
public static event LifecycleEventHandler LifecycleEventHandler;
}
diff --git a/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceIndexer.cs b/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceIndexer.cs
index 30ad9dd0ee..e4eb1eb1e6 100644
--- a/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceIndexer.cs
+++ b/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceIndexer.cs
@@ -241,6 +241,16 @@ public class AdaptivePerformanceIndexer
///
public StateAction PerformanceAction { get; private set; }
+ // Raised when the indexer changes a registered scaler's level (increase or decrease).
+ // Internal so the Visual Scripting bridge in the Adaptive Performance package can forward it
+ // to the Visual Scripting EventBus without expanding the public engine API.
+ internal event System.Action ScalerLevelChanged;
+
+ internal void NotifyScalerLevelChanged(AdaptivePerformanceScaler scaler)
+ {
+ ScalerLevelChanged?.Invoke(scaler);
+ }
+
///
/// Returns all currently applied scalers.
///
diff --git a/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceRenderSettings.cs b/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceRenderSettings.cs
index 26904b5ca0..e5b421362d 100644
--- a/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceRenderSettings.cs
+++ b/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceRenderSettings.cs
@@ -4,6 +4,7 @@
using System.Collections;
using System.Collections.Generic;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
namespace UnityEngine.AdaptivePerformance
@@ -14,9 +15,13 @@ namespace UnityEngine.AdaptivePerformance
///
public static class AdaptivePerformanceRenderSettings
{
+ [NoAutoStaticsCleanup] // render quality multiplier actively managed by the scaler system
private static float s_MaxShadowDistanceMultiplier = 1;
+ [NoAutoStaticsCleanup] // render quality multiplier actively managed by the scaler system
private static float s_ShadowResolutionMultiplier = 1;
+ [NoAutoStaticsCleanup] // render quality multiplier actively managed by the scaler system
private static float s_RenderScaleMultiplier = 1;
+ [NoAutoStaticsCleanup] // render quality value actively managed by the scaler system
private static float s_DecalsMaxDistance = 1000;
///
@@ -40,6 +45,7 @@ public static float DecalsDrawDistance
///
/// Adjust the number of shadow cascades for the main camera in the scene.
///
+ [NoAutoStaticsCleanup] // render quality setting actively managed by the scaler system
public static int MainLightShadowCascadesCountBias
{
get;
@@ -49,6 +55,7 @@ public static int MainLightShadowCascadesCountBias
///
/// Adjust the quality setting of shadows.
///
+ [NoAutoStaticsCleanup] // render quality setting actively managed by the scaler system
public static int ShadowQualityBias
{
get;
@@ -57,6 +64,7 @@ public static int ShadowQualityBias
///
/// Adjust the size of lookup tables that are used for color grading.
///
+ [NoAutoStaticsCleanup] // render quality setting actively managed by the scaler system
public static float LutBias
{
get;
@@ -81,6 +89,7 @@ public static float RenderScaleMultiplier
///
/// Adjust the quality of MSAA.
///
+ [NoAutoStaticsCleanup] // render quality setting actively managed by the scaler system
public static int AntiAliasingQualityBias
{
get;
@@ -102,6 +111,7 @@ public static bool SkipDynamicBatching
/// When enabled, there is a higher load on the CPU but less rendering overdraw.
/// When disabled, there is less CPU utilization but more overdraw.
///
+ [NoAutoStaticsCleanup] // render quality setting actively managed by the scaler system
public static bool SkipFrontToBackSorting
{
get;
@@ -112,6 +122,7 @@ public static bool SkipFrontToBackSorting
/// Whether transparent objects should be rendered
/// When enabled, there is less rendering overdraw, but entire objects can disappear.
///
+ [NoAutoStaticsCleanup] // render quality setting actively managed by the scaler system
public static bool SkipTransparentObjects
{
get;
diff --git a/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceScaler.cs b/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceScaler.cs
index ba6405e81a..3ffd471dea 100644
--- a/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceScaler.cs
+++ b/Modules/AdaptivePerformance/Indexer/AdaptivePerformanceScaler.cs
@@ -4,7 +4,6 @@
using UnityEngine.Scripting;
-
namespace UnityEngine.AdaptivePerformance
{
///
@@ -319,6 +318,7 @@ internal void IncreaseLevel()
CurrentLevel++;
OnLevelIncrease();
OnLevel();
+ m_Indexer?.NotifyScalerLevelChanged(this);
}
internal void DecreaseLevel()
@@ -331,6 +331,7 @@ internal void DecreaseLevel()
CurrentLevel--;
OnLevelDecrease();
OnLevel();
+ m_Indexer?.NotifyScalerLevelChanged(this);
}
internal void Activate()
diff --git a/Modules/AdaptivePerformance/Management/AdaptivePerformanceGeneralSettings.cs b/Modules/AdaptivePerformance/Management/AdaptivePerformanceGeneralSettings.cs
index 9ac60abdab..b3dcbd6b40 100644
--- a/Modules/AdaptivePerformance/Management/AdaptivePerformanceGeneralSettings.cs
+++ b/Modules/AdaptivePerformance/Management/AdaptivePerformanceGeneralSettings.cs
@@ -2,6 +2,7 @@
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
@@ -10,10 +11,12 @@ namespace UnityEngine.AdaptivePerformance
///
/// A `ScriptableObject` that contains global settings applicable to all Adaptive Performance providers.
///
- public class AdaptivePerformanceGeneralSettings : ScriptableObject
+ public partial class AdaptivePerformanceGeneralSettings : ScriptableObject
{
/// The key used to query to get the current loader settings.
+ [NoAutoStaticsCleanup] // public API field; readonly would be a source-breaking change
public static string k_SettingsKey = "com.unity.adaptiveperformance.loader_settings";
+ [AutoStaticsCleanupOnCodeReload]
internal static AdaptivePerformanceGeneralSettings s_RuntimeSettingsInstance = null;
[SerializeField]
diff --git a/Modules/AdaptivePerformance/Management/AdaptivePerformanceManagerSettings.cs b/Modules/AdaptivePerformance/Management/AdaptivePerformanceManagerSettings.cs
index e821306edc..23bf6297b0 100644
--- a/Modules/AdaptivePerformance/Management/AdaptivePerformanceManagerSettings.cs
+++ b/Modules/AdaptivePerformance/Management/AdaptivePerformanceManagerSettings.cs
@@ -6,6 +6,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
+using Unity.Scripting.LifecycleManagement;
[assembly: InternalsVisibleTo("Unity.AdaptivePerformance.Tests")]
[assembly: InternalsVisibleTo("Unity.AdaptivePerformance.Editor.Tests")]
@@ -37,7 +38,7 @@ namespace UnityEngine.AdaptivePerformance
/// * OnDisable calls internally. Ask the active loader to stop all subsystems.
/// * OnDestroy calls internally. Deinitialize and remove the active loader.
///
- public sealed class AdaptivePerformanceManagerSettings : ScriptableObject
+ public sealed partial class AdaptivePerformanceManagerSettings : ScriptableObject
{
[HideInInspector]
bool m_InitializationComplete = false;
@@ -99,6 +100,7 @@ public bool isInitializationComplete
}
[HideInInspector]
+ [AutoStaticsCleanupOnCodeReload]
static AdaptivePerformanceLoader s_ActiveLoader = null;
///
diff --git a/Modules/AdaptivePerformance/Management/IAdaptivePerformanceSettings.cs b/Modules/AdaptivePerformance/Management/IAdaptivePerformanceSettings.cs
index 5eaacaf14b..a21e3b5f0c 100644
--- a/Modules/AdaptivePerformance/Management/IAdaptivePerformanceSettings.cs
+++ b/Modules/AdaptivePerformance/Management/IAdaptivePerformanceSettings.cs
@@ -7,6 +7,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
+using Unity.Scripting.LifecycleManagement;
//using UnityEditor;
using UnityEngine;
using UnityEngine.Bindings;
@@ -555,6 +556,7 @@ public IReadOnlyList DefaultScalerSetting
}
}
+ [NoAutoStaticsCleanup] // fixed compile-time list of built-in scaler types, never changes
internal static readonly List k_DefaultScalerNames = new List
{
typeof(UnityEngine.AdaptivePerformance.AdaptiveFramerate),
diff --git a/Modules/AdaptivePerformance/Profiler/AdaptivePerformanceProfilerStats.cs b/Modules/AdaptivePerformance/Profiler/AdaptivePerformanceProfilerStats.cs
index 28778b59e4..55783688f8 100644
--- a/Modules/AdaptivePerformance/Profiler/AdaptivePerformanceProfilerStats.cs
+++ b/Modules/AdaptivePerformance/Profiler/AdaptivePerformanceProfilerStats.cs
@@ -10,6 +10,7 @@
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using Unity.Profiling.LowLevel.Unsafe;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.Profiling;
using Unity.Collections.LowLevel.Unsafe;
@@ -84,62 +85,77 @@ private static byte GetProfilerMarkerDataType()
///
/// Profiler counter to report cpu frametime.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker CurrentCPUMarker = new CustomProfilerMarker("CPU frametime", ProfilerMarkerDataUnit.TimeNanoseconds);
///
/// Profiler counter to report cpu average frametime.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker AvgCPUMarker = new CustomProfilerMarker("CPU avg frametime", ProfilerMarkerDataUnit.TimeNanoseconds);
///
/// Profiler counter to report gpu frametime.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker CurrentGPUMarker = new CustomProfilerMarker("GPU frametime", ProfilerMarkerDataUnit.TimeNanoseconds);
///
/// Profiler counter to report gpu average frametime.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker AvgGPUMarker = new CustomProfilerMarker("GPU avg frametime", ProfilerMarkerDataUnit.TimeNanoseconds);
///
/// Profiler counter to report cpu performance level.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker CurrentCPULevelMarker = new CustomProfilerMarker("CPU performance level", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report gpu performance level.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker CurrentGPULevelMarker = new CustomProfilerMarker("GPU performance level", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report frametime.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker CurrentFrametimeMarker = new CustomProfilerMarker("Frametime", ProfilerMarkerDataUnit.TimeNanoseconds);
///
/// Profiler counter to report average frametime.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker AvgFrametimeMarker = new CustomProfilerMarker("Avg frametime", ProfilerMarkerDataUnit.TimeNanoseconds);
///
/// Profiler counter to report the thermal warning level.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker WarningLevelMarker = new CustomProfilerMarker("Thermal Warning Level", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report the temperature level.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker TemperatureLevelMarker = new CustomProfilerMarker("Temperature Level", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report the temperature trend.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker TemperatureTrendMarker = new CustomProfilerMarker("Temperature Trend", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report the bottleneck.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker BottleneckMarker = new CustomProfilerMarker("Bottleneck", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report the performance mode.
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker PerformanceModeMarker = new CustomProfilerMarker("Performance Mode", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report the CPU utilization (normalized 0-1).
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker CpuUtilizationMarker = new CustomProfilerMarker("CPU Utilization", ProfilerMarkerDataUnit.Count);
///
/// Profiler counter to report the GPU utilization (normalized 0-1).
///
+ [NoAutoStaticsCleanup] // public API field; profiler counter initialized once at startup
public static CustomProfilerMarker GpuUtilizationMarker = new CustomProfilerMarker("GPU Utilization", ProfilerMarkerDataUnit.Count);
///
@@ -154,7 +170,9 @@ private static byte GetProfilerMarkerDataType()
const int kMaxScalerNameSizeInBytes = 320;
+ [NoAutoStaticsCleanup] // per-frame profiler buffer, populated fresh each frame
static List scalerInfos = new List();
+ [NoAutoStaticsCleanup] // per-frame profiler buffer index, populated fresh each frame
static Dictionary scalerInfosIndex = new Dictionary();
///
diff --git a/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderLoader.cs b/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderLoader.cs
index fdf10a55ea..2a85358c11 100644
--- a/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderLoader.cs
+++ b/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderLoader.cs
@@ -4,6 +4,7 @@
using UnityEngine;
using System.Collections.Generic;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.AdaptivePerformance;
using UnityEngine.AdaptivePerformance.Basic;
using UnityEngine.AdaptivePerformance.Provider;
@@ -18,6 +19,7 @@ namespace UnityEngine.AdaptivePerformance.Basic
[VisibleToOtherModules("UnityEditor.AdaptivePerformanceModule")]
internal class BasicProviderLoader : AdaptivePerformanceLoaderHelper
{
+ [NoAutoStaticsCleanup] // populated by native subsystem registration, not C# state
static List s_BasicSubsystemDescriptors =
new List();
diff --git a/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderSettings.cs b/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderSettings.cs
index 97aec36077..c7b58331ed 100644
--- a/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderSettings.cs
+++ b/Modules/AdaptivePerformance/Provider/BasicProvider/BasicProviderSettings.cs
@@ -2,6 +2,7 @@
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
using UnityEngine.AdaptivePerformance;
@@ -12,8 +13,9 @@ namespace UnityEngine.AdaptivePerformance.Basic
///
[System.Serializable]
[AdaptivePerformanceConfigurationData("Basic", BasicProviderConstants.k_SettingKey)]
- public class BasicProviderSettings: IAdaptivePerformanceSettings
+ public partial class BasicProviderSettings: IAdaptivePerformanceSettings
{
+ [AutoStaticsCleanupOnCodeReload]
static BasicProviderSettings m_Instance = null;
void Awake()
{
diff --git a/Modules/AdaptivePerformance/Scalers/AdaptiveResolution.cs b/Modules/AdaptivePerformance/Scalers/AdaptiveResolution.cs
index a64791cb29..cb512aab3b 100644
--- a/Modules/AdaptivePerformance/Scalers/AdaptiveResolution.cs
+++ b/Modules/AdaptivePerformance/Scalers/AdaptiveResolution.cs
@@ -2,6 +2,7 @@
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.Rendering;
namespace UnityEngine.AdaptivePerformance
@@ -12,6 +13,7 @@ namespace UnityEngine.AdaptivePerformance
///
public class AdaptiveResolution : AdaptivePerformanceScaler
{
+ [NoAutoStaticsCleanup] // instance counter maintained via Start/OnDestroy lifecycle
static int instanceCount = 0;
///
diff --git a/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfo.cs b/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfo.cs
index 7bb3d36da4..46b3881850 100644
--- a/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfo.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfo.cs
@@ -5,7 +5,7 @@
using System;
using System.Collections.Generic;
using System.IO;
-
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.AdaptivePerformance;
namespace UnityEditor.AdaptivePerformance.Editor
@@ -37,7 +37,7 @@ public bool Equals(AdaptivePerformanceLoaderInfo other)
return other != null && Equals(loaderType, other.loaderType) && Equals(instance, other.instance);
}
- static string[] s_LoaderblockList = { "DummyLoader", "SampleLoader", "AdaptivePerformanceLoaderHelper" };
+ static readonly string[] s_LoaderblockList = { "DummyLoader", "SampleLoader", "AdaptivePerformanceLoaderHelper" };
internal static void GetAllKnownLoaderInfos(List newInfos)
{
diff --git a/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfoManager.cs b/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfoManager.cs
index f811cca5ef..4d30caf74f 100644
--- a/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfoManager.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceLoaderInfoManager.cs
@@ -5,20 +5,23 @@
using System;
using System.Collections.Generic;
using System.IO;
-
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.AdaptivePerformance;
namespace UnityEditor.AdaptivePerformance.Editor
{
- internal class AdaptivePerformanceLoaderInfoManager : IAdaptivePerformanceLoaderOrderManager
+ internal partial class AdaptivePerformanceLoaderInfoManager : IAdaptivePerformanceLoaderOrderManager
{
// Simple class to give us updates when the asset database changes.
- internal class AssetCallbacks : AssetPostprocessor
+ internal partial class AssetCallbacks : AssetPostprocessor
{
+ [AutoStaticsCleanup]
static bool s_EditorUpdatable = false;
+ [AutoStaticsCleanup]
internal static System.Action Callback { get; set; }
- static AssetCallbacks()
+ [OnCodeLoaded]
+ static void Initialize()
{
if (!s_EditorUpdatable)
{
diff --git a/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceSettingsManager.cs b/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceSettingsManager.cs
index 412096ee00..831b0dd22f 100644
--- a/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceSettingsManager.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/AdaptivePerformanceSettingsManager.cs
@@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using Unity.Scripting.LifecycleManagement;
using UnityEditor.AdaptivePerformance.Editor.Metadata;
using UnityEditor.PackageManager;
using UnityEngine;
@@ -13,9 +14,10 @@
namespace UnityEditor.AdaptivePerformance.Editor
{
- class AdaptivePerformanceSettingsManager : SettingsProvider
+ partial class AdaptivePerformanceSettingsManager : SettingsProvider
{
const string k_WarningPlaymodePopup = "Adaptive Performance settings cannot be changed while the Editor is in Play mode.";
+ const string k_WarningPackageOperationPopup = "Adaptive Performance is updating its packages. Settings are temporarily unavailable until the operation finishes.";
struct Content
{
@@ -26,13 +28,21 @@ struct Content
public static readonly GUIContent k_FrameTimingExplanatoryText = new GUIContent(L10n.Tr("Please enable Frame Timing Stats in the Player Settings. Adaptive Performance requires precise frame time information."));
}
- internal static string s_SettingsRootTitle = $"Project/{AdaptivePerformanceConstants.kAdaptivePerformanceProviderManagement}";
+ internal static readonly string s_SettingsRootTitle = $"Project/{AdaptivePerformanceConstants.kAdaptivePerformanceProviderManagement}";
+ [AutoStaticsCleanup]
static AdaptivePerformanceSettingsManager s_SettingsManager = null;
+ [NoAutoStaticsCleanup] // UI state flag, refreshed from settings on each OnGUI call
static bool s_EnableAdaptivePerformance = false;
internal static AdaptivePerformanceSettingsManager Instance => s_SettingsManager;
+ // Guards the get-or-create of the general settings config object. A dedicated object rather than
+ // Instance: the provider instance is null until Create() runs (and is cleared again on statics
+ // cleanup), so locking on it both threw ArgumentNullException and changed identity across reloads.
+ [NoAutoStaticsCleanup]
+ static readonly object s_CurrentSettingsLock = new object();
+
static AdaptivePerformanceGeneralSettingsPerBuildTarget currentSettings
{
get
@@ -41,7 +51,7 @@ static AdaptivePerformanceGeneralSettingsPerBuildTarget currentSettings
EditorBuildSettings.TryGetConfigObject(AdaptivePerformanceGeneralSettings.k_SettingsKey, out generalSettings);
if (generalSettings == null && s_EnableAdaptivePerformance)
{
- lock (AdaptivePerformanceSettingsManager.Instance)
+ lock (s_CurrentSettingsLock)
{
EditorBuildSettings.TryGetConfigObject(AdaptivePerformanceGeneralSettings.k_SettingsKey, out generalSettings);
if (generalSettings == null)
@@ -314,7 +324,9 @@ void DisplayEnableToggle()
if (EditorApplication.isPlayingOrWillChangePlaymode)
EditorGUILayout.HelpBox(L10n.Tr(k_WarningPlaymodePopup), MessageType.Warning);
- using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode))
+ else if (EditorUtilities.IsPackageOperationInProgress)
+ EditorGUILayout.HelpBox(L10n.Tr(k_WarningPackageOperationPopup), MessageType.Info);
+ using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode || EditorUtilities.IsPackageOperationInProgress))
{
s_EnableAdaptivePerformance = EditorGUILayout.Toggle("Enable Adaptive Performance", s_EnableAdaptivePerformance);
}
diff --git a/Modules/AdaptivePerformanceEditor/Management/EditorUtilities.cs b/Modules/AdaptivePerformanceEditor/Management/EditorUtilities.cs
index a0feb553b9..871bd1a3cb 100644
--- a/Modules/AdaptivePerformanceEditor/Management/EditorUtilities.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/EditorUtilities.cs
@@ -7,14 +7,17 @@
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
+using Unity.Scripting.LifecycleManagement;
using UnityEditor.Build.Profile;
using UnityEditor.PackageManager;
+using UnityEditor.PackageManager.Requests;
using UnityEngine;
using UnityEngine.AdaptivePerformance;
using UnityEngine.Assemblies;
namespace UnityEditor.AdaptivePerformance.Editor
{
+ [InitializeOnLoad]
internal static class EditorUtilities
{
internal static readonly string[] s_DefaultGeneralSettingsPath = {"Adaptive Performance"};
@@ -431,20 +434,89 @@ internal static AdaptivePerformanceGeneralSettings GetSettingsOrBuildProfilesSet
return settings;
}
+ // Toggling Adaptive Performance adds or removes the built-in module package, which triggers an
+ // asynchronous package resolution and domain reload. Interacting with the settings or entering Play
+ // mode while that operation is in flight corrupts state (mismatched DefaultScenario state, duplicate
+ // ScriptableSingletons, missing script references), so we track the pending operation to gate the
+ // settings UI and to veto Play mode entry until it completes.
+ // Resetting this on a Play mode transition would drop the gate while the operation is still resolving,
+ // which is exactly what it exists to prevent. MonitorPackageRequest clears it on completion, and the
+ // package operation itself ends in a domain reload that discards it.
+ [NoAutoStaticsCleanup]
+ static Func s_PendingPackageOperation;
+
+ const string k_WarningPlaymodeDuringPackageOperation =
+ "Adaptive Performance is updating its packages. Wait for the operation to finish before entering Play mode.";
+
+ static EditorUtilities()
+ {
+ EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
+ }
+
+ // True while an Adaptive Performance enable/disable package operation (and its domain reload) is still resolving.
+ internal static bool IsPackageOperationInProgress => s_PendingPackageOperation?.Invoke() ?? false;
+
+ static void OnPlayModeStateChanged(PlayModeStateChange state)
+ {
+ // ExitingEditMode is the last point at which Play mode entry can be cancelled. Block it while a
+ // package operation is still resolving to avoid entering Play mode mid domain reload.
+ if (state != PlayModeStateChange.ExitingEditMode || !IsPackageOperationInProgress)
+ return;
+
+ Debug.LogWarning(L10n.Tr(k_WarningPlaymodeDuringPackageOperation));
+ EditorApplication.isPlaying = false;
+ }
+
internal static void EnableAPModule(bool enable)
{
var packageID = "com.unity.modules.adaptiveperformance";
if (enable)
{
- Client.Add(packageID);
+ TrackPackageRequest(Client.Add(packageID));
}
else
{
var settings = EditorUtilities.GetSettingsOrBuildProfilesSettings();
if (settings == null)
- Client.Remove(packageID); // neither classic platforms (Settings) nor build profiles are enabled
+ TrackPackageRequest(Client.Remove(packageID)); // neither classic platforms (Settings) nor build profiles are enabled
}
}
+
+ internal static void TrackPackageRequest(Request request)
+ {
+ // Gate the settings UI on the request until UPM reports it complete.
+ TrackPackageOperation(() => request != null && !request.IsCompleted);
+ }
+
+ // Tracks an arbitrary "still in progress" predicate. Separated from TrackPackageRequest so the
+ // gating and cleanup logic can be exercised without a live UnityEditor.PackageManager request,
+ // whose completion state cannot be faked.
+ internal static void TrackPackageOperation(Func isInProgress)
+ {
+ s_PendingPackageOperation = isInProgress;
+ EditorApplication.update -= MonitorPackageRequest;
+ EditorApplication.update += MonitorPackageRequest;
+ }
+
+ internal static void MonitorPackageRequest()
+ {
+ bool inProgress;
+ try
+ {
+ inProgress = IsPackageOperationInProgress;
+ }
+ catch (Exception ex)
+ {
+ Debug.LogException(ex);
+ inProgress = false;
+ }
+
+ if (inProgress)
+ return;
+
+ s_PendingPackageOperation = null;
+ EditorApplication.update -= MonitorPackageRequest;
+ }
}
}
diff --git a/Modules/AdaptivePerformanceEditor/Management/EditorWorkQueue.cs b/Modules/AdaptivePerformanceEditor/Management/EditorWorkQueue.cs
index f6814f4180..e738113364 100644
--- a/Modules/AdaptivePerformanceEditor/Management/EditorWorkQueue.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/EditorWorkQueue.cs
@@ -5,7 +5,7 @@
using System;
using System.Collections.Generic;
using System.IO;
-
+using Unity.Scripting.LifecycleManagement;
using UnityEditor;
using UnityEngine;
@@ -22,7 +22,7 @@ internal static bool SessionStateHasStoredData(string queueName)
}
}
- internal class EditorWorkQueue : EditorWorkQueueBase
+ internal partial class EditorWorkQueue : EditorWorkQueueBase
{
[Serializable]
struct Queue
@@ -33,6 +33,7 @@ struct Queue
public string QueueName { get; set; }
+ [AutoStaticsCleanup]
private static Lazy> s_Instance = new Lazy>();
public static EditorWorkQueue Instance => s_Instance.Value;
diff --git a/Modules/AdaptivePerformanceEditor/Management/EnterNamePopup.cs b/Modules/AdaptivePerformanceEditor/Management/EnterNamePopup.cs
index d4e142707a..3047a764d4 100644
--- a/Modules/AdaptivePerformanceEditor/Management/EnterNamePopup.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/EnterNamePopup.cs
@@ -16,8 +16,8 @@ class EnterNamePopup : PopupWindowContent
private string m_NewProfileName = "New Scaler Profile";
private bool m_NeedsFocus = true;
private List existingProfileNames = new List();
- static string s_WarningPopup = L10n.Tr("Warning");
- static string s_WarningPopupOption = L10n.Tr("Ok");
+ static readonly string s_WarningPopup = L10n.Tr("Warning");
+ static readonly string s_WarningPopupOption = L10n.Tr("Ok");
const int k_maxChars = 256;
static readonly string k_ErrorMessageLength = string.Format(L10n.Tr("Scaler profile name is too long (maximum {0} characters)"), k_maxChars);
diff --git a/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformanceKnownPackages.cs b/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformanceKnownPackages.cs
index 071984b3cf..558e2c14d3 100644
--- a/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformanceKnownPackages.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformanceKnownPackages.cs
@@ -4,12 +4,12 @@
using System;
using System.Collections.Generic;
-
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
namespace UnityEditor.AdaptivePerformance.Editor.Metadata
{
- internal class AdaptivePerformanceKnownPackages
+ internal partial class AdaptivePerformanceKnownPackages
{
class KnownLoaderMetadata : IAdaptivePerformanceLoaderMetadata
{
@@ -36,6 +36,7 @@ class KnownPackage : IAdaptivePerformancePackage
public bool PopulateNewSettingsInstance(ScriptableObject obj) { return true; }
}
+ [AutoStaticsCleanup]
private static Lazy> s_KnownPackages = new Lazy>(InitKnownPackages);
internal static List Packages => s_KnownPackages.Value;
@@ -177,6 +178,29 @@ static List InitKnownPackages()
}
}
});
+
+ packages.Add(new KnownPackage() {
+ metadata = new KnownPackageMetadata(){
+ packageName = "Adaptive Performance Meta OpenXR",
+ packageId = "com.unity.xr.meta-openxr",
+ settingsType = "UnityEngine.XR.OpenXR.Features.Meta.MetaOpenXRAdaptivePerformanceProviderSettings",
+ licenseURL = "https://docs.unity3d.com/Packages/com.unity.xr.meta-openxr@latest?subfolder=/license/LICENSE.html",
+ isDefaultPlatformProvider = "false",
+ isDeprecated = "false",
+ loaderMetadata = new List()
+ {
+ new KnownLoaderMetadata() {
+ loaderName = "Meta OpenXR Provider",
+ loaderType = "UnityEngine.XR.OpenXR.Features.Meta.MetaOpenXRAdaptivePerformanceProviderLoader",
+ supportedBuildTargets = new List()
+ {
+ BuildTargetGroup.Android
+ },
+ priority = 2,
+ },
+ }
+ }
+ });
return packages;
}
}
diff --git a/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformancePackageMetadata.cs b/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformancePackageMetadata.cs
index 02a0df0e9d..303c54440b 100644
--- a/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformancePackageMetadata.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/Metadata/AdaptivePerformancePackageMetadata.cs
@@ -5,6 +5,7 @@
using System;
using System.Collections.Generic;
using System.IO;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
@@ -113,7 +114,7 @@ public interface IAdaptivePerformancePackageMetadata
/// Provide access to the metadata store. Currently only usable as a way to assign and remove loaders
/// to or from an instance.
///
- public class AdaptivePerformancePackageMetadataStore
+ public partial class AdaptivePerformancePackageMetadataStore
{
const string k_WaitingPackmanQuery = "APMGT Waiting Packman Query.";
const string k_RebuildCache = "APMGT Rebuilding Cache.";
@@ -122,8 +123,10 @@ public class AdaptivePerformancePackageMetadataStore
const string k_UninstallingPackage = "APMGT Uninstalling Adaptive Performance Package.";
const string k_CachedMDStoreKey = "Adaptive Performance Metadata Store";
- static float k_TimeOutDelta = 30f;
+ const float k_TimeOutDelta = 30f;
+ [AutoStaticsCleanup]
static bool s_KnowPackageInitialized = false;
+ [AutoStaticsCleanup]
static bool s_EnableLogging = false;
@@ -144,6 +147,7 @@ struct CachedMDStoreInformation
public string[] installablePackages;
}
+ [AutoStaticsCleanup]
static CachedMDStoreInformation s_CachedMDStoreInformation = new CachedMDStoreInformation()
{
hasAlreadyRequestedData = false,
@@ -221,8 +225,11 @@ struct LoaderAssignmentRequests
public List activeRequests;
}
+ [AutoStaticsCleanup]
static List m_AddRequests = new List();
+ [AutoStaticsCleanup]
static Dictionary s_Packages = new Dictionary();
+ [AutoStaticsCleanup]
static SearchRequest s_SearchRequest = null;
const string k_DefaultSessionStateString = "AP_DEFAULT_SESSION_STATE";
@@ -566,7 +573,8 @@ internal static void InitKnownPluginPackages()
}
}
- static AdaptivePerformancePackageMetadataStore()
+ [OnCodeLoaded]
+ static void Initialize()
{
EditorApplication.playModeStateChanged += PlayModeStateChanged;
if (IsEditorInPlayMode())
diff --git a/Modules/AdaptivePerformanceEditor/Management/ProviderSettingsEditor.cs b/Modules/AdaptivePerformanceEditor/Management/ProviderSettingsEditor.cs
index 4a67a18279..c3e226744d 100644
--- a/Modules/AdaptivePerformanceEditor/Management/ProviderSettingsEditor.cs
+++ b/Modules/AdaptivePerformanceEditor/Management/ProviderSettingsEditor.cs
@@ -29,47 +29,47 @@ public class ProviderSettingsEditor : UnityEditor.Editor
const string k_IndexerPerformanceActionDelay = "m_PerformanceActionDelay";
const string k_ScalerProfileList = "m_scalerProfileList";
- static GUIContent s_LoggingLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Logging"), L10n.Tr("Only active in development mode."));
- static GUIContent s_AutomaticPerformanceModeEnabledLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Auto Performance Mode"), L10n.Tr("Auto Performance Mode controls performance by changing CPU and GPU levels."));
- static GUIContent s_AutomaticGameModeEnabledLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Auto Game Mode"), L10n.Tr("Auto Game Mode controls performance by changing target FPS based on device GameMode settings."));
- static GUIContent s_EnableBoostOnStartupLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Boost mode on startup"), L10n.Tr("Enables the CPU and GPU boost mode before engine startup to decrease startup time."));
- static GUIContent s_StatsLoggingFrequencyInFramesLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Logging Frequency"), L10n.Tr("Changes the logging frequency."));
- static GUIContent s_IndexerActiveLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Active"), L10n.Tr("Is indexer enabled."));
- static GUIContent s_IndexerThermalActionDelayLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Thermal Action Delay"), L10n.Tr("Delay after any scaler is applied or unapplied because of thermal state."));
- static GUIContent s_IndexerPerformanceActionDelayLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Performance Action Delay"), L10n.Tr("Delay after any scaler is applied or unapplied because of performance state."));
-
- static GUIContent s_ScalerScale = EditorGUIUtility.TrTextContent(L10n.Tr("Scale"), L10n.Tr("Scale to control the quality impact for the scaler. No quality change when 1, improved quality when >1, and lowered quality when <1"));
- static GUIContent s_ScalerVisualImpact = EditorGUIUtility.TrTextContent(L10n.Tr("Visual Impact"), L10n.Tr("Visual impact the scaler has on the application. The higher the more impact the scaler has on the visuals."));
- static GUIContent s_ScalerTarget = EditorGUIUtility.TrTextContent(L10n.Tr("Target"), L10n.Tr("Target for the scaler of the application bottleneck. The target selected has the most impact on the quality control of this scaler. Can only be overriden via API."));
- static GUIContent s_ScalerMaxLevel = EditorGUIUtility.TrTextContent(L10n.Tr("Max Level"), L10n.Tr("Maximum level for the scaler. This is tied to the implementation of the scaler to divide the levels into concrete steps."));
- static GUIContent s_ScalerMinBound = EditorGUIUtility.TrTextContent(L10n.Tr("Min Scale"), L10n.Tr("Minimum value for the scale boundary."));
- static GUIContent s_ScalerMaxBound = EditorGUIUtility.TrTextContent(L10n.Tr("Max Scale"), L10n.Tr("Maximum value for the scale boundary."));
-
- static GUIContent s_AdaptiveFramerate = EditorGUIUtility.TrTextContent(L10n.Tr("Framerate"), L10n.Tr("Adaptive Framerate enables you to automatically control the application's framerate by the defined minimum and maximum framerate. It uses Application.targetFramerate to control the framerate for your application."));
- static GUIContent s_AdaptiveResolution = EditorGUIUtility.TrTextContent(L10n.Tr("Resolution"), L10n.Tr("Adaptive Resolution enables you to automatically control the screen resolution of the application by the defined scale. It uses Dynamic Resolution (Vulkan only) and uses Resolution Scale of the Universal Render Pipeline as fallback if the project uses Universal Render Pipeline."));
- static GUIContent s_AdaptiveLOD = EditorGUIUtility.TrTextContent(L10n.Tr("LOD"), L10n.Tr("Adaptive LOD changes the LOD bias based on the thermal and performance load."));
- static GUIContent s_AdaptiveLut = EditorGUIUtility.TrTextContent(L10n.Tr("LUT"), L10n.Tr("Requires Universal Render Pipeline. Adaptive LUT changes the LUT Bias of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveMSAA = EditorGUIUtility.TrTextContent(L10n.Tr("MSAA"), L10n.Tr("Requires Universal Render Pipeline. Adaptive MSAA changes the Anti Aliasing Quality Bias of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveShadowCascade = EditorGUIUtility.TrTextContent(L10n.Tr("Shadow Cascade"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadow Cascade changes the Main Light Shadow Cascades Count Bias of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveShadowDistance = EditorGUIUtility.TrTextContent(L10n.Tr("Shadow Distance"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadow Distance changes the Max Shadow Distance Multiplier of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveShadowmapResolution = EditorGUIUtility.TrTextContent(L10n.Tr("Shadowmap Resolution"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadowmap Resolution changes the Main Light Shadowmap Resolution Multiplier of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveShadowQuality = EditorGUIUtility.TrTextContent(L10n.Tr("Shadow Quality"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadow Quality changes the Shadow Quality Bias of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveSorting = EditorGUIUtility.TrTextContent(L10n.Tr("Sorting"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Sorting skips the front-to-back sorting of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveTransparency = EditorGUIUtility.TrTextContent(L10n.Tr("Transparency"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Transparency skips transparent objects render pass."));
- static GUIContent s_AdaptiveViewDistance = EditorGUIUtility.TrTextContent(L10n.Tr("View Distance"), L10n.Tr("Adaptive View Distance changes the view distance of the main camera. Requires the MainCamera tag on the Camera you want to assign."));
- static GUIContent s_AdaptivePhysics = EditorGUIUtility.TrTextContent(L10n.Tr("Physics"), L10n.Tr("Adaptive Physics changes the Time.fixedDeltaTime based on the thermal and performance load."));
- static GUIContent s_AdaptiveDecals = EditorGUIUtility.TrTextContent(L10n.Tr("Decals"), L10n.Tr("Adaptive Decal changes the maximum draw distance for all decals of the Universal Render Pipeline based on the thermal and performance load."));
- static GUIContent s_AdaptiveLayerCulling = EditorGUIUtility.TrTextContent(L10n.Tr("Layer Culling"), L10n.Tr("Adaptive Layer Culling changes the maximum draw distance for each layer based on the thermal and performance load. It scales the value provided by camera.layerCullDistances."));
-
- static string s_FramerateWarningVSync = L10n.Tr("Adaptive Framerate is only supported without VSync. Set VSync Count to \"Don't Sync\" in Quality settings.");
- static string s_FramerateWarningGameMode = L10n.Tr("Adaptive Framerate is only supported when \"Auto Game Mode\" is turned off.");
- static string s_WarningPopup = L10n.Tr("Warning");
- static string s_WarningPopupMessage = L10n.Tr("Adaptive Performance requires at least one profile to work properly");
- static string s_WarningPopupOption = L10n.Tr("Ok");
- static string s_AdaptiveFramerateMenu = L10n.Tr("Adaptive Framerate");
- static string s_WarningPlaymodePopup = L10n.Tr("Adaptive Performance settings cannot be changed when the Editor is in Play mode.");
- static string s_WarningIndexer = L10n.Tr("You have to enable Adaptive Performance Indexer to use Scaler.");
- static string s_WarningLegacyPackage = L10n.Tr(" Please consider update the legacy provider settings editor to support build profile UI properly. ");
+ static readonly GUIContent s_LoggingLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Logging"), L10n.Tr("Only active in development mode."));
+ static readonly GUIContent s_AutomaticPerformanceModeEnabledLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Auto Performance Mode"), L10n.Tr("Auto Performance Mode controls performance by changing CPU and GPU levels."));
+ static readonly GUIContent s_AutomaticGameModeEnabledLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Auto Game Mode"), L10n.Tr("Auto Game Mode controls performance by changing target FPS based on device GameMode settings."));
+ static readonly GUIContent s_EnableBoostOnStartupLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Boost mode on startup"), L10n.Tr("Enables the CPU and GPU boost mode before engine startup to decrease startup time."));
+ static readonly GUIContent s_StatsLoggingFrequencyInFramesLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Logging Frequency"), L10n.Tr("Changes the logging frequency."));
+ static readonly GUIContent s_IndexerActiveLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Active"), L10n.Tr("Is indexer enabled."));
+ static readonly GUIContent s_IndexerThermalActionDelayLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Thermal Action Delay"), L10n.Tr("Delay after any scaler is applied or unapplied because of thermal state."));
+ static readonly GUIContent s_IndexerPerformanceActionDelayLabel = EditorGUIUtility.TrTextContent(L10n.Tr("Performance Action Delay"), L10n.Tr("Delay after any scaler is applied or unapplied because of performance state."));
+
+ static readonly GUIContent s_ScalerScale = EditorGUIUtility.TrTextContent(L10n.Tr("Scale"), L10n.Tr("Scale to control the quality impact for the scaler. No quality change when 1, improved quality when >1, and lowered quality when <1"));
+ static readonly GUIContent s_ScalerVisualImpact = EditorGUIUtility.TrTextContent(L10n.Tr("Visual Impact"), L10n.Tr("Visual impact the scaler has on the application. The higher the more impact the scaler has on the visuals."));
+ static readonly GUIContent s_ScalerTarget = EditorGUIUtility.TrTextContent(L10n.Tr("Target"), L10n.Tr("Target for the scaler of the application bottleneck. The target selected has the most impact on the quality control of this scaler. Can only be overriden via API."));
+ static readonly GUIContent s_ScalerMaxLevel = EditorGUIUtility.TrTextContent(L10n.Tr("Max Level"), L10n.Tr("Maximum level for the scaler. This is tied to the implementation of the scaler to divide the levels into concrete steps."));
+ static readonly GUIContent s_ScalerMinBound = EditorGUIUtility.TrTextContent(L10n.Tr("Min Scale"), L10n.Tr("Minimum value for the scale boundary."));
+ static readonly GUIContent s_ScalerMaxBound = EditorGUIUtility.TrTextContent(L10n.Tr("Max Scale"), L10n.Tr("Maximum value for the scale boundary."));
+
+ static readonly GUIContent s_AdaptiveFramerate = EditorGUIUtility.TrTextContent(L10n.Tr("Framerate"), L10n.Tr("Adaptive Framerate enables you to automatically control the application's framerate by the defined minimum and maximum framerate. It uses Application.targetFramerate to control the framerate for your application."));
+ static readonly GUIContent s_AdaptiveResolution = EditorGUIUtility.TrTextContent(L10n.Tr("Resolution"), L10n.Tr("Adaptive Resolution enables you to automatically control the screen resolution of the application by the defined scale. It uses Dynamic Resolution (Vulkan only) and uses Resolution Scale of the Universal Render Pipeline as fallback if the project uses Universal Render Pipeline."));
+ static readonly GUIContent s_AdaptiveLOD = EditorGUIUtility.TrTextContent(L10n.Tr("LOD"), L10n.Tr("Adaptive LOD changes the LOD bias based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveLut = EditorGUIUtility.TrTextContent(L10n.Tr("LUT"), L10n.Tr("Requires Universal Render Pipeline. Adaptive LUT changes the LUT Bias of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveMSAA = EditorGUIUtility.TrTextContent(L10n.Tr("MSAA"), L10n.Tr("Requires Universal Render Pipeline. Adaptive MSAA changes the Anti Aliasing Quality Bias of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveShadowCascade = EditorGUIUtility.TrTextContent(L10n.Tr("Shadow Cascade"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadow Cascade changes the Main Light Shadow Cascades Count Bias of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveShadowDistance = EditorGUIUtility.TrTextContent(L10n.Tr("Shadow Distance"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadow Distance changes the Max Shadow Distance Multiplier of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveShadowmapResolution = EditorGUIUtility.TrTextContent(L10n.Tr("Shadowmap Resolution"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadowmap Resolution changes the Main Light Shadowmap Resolution Multiplier of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveShadowQuality = EditorGUIUtility.TrTextContent(L10n.Tr("Shadow Quality"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Shadow Quality changes the Shadow Quality Bias of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveSorting = EditorGUIUtility.TrTextContent(L10n.Tr("Sorting"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Sorting skips the front-to-back sorting of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveTransparency = EditorGUIUtility.TrTextContent(L10n.Tr("Transparency"), L10n.Tr("Requires Universal Render Pipeline. Adaptive Transparency skips transparent objects render pass."));
+ static readonly GUIContent s_AdaptiveViewDistance = EditorGUIUtility.TrTextContent(L10n.Tr("View Distance"), L10n.Tr("Adaptive View Distance changes the view distance of the main camera. Requires the MainCamera tag on the Camera you want to assign."));
+ static readonly GUIContent s_AdaptivePhysics = EditorGUIUtility.TrTextContent(L10n.Tr("Physics"), L10n.Tr("Adaptive Physics changes the Time.fixedDeltaTime based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveDecals = EditorGUIUtility.TrTextContent(L10n.Tr("Decals"), L10n.Tr("Adaptive Decal changes the maximum draw distance for all decals of the Universal Render Pipeline based on the thermal and performance load."));
+ static readonly GUIContent s_AdaptiveLayerCulling = EditorGUIUtility.TrTextContent(L10n.Tr("Layer Culling"), L10n.Tr("Adaptive Layer Culling changes the maximum draw distance for each layer based on the thermal and performance load. It scales the value provided by camera.layerCullDistances."));
+
+ static readonly string s_FramerateWarningVSync = L10n.Tr("Adaptive Framerate is only supported without VSync. Set VSync Count to \"Don't Sync\" in Quality settings.");
+ static readonly string s_FramerateWarningGameMode = L10n.Tr("Adaptive Framerate is only supported when \"Auto Game Mode\" is turned off.");
+ static readonly string s_WarningPopup = L10n.Tr("Warning");
+ static readonly string s_WarningPopupMessage = L10n.Tr("Adaptive Performance requires at least one profile to work properly");
+ static readonly string s_WarningPopupOption = L10n.Tr("Ok");
+ static readonly string s_AdaptiveFramerateMenu = L10n.Tr("Adaptive Framerate");
+ static readonly string s_WarningPlaymodePopup = L10n.Tr("Adaptive Performance settings cannot be changed when the Editor is in Play mode.");
+ static readonly string s_WarningIndexer = L10n.Tr("You have to enable Adaptive Performance Indexer to use Scaler.");
+ static readonly string s_WarningLegacyPackage = L10n.Tr(" Please consider update the legacy provider settings editor to support build profile UI properly. ");
SerializedProperty m_LoggingProperty;
SerializedProperty m_AutoPerformanceModeEnabledProperty;
@@ -125,11 +125,11 @@ public class ProviderSettingsEditor : UnityEditor.Editor
///
protected virtual bool IsThermalActionDelayAvailable { get; private set; } = true;
- static GUIContent k_ShowRuntimeSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Runtime Settings"));
- static GUIContent k_ShowDevelopmentSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Development Settings"));
- static GUIContent k_ShowIndexerSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Indexer Settings"));
- static GUIContent k_ShowScalerSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Scaler Settings"));
- static GUIContent k_ShowScalerProfiles = EditorGUIUtility.TrTextContent(L10n.Tr("Scaler Profiles"));
+ static readonly GUIContent k_ShowRuntimeSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Runtime Settings"));
+ static readonly GUIContent k_ShowDevelopmentSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Development Settings"));
+ static readonly GUIContent k_ShowIndexerSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Indexer Settings"));
+ static readonly GUIContent k_ShowScalerSettings = EditorGUIUtility.TrTextContent(L10n.Tr("Scaler Settings"));
+ static readonly GUIContent k_ShowScalerProfiles = EditorGUIUtility.TrTextContent(L10n.Tr("Scaler Profiles"));
struct ScalerSettingInformation
{
@@ -142,8 +142,8 @@ class ScalerProfileSettingInformation
public Dictionary scalerSettingsInfos = new Dictionary();
}
- static int k_NumberOfScalerProperties = 5;
- static int k_TickboxPosition = 227;
+ const int k_NumberOfScalerProperties = 5;
+ const int k_TickboxPosition = 227;
Dictionary m_ScalerProfiles = new Dictionary();
@@ -193,7 +193,7 @@ void AddNewReorderableList(List list)
///
public void OnEnable()
{
- if (serializedObject == null || serializedObject.targetObject == null)
+ if (target == null || serializedObject == null || serializedObject.targetObject == null)
return;
m_FoldoutState.Clear();
m_FieldObjects.Clear();
@@ -228,7 +228,7 @@ public void OnEnable()
///
public bool DisplayBaseSettingsBegin(bool isLegacyAPI = true)
{
- if (serializedObject == null || serializedObject.targetObject == null)
+ if (target == null || serializedObject == null || serializedObject.targetObject == null)
return false;
serializedObject.Update();
@@ -279,7 +279,7 @@ public bool DisplayBaseSettingsBegin(bool isLegacyAPI = true)
///
public void DisplayBaseSettingsEnd(bool isLegacyAPI = true)
{
- if (serializedObject == null || serializedObject.targetObject == null)
+ if (target == null || serializedObject == null || serializedObject.targetObject == null)
return;
if (isLegacyAPI)
diff --git a/Modules/AdaptivePerformanceEditor/Profiler/AdaptivePerformanceProfilerModule.cs b/Modules/AdaptivePerformanceEditor/Profiler/AdaptivePerformanceProfilerModule.cs
index f1bda7af46..f50400495a 100644
--- a/Modules/AdaptivePerformanceEditor/Profiler/AdaptivePerformanceProfilerModule.cs
+++ b/Modules/AdaptivePerformanceEditor/Profiler/AdaptivePerformanceProfilerModule.cs
@@ -5,6 +5,7 @@
using System;
using Unity.Profiling;
using Unity.Profiling.Editor;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.AdaptivePerformance;
namespace UnityEditor.AdaptivePerformance.Editor
{
@@ -12,6 +13,7 @@ namespace UnityEditor.AdaptivePerformance.Editor
[ProfilerModuleMetadata("Adaptive Performance")]
internal class AdaptivePerformanceProfilerModule : ProfilerModule
{
+ [NoAutoStaticsCleanup] // fixed compile-time list of profiler counter descriptors
static readonly ProfilerCounterDescriptor[] k_ChartCounters = new ProfilerCounterDescriptor[]
{
new ProfilerCounterDescriptor("CPU frametime", ProfilerCategory.Scripts),
diff --git a/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderLoader.cs b/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderLoader.cs
index 7a19eac268..b79b62d7ad 100644
--- a/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderLoader.cs
+++ b/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderLoader.cs
@@ -4,6 +4,7 @@
using UnityEngine;
using System.Collections.Generic;
+using Unity.Scripting.LifecycleManagement;
using UnityEngine.AdaptivePerformance;
using UnityEditor.AdaptivePerformance.Editor;
using UnityEngine.AdaptivePerformance.Provider;
@@ -16,6 +17,7 @@ namespace UnityEditor.AdaptivePerformance.Simulator.Editor
[AdaptivePerformanceSupportedBuildTargetAttribute(BuildTargetGroup.Standalone)]
public class SimulatorProviderLoader : AdaptivePerformanceLoaderHelper
{
+ [NoAutoStaticsCleanup] // populated by native subsystem registration, not C# state
static List s_SimulatorSubsystemDescriptors =
new List();
diff --git a/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderSettings.cs b/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderSettings.cs
index f2f408651e..5f24e685da 100644
--- a/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderSettings.cs
+++ b/Modules/AdaptivePerformanceEditor/Provider/SimulatorProviderSettings.cs
@@ -2,6 +2,7 @@
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+using Unity.Scripting.LifecycleManagement;
using UnityEngine;
using UnityEngine.AdaptivePerformance;
@@ -12,8 +13,9 @@ namespace UnityEditor.AdaptivePerformance.Simulator.Editor
///
[System.Serializable]
[AdaptivePerformanceConfigurationData("Simulator", SimulatorProviderConstants.k_SettingsKey)]
- public class SimulatorProviderSettings : IAdaptivePerformanceSettings
+ public partial class SimulatorProviderSettings : IAdaptivePerformanceSettings
{
+ [AutoStaticsCleanup]
static SimulatorProviderSettings m_Settings = null;
///
diff --git a/Modules/AdaptivePerformanceEditor/UI/BuildProfileAdaptivePerformanceProviderUI.cs b/Modules/AdaptivePerformanceEditor/UI/BuildProfileAdaptivePerformanceProviderUI.cs
index a35e1b9b73..63fe78ce6b 100644
--- a/Modules/AdaptivePerformanceEditor/UI/BuildProfileAdaptivePerformanceProviderUI.cs
+++ b/Modules/AdaptivePerformanceEditor/UI/BuildProfileAdaptivePerformanceProviderUI.cs
@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
+using Unity.Scripting.LifecycleManagement;
using UnityEditor.AdaptivePerformance.Editor.Metadata;
using UnityEditor.Build.Profile;
using UnityEditor.PackageManager;
@@ -36,6 +37,7 @@ internal struct LoaderInformation
DropdownField m_DropDown;
List m_LoaderNameList;
ReorderableList m_ReorderableList;
+ [NoAutoStaticsCleanup] // dialog-guard flag, always restored to false after dialog closes
static bool s_ShowingDialog = false;
internal readonly GUIContent k_ViewGuide = new("View Guide");
diff --git a/Modules/Animation/ScriptBindings/HumanTrait.bindings.cs b/Modules/Animation/ScriptBindings/HumanTrait.bindings.cs
index 9059717341..7723e53510 100644
--- a/Modules/Animation/ScriptBindings/HumanTrait.bindings.cs
+++ b/Modules/Animation/ScriptBindings/HumanTrait.bindings.cs
@@ -20,7 +20,16 @@ extern public static int MuscleCount
get;
}
- extern internal static int GetBoneIndexFromMono(int humanId);
+ internal static int GetBoneIndexFromMono(int humanId)
+ {
+ if (humanId < 0 || humanId >= BoneCount)
+ throw new ArgumentOutOfRangeException(nameof(humanId));
+ return Internal_GetBoneIndexFromMono(humanId);
+ }
+
+ [NativeMethod("GetBoneIndexFromMono")]
+ extern static int Internal_GetBoneIndexFromMono(int humanId);
+
extern internal static int GetBoneIndexToMono(int boneIndex);
// Muscle's name
diff --git a/Modules/AnimationWindow/Editor/AddCurvesPopupHierarchyGUI.cs b/Modules/AnimationWindow/Editor/AddCurvesPopupHierarchyGUI.cs
index a6c256c918..ca2c77ca74 100644
--- a/Modules/AnimationWindow/Editor/AddCurvesPopupHierarchyGUI.cs
+++ b/Modules/AnimationWindow/Editor/AddCurvesPopupHierarchyGUI.cs
@@ -16,9 +16,7 @@ internal class AddCurvesPopupHierarchyGUI : TreeViewGUI
{
public EditorWindow owner;
public bool showPlusButton { get; set; }
- private GUIStyle buttonStyle = "IconButton";
private GUIContent plusIcon = EditorGUIUtility.TrIconContent("Toolbar Plus");
- private GUIStyle plusButtonBackgroundStyle = "Tag MenuItem";
private GUIContent addPropertiesContent = EditorGUIUtility.TrTextContent("Add Properties");
private const float plusButtonWidth = 17;
@@ -42,14 +40,14 @@ private void DoAddCurveButton(Rect rowRect, TreeViewItem node)
if (hierarchyNode == null || hierarchyNode.curveBindings == null || hierarchyNode.curveBindings.Length == 0)
return;
- Rect buttonRect = new Rect(rowRect.width - plusButtonWidth, rowRect.yMin, plusButtonWidth, buttonStyle.fixedHeight);
+ Rect buttonRect = new Rect(rowRect.width - plusButtonWidth, rowRect.yMin, plusButtonWidth, AnimationWindowStyles.plusButton.fixedHeight);
// TODO Make a style for add curves popup
// Draw background behind plus button to prevent text overlapping
- GUI.Box(buttonRect, GUIContent.none, plusButtonBackgroundStyle);
+ GUI.Box(buttonRect, GUIContent.none, AnimationWindowStyles.plusButtonBackground);
// Check if the curve already exists and remove plus button
- if (GUI.Button(buttonRect, plusIcon, buttonStyle))
+ if (GUI.Button(buttonRect, plusIcon, AnimationWindowStyles.plusButton))
{
AddCurvesPopup.AddNewCurve(hierarchyNode);
diff --git a/Modules/AnimationWindow/Editor/AnimationWindow.cs b/Modules/AnimationWindow/Editor/AnimationWindow.cs
index 6becd6aad3..69665c449b 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindow.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindow.cs
@@ -186,6 +186,9 @@ void OnEnable()
m_AnimEditor.hideFlags = HideFlags.HideAndDontSave;
}
+ if (state != null)
+ state.onHierarchySelectionChange += SyncSceneSelection;
+
s_AnimationWindows.Add(this);
OnSelectionChangeInternal(false);
@@ -340,6 +343,96 @@ internal void OnSelectionUpdated()
state?.OnSelectionUpdated();
}
+ internal bool WouldChangeSelection(UnityObject candidate)
+ {
+ if (m_LockTracker.isLocked || (state != null && state.linkedWithSequencer))
+ return false;
+
+ foreach (var responder in s_Responders)
+ {
+ if (WouldResponderChangeSelection(responder, candidate))
+ return true;
+ }
+ return false;
+ }
+
+ bool WouldResponderChangeSelection(IAnimationWindowResponder responder, UnityEngine.Object candidateObject)
+ {
+ if (!responder.OnSelectionChange(this, candidateObject, out var probe))
+ return false;
+ if (probe == selection)
+ return false;
+ if (probe != null)
+ probe.Dispose();
+ return true;
+ }
+
+ // Set scene active go to be the same as the one selected from hierarchy
+ void SyncSceneSelection(int[] selectedNodeIDs)
+ {
+ if (state == null || state.filterBySelection)
+ return;
+
+ var selection = state.selection;
+ if (selection == null || !selection.canSyncSceneSelection)
+ return;
+
+ GameObject rootGameObject = selection.rootGameObject;
+ if (rootGameObject == null)
+ return;
+
+ var selectedGameObjectIDs = new List(selectedNodeIDs.Length);
+ foreach (var selectedNodeID in selectedNodeIDs)
+ {
+ // Skip nodes without associated curves.
+ if (selectedNodeID == 0)
+ continue;
+
+ AnimationWindowHierarchyNode node = state.hierarchyData.FindItem(selectedNodeID) as AnimationWindowHierarchyNode;
+
+ if (node == null)
+ continue;
+
+ if (node is AnimationWindowHierarchyMasterNode)
+ continue;
+
+ Transform t = rootGameObject.transform.Find(node.path);
+
+ // In the case of nested animation component, we don't want to sync the scene selection (case 569506)
+ // When selection changes, animation window will always pick nearest animator component in terms of hierarchy depth
+ // Automatically syncinc scene selection in nested scenarios would cause unintuitive clip & animation change for animation window so we check for it and deny sync if necessary
+ if (selection.IsCompatibleWith(t))
+ {
+ EntityId entity;
+ if (node.curves.Length > 0)
+ {
+ AnimationWindowCurve firstCurve = node.curves[0];
+ // Query the animation system for the associate EntityId
+ // For custom IAnimationBinding (e.g., UIToolkit), this will return the appropriate selection object
+ // For standard animations, returns the GameObject's EntityId
+ entity = AnimationUtility.GetAssociatedEntityId(t.gameObject, firstCurve.binding);
+
+ // Case 569506 protection extended to non-Animator routing: skip when the
+ // entity routes to a different SelectionItem (e.g. nested VE with its own UIAnimationClip).
+ var entityObj = EditorUtility.EntityIdToObject(entity);
+ if (entityObj != null && entityObj != t.gameObject && WouldChangeSelection(entityObj))
+ continue;
+ }
+ else
+ {
+ entity = t.gameObject.GetEntityId();
+ }
+
+ selectedGameObjectIDs.Add(entity);
+ }
+ }
+
+ if (selectedGameObjectIDs.Count > 0)
+ Selection.entityIds = selectedGameObjectIDs.ToArray();
+ else
+ Selection.activeGameObject = rootGameObject;
+ }
+
void OnFocus()
{
OnSelectionChangeInternal(false);
diff --git a/Modules/AnimationWindow/Editor/AnimationWindowHierarchyGUI.cs b/Modules/AnimationWindow/Editor/AnimationWindowHierarchyGUI.cs
index 922edefc38..906124b60d 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindowHierarchyGUI.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindowHierarchyGUI.cs
@@ -43,8 +43,9 @@ internal class AnimationWindowHierarchyGUI : TreeViewGUI
private const float k_ValueFieldDragWidth = 15;
private const float k_ValueFieldWidth = 80;
private const float k_ValueFieldOffsetFromRightSide = 100;
- private const float k_ObjectFieldAdditionalWidth = 30;
- private const float k_ObjectFieldAdditionalOffset = k_ObjectFieldAdditionalWidth + 30;
+ private const float k_ObjectFieldWidth = 110;
+ private const float k_ObjectFieldOffsetFromRightSide = 160;
+ private const float k_LabelFieldSpacing = 2;
private const float k_ObjectFieldMaxHeight = 18;
private const float k_ColorIndicatorTopMargin = 3;
public static readonly float k_DopeSheetRowHeight = EditorGUI.kSingleLineHeight;
@@ -110,6 +111,8 @@ protected void DoNodeGUI(Rect rect, AnimationWindowHierarchyNode node, bool sele
float indent = k_BaseIndent + (node.depth + node.indent) * k_IndentWidth;
+ CalculateRects(rect, node, indent, out var labelRect, out var valueFieldRect);
+
if (node is AnimationWindowHierarchyAddButtonNode)
{
if (Event.current.type == EventType.MouseMove && s_WasInsideValueRectFrame >= 0)
@@ -128,13 +131,13 @@ protected void DoNodeGUI(Rect rect, AnimationWindowHierarchyNode node, bool sele
else
{
DoRowBackground(rect, row);
- DoIconAndName(rect, node, selected, focused, indent);
+ DoIconAndName(rect, labelRect, node, selected, focused);
DoFoldout(node, rect, indent, row);
bool enabled = !state.selection.isReadOnly;
using (new EditorGUI.DisabledScope(!enabled))
{
- DoValueField(rect, node, row);
+ DoValueField(rect, valueFieldRect, node, row);
}
DoCurveDropdown(rect, node, row, enabled);
HandleContextMenu(rect, node, enabled);
@@ -194,6 +197,49 @@ private void OnNewCurveAdded(AddCurvesPopupPropertyNode node)
{
}
+ void CalculateRects(Rect rect, AnimationWindowHierarchyNode node, float indent, out Rect labelRect, out Rect fieldRect)
+ {
+ // Calculate labelRect
+ labelRect = rect;
+
+ // Offset the labelRect with the amount of indent and the foldout width
+ labelRect.xMin += (int)(indent + foldoutStyleWidth + lineStyle.margin.left);
+ labelRect.yMin = rect.y + (rect.height - EditorGUIUtility.singleLineHeight) / 2;
+
+ // labelRect will take the entire row unless the node is a property.
+ // Return early and avoid fieldRect calculations.
+ if (node is not AnimationWindowHierarchyPropertyNode propertyNode)
+ {
+ fieldRect = Rect.zero; // no field on the right
+ return;
+ }
+
+ var offset = propertyNode.isPPtrNode
+ ? k_ObjectFieldOffsetFromRightSide
+ : k_ValueFieldOffsetFromRightSide;
+ var fieldWidth = propertyNode.isPPtrNode
+ ? k_ObjectFieldWidth
+ : k_ValueFieldWidth;
+
+ // Adjust labelRect based on the space taken by fieldRect
+ labelRect.xMax -= offset + k_LabelFieldSpacing;
+
+ // Calculate fieldRect
+ fieldRect = rect;
+ fieldRect.x = rect.xMax - offset;
+ fieldRect.width = fieldWidth;
+
+ // Limit height of PPtr field to avoid showing a squashed preview of the object
+ if (propertyNode.isPPtrNode)
+ {
+ var height = Mathf.Min(k_ObjectFieldMaxHeight, fieldRect.height);
+ var yOffset = (fieldRect.height - height) * 0.5f;
+
+ fieldRect.y += yOffset;
+ fieldRect.height = height;
+ }
+ }
+
private void DoRowBackground(Rect rect, int row)
{
if (Event.current.type != EventType.Repaint)
@@ -244,7 +290,7 @@ private void DoFoldout(AnimationWindowHierarchyNode node, Rect rect, float inden
}
}
- private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool selected, bool focused, float indent)
+ private void DoIconAndName(Rect rect, Rect labelRect, AnimationWindowHierarchyNode node, bool selected, bool focused)
{
EditorGUIUtility.SetIconSize(new Vector2(13, 13)); // If not set we see icons scaling down if text is being cropped
@@ -254,10 +300,6 @@ private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool se
if (selected)
selectionStyle.Draw(rect, false, false, true, focused);
- // Leave some space for the value field that comes after.
- if (node is AnimationWindowHierarchyPropertyNode)
- rect.width -= k_ValueFieldOffsetFromRightSide + 2;
-
bool isLeftOverCurve = AnimationWindowUtility.IsNodeLeftOverCurve(state, node);
bool isAmbiguous = AnimationWindowUtility.IsNodeAmbiguous(state, node);
bool isPhantom = AnimationWindowUtility.IsNodePhantom(node);
@@ -323,15 +365,15 @@ private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool se
SetStyleTextColor(lineStyle, textColor);
- rect.xMin += (int)(indent + foldoutStyleWidth + lineStyle.margin.left);
- rect.yMin = rect.y + (rect.height - EditorGUIUtility.singleLineHeight) / 2;
- GUI.Label(rect, Styles.content, lineStyle);
+ GUI.Label(labelRect, Styles.content, lineStyle);
SetStyleTextColor(lineStyle, oldColor);
+
+ GUIView.current?.MarkHotRegion(GUIClip.UnclipToWindow(labelRect));
}
if (IsRenaming(node.id) && Event.current.type != EventType.Layout)
- GetRenameOverlay().editFieldRect = new Rect(rect.x + k_IndentWidth, rect.y, rect.width - k_IndentWidth - 1, rect.height);
+ GetRenameOverlay().editFieldRect = new Rect(labelRect.x + k_IndentWidth, labelRect.y, labelRect.width - k_IndentWidth - 1, labelRect.height);
}
private string GetGameObjectName(GameObject rootGameObject, string path)
@@ -343,7 +385,7 @@ private string GetGameObjectName(GameObject rootGameObject, string path)
return splits[splits.Length - 1];
}
- private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
+ private void DoValueField(Rect rect, Rect fieldRect, AnimationWindowHierarchyNode node, int row)
{
bool curvesChanged = false;
@@ -359,10 +401,9 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
int id = m_HierarchyItemValueControlIDs[row];
- Rect valueFieldDragRect = new Rect(rect.xMax - k_ValueFieldOffsetFromRightSide - k_ValueFieldDragWidth, rect.y, k_ValueFieldDragWidth, rect.height);
- Rect valueFieldRect = new Rect(rect.xMax - k_ValueFieldOffsetFromRightSide, rect.y, k_ValueFieldWidth, rect.height);
+ Rect valueFieldDragRect = new Rect(fieldRect.x - k_ValueFieldDragWidth, rect.y, k_ValueFieldDragWidth, rect.height);
- if (Event.current.type == EventType.MouseMove && valueFieldRect.Contains(Event.current.mousePosition))
+ if (Event.current.type == EventType.MouseMove && fieldRect.Contains(Event.current.mousePosition))
s_WasInsideValueRectFrame = Time.frameCount;
EditorGUI.BeginChangeCheck();
@@ -370,7 +411,7 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
bool handledByCustomHandler = false;
foreach (var handler in AnimationWindowUtility.PropertyHandlers)
{
- if (handler.TryDoValueField(valueFieldRect, valueFieldDragRect, id,
+ if (handler.TryDoValueField(fieldRect, valueFieldDragRect, id,
curve.binding, curve.valueType, node.animatableObjectType, value,
out var handlerValue, ref node.handlerData))
{
@@ -388,16 +429,12 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
if (typeof(UnityEngine.Object).IsAssignableFrom(objType))
{
- var height = Mathf.Min(k_ObjectFieldMaxHeight, valueFieldRect.height);
- var yOffset = (valueFieldRect.height - height) * 0.5f;
- valueFieldRect = new Rect(valueFieldRect.x - k_ObjectFieldAdditionalOffset, valueFieldRect.y + yOffset, valueFieldRect.width + k_ObjectFieldAdditionalWidth, height);
-
- value = EditorGUI.DoObjectField(valueFieldRect, valueFieldRect, id, value as UnityEngine.Object, null, objType, null, false);
+ value = EditorGUI.DoObjectField(fieldRect, fieldRect, id, value as UnityEngine.Object, null, objType, null, false);
}
}
else if (curve.valueType == typeof(bool))
{
- value = GUI.Toggle(valueFieldRect, id, Convert.ToSingle(value) != 0f, GUIContent.none, EditorStyles.toggle) ? 1f : 0f;
+ value = GUI.Toggle(fieldRect, id, Convert.ToSingle(value) != 0f, GUIContent.none, EditorStyles.toggle) ? 1f : 0f;
}
else
{
@@ -408,7 +445,7 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
// Force back keyboard focus to float field editor when editing it since the TreeView forces keyboard focus on itself at mouse down.
// The focus will be reclaimed after the TreeViewController.OnGUI call.
- if (EditorGUI.s_RecycledEditor.controlID == id && Event.current.type == EventType.MouseDown && valueFieldRect.Contains(Event.current.mousePosition))
+ if (EditorGUI.s_RecycledEditor.controlID == id && Event.current.type == EventType.MouseDown && fieldRect.Contains(Event.current.mousePosition))
{
m_NeedsToReclaimFieldFocus = true;
m_FieldToReclaimFocus = id;
@@ -417,7 +454,7 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
if (curve.isDiscreteCurve)
{
value = EditorGUI.DoIntField(EditorGUI.s_RecycledEditor,
- valueFieldRect,
+ fieldRect,
valueFieldDragRect,
id,
Convert.ToInt32(value),
@@ -434,7 +471,7 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row)
else
{
value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor,
- valueFieldRect,
+ fieldRect,
valueFieldDragRect,
id,
Convert.ToSingle(value),
@@ -494,6 +531,7 @@ private bool DoTreeViewButton(int id, Rect position, GUIContent content, GUIStyl
{
case EventType.Repaint:
style.Draw(position, content, id, false, position.Contains(evt.mousePosition));
+ GUIView.current?.MarkHotRegion(GUIClip.UnclipToWindow(position));
break;
case EventType.MouseDown:
if (position.Contains(evt.mousePosition) && evt.button == 0)
@@ -749,7 +787,6 @@ void ChangeRotationInterpolation(System.Object interpolationMode)
}
state.activeClip.SetInterpolations(curveBindings, mode, L10n.Tr("Rotation Interpolation"));
- MaintainTreeviewStateAfterRotationInterpolation(mode);
state.hierarchyData.ReloadData();
}
@@ -824,54 +861,6 @@ private List GetCurvesAffectedByNodes(List selectedInstaceIDs = state.hierarchyState.selectedIDs;
- List expandedInstaceIDs = state.hierarchyState.expandedIDs;
-
- List oldIDs = new List();
- List newIds = new List();
-
- for (int i = 0; i < selectedInstaceIDs.Count; i++)
- {
- AnimationWindowHierarchyNode node = state.hierarchyData.FindItem(selectedInstaceIDs[i]) as AnimationWindowHierarchyNode;
-
- if (node != null && !node.propertyName.Equals(RotationCurveInterpolation.GetPrefixForInterpolation(newMode)))
- {
- string oldPrefix = node.propertyName.Split('.')[0];
- string newPropertyName = node.propertyName.Replace(oldPrefix, RotationCurveInterpolation.GetPrefixForInterpolation(newMode));
-
- // old treeview node id
- oldIDs.Add(selectedInstaceIDs[i]);
- // and its new replacement
- newIds.Add((node.path + node.animatableObjectType.Name + newPropertyName).GetHashCode());
- }
- }
-
- // Replace old IDs with new ones
- for (int i = 0; i < oldIDs.Count; i++)
- {
- if (selectedInstaceIDs.Contains(oldIDs[i]))
- {
- int index = selectedInstaceIDs.IndexOf(oldIDs[i]);
- selectedInstaceIDs[index] = newIds[i];
- }
- if (expandedInstaceIDs.Contains(oldIDs[i]))
- {
- int index = expandedInstaceIDs.IndexOf(oldIDs[i]);
- expandedInstaceIDs[index] = newIds[i];
- }
- if (state.hierarchyState.lastClickedID == oldIDs[i])
- state.hierarchyState.lastClickedID = newIds[i];
- }
-
- state.hierarchyState.selectedIDs = new List(selectedInstaceIDs);
- state.hierarchyState.expandedIDs = new List(expandedInstaceIDs);
- }
-
private RotationCurveInterpolation.Mode GetRotationInterpolationMode(EditorCurveBinding[] curves)
{
if (curves == null || curves.Length == 0)
diff --git a/Modules/AnimationWindow/Editor/AnimationWindowSearchFilter.cs b/Modules/AnimationWindow/Editor/AnimationWindowSearchFilter.cs
index a0fb8d8b0f..615945e318 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindowSearchFilter.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindowSearchFilter.cs
@@ -13,6 +13,7 @@ struct AnimationWindowSearchFilter
{
static readonly string[] k_TypePrefixes = ["t=", "type="];
static readonly string[] k_PropertyPrefixes = ["p=", "property="];
+ public const string k_FilterPrefix = "animation:";
static readonly char[] kFilterSeparator = new [] { ' ', '\t', ',', '*', '?'};
[SerializeField] List m_NameFilters = new();
@@ -102,6 +103,12 @@ void SetSearchString(string searchString)
void CheckForKeyWords(string searchString, int quote1, int quote2)
{
+ // Ignore filter prefix
+ if (searchString.StartsWith(k_FilterPrefix))
+ {
+ searchString = searchString.Substring(k_FilterPrefix.Length);
+ }
+
// Support: 't=type' syntax (e.g 't=Transform' will show Transform components)
foreach (var typePrefix in k_TypePrefixes)
{
diff --git a/Modules/AnimationWindow/Editor/AnimationWindowSearchView.cs b/Modules/AnimationWindow/Editor/AnimationWindowSearchView.cs
index e3d6c23016..8e1fb95e9b 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindowSearchView.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindowSearchView.cs
@@ -40,7 +40,8 @@ SearchProvider CreateAnimationProvider()
{
return new SearchProvider("animation", "Animation")
{
- isExplicitProvider = false,
+ isExplicitProvider = true,
+ filterId = AnimationWindowSearchFilter.k_FilterPrefix,
priority = 100,
active = true,
fetchPropositions = (context, options) => FetchAnimationPropositions(context, options)
@@ -151,7 +152,7 @@ void ISearchView.SetSearchText(string searchText, TextCursorPlacement moveCursor
return;
context.searchText = searchText;
- m_State.searchFilter = context.searchQuery;
+ m_State.searchFilter = searchText;
}
void ISearchView.SetSelection(params int[] selection)
diff --git a/Modules/AnimationWindow/Editor/AnimationWindowState.cs b/Modules/AnimationWindow/Editor/AnimationWindowState.cs
index c489001268..31c3c5379c 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindowState.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindowState.cs
@@ -38,6 +38,7 @@ public enum SnapMode
[SerializeField] public AnimEditor animEditor; // Reference to owner of this state. Used to trigger repaints.
[SerializeField] public AnimationWindowHierarchyState hierarchyState = new(); // Persistent state of treeview on the left side of window
[NonSerialized] public AnimationWindowHierarchyDataSource hierarchyData;
+ [NonSerialized] public Action onHierarchySelectionChange;
[SerializeReference] private TimeArea m_TimeArea; // Either curveeditor or dopesheet depending on which is selected
@@ -1565,7 +1566,7 @@ public void HandleHierarchySelectionChanged(int[] selectedInstanceIDs, bool trig
m_ActiveCurvesCache = null;
if (triggerSceneSelectionSync)
- SyncSceneSelection(selectedInstanceIDs);
+ onHierarchySelectionChange?.Invoke(selectedInstanceIDs);
}
public void SelectHierarchyItem(DopeLine dopeline, bool additive)
@@ -1667,65 +1668,6 @@ public DopeLine GetDopeline(int selectedInstanceID)
return null;
}
- // Set scene active go to be the same as the one selected from hierarchy
- private void SyncSceneSelection(int[] selectedNodeIDs)
- {
- if (filterBySelection)
- return;
-
- if (!selection.canSyncSceneSelection)
- return;
-
- GameObject rootGameObject = selection.rootGameObject;
- if (rootGameObject == null)
- return;
-
- var selectedGameObjectIDs = new List(selectedNodeIDs.Length);
- foreach (var selectedNodeID in selectedNodeIDs)
- {
- // Skip nodes without associated curves.
- if (selectedNodeID == 0)
- continue;
-
- AnimationWindowHierarchyNode node = hierarchyData.FindItem(selectedNodeID) as AnimationWindowHierarchyNode;
-
- if (node == null)
- continue;
-
- if (node is AnimationWindowHierarchyMasterNode)
- continue;
-
- Transform t = rootGameObject.transform.Find(node.path);
-
- // In the case of nested animation component, we don't want to sync the scene selection (case 569506)
- // When selection changes, animation window will always pick nearest animator component in terms of hierarchy depth
- // Automatically syncinc scene selection in nested scenarios would cause unintuitive clip & animation change for animation window so we check for it and deny sync if necessary
- if (selection.IsCompatibleWith(t))
- {
- EntityId entity;
- if (node.curves.Length > 0)
- {
- AnimationWindowCurve firstCurve = node.curves[0];
- // Query the animation system for the associate EntityId
- // For custom IAnimationBinding (e.g., UIToolkit), this will return the appropriate selection object
- // For standard animations, returns the GameObject's EntityId
- entity = AnimationUtility.GetAssociatedEntityId(t.gameObject, firstCurve.binding);
- }
- else
- {
- entity = t.gameObject.GetEntityId();
- }
-
- selectedGameObjectIDs.Add(entity);
- }
- }
-
- if (selectedGameObjectIDs.Count > 0)
- UnityEditor.Selection.entityIds = selectedGameObjectIDs.ToArray();
- else
- UnityEditor.Selection.activeGameObject = rootGameObject;
- }
-
[Obsolete("Use frameRate property instead.")]
public float clipFrameRate
{
@@ -1776,6 +1718,11 @@ public float frameRate
}
selection.clip.frameRate = value;
+
+ // Preserve the current frame position at the new frame rate
+ int oldFrame = AnimationKeyTime.Time(currentTime, oldFrameRate).frame;
+ float newTime = AnimationKeyTime.Frame(oldFrame, value).time;
+ currentTime = newTime;
}
}
}
diff --git a/Modules/AnimationWindow/Editor/AnimationWindowStyles.cs b/Modules/AnimationWindow/Editor/AnimationWindowStyles.cs
index c5c29fadd3..b68190e0da 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindowStyles.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindowStyles.cs
@@ -68,6 +68,9 @@ internal class AnimationWindowStyles
public static GUIStyle miniToolbarButton = new GUIStyle(EditorStyles.toolbarButton);
public static GUIStyle toolbarLabel = new GUIStyle(AnimationWindowStyles.animClipToolbarPopup);
+ public static readonly GUIStyle plusButton = "IconButton";
+ public static readonly GUIStyle plusButtonBackground = "Tag MenuItem";
+
public static void Initialize()
{
toolbarLabel.normal.background = null;
diff --git a/Modules/AnimationWindow/Editor/AnimationWindowUtility.cs b/Modules/AnimationWindow/Editor/AnimationWindowUtility.cs
index 45d8e02b14..bbcd3c3b43 100644
--- a/Modules/AnimationWindow/Editor/AnimationWindowUtility.cs
+++ b/Modules/AnimationWindow/Editor/AnimationWindowUtility.cs
@@ -16,6 +16,8 @@ namespace UnityEditorInternal
[VisibleToOtherModules("UnityEditor.UIToolkitAuthoringModule")]
static partial class AnimationWindowUtility
{
+ public const float MaxDisplayableKeyValue = 5e5f;
+
private static readonly List s_PropertyHandlers = new();
[VisibleToOtherModules("UnityEditor.UIToolkitAuthoringModule")]
@@ -51,6 +53,10 @@ static void SetDefaultValues(AnimationWindowState state, IAnimationWindowClip cl
Type type = state.selection.GetValueType(curve.binding);
object currentValue = CurveBindingUtility.GetCurrentValue(state, curve.binding);
+
+ if (currentValue is float f)
+ currentValue = float.IsNaN(f) ? 0f : Mathf.Clamp(f, -MaxDisplayableKeyValue, MaxDisplayableKeyValue);
+
if (curve.length == 0.0F)
{
AddKeyframeToCurve(curve, currentValue, type, AnimationKeyTime.Time(0.0F, clip.frameRate));
@@ -561,9 +567,12 @@ public static bool CurveExists(EditorCurveBinding binding, AnimationWindowCurve[
private const string k_ComponentPathSeparator = " : ";
- private static string FormatComponentPathDisplayName(Type componentType, string displayPath)
+ private static string FormatComponentPathDisplayName(Type componentType, string propertyName, string displayPath)
{
- return ObjectNames.NicifyVariableName(componentType.Name) + k_ComponentPathSeparator + displayPath.Replace("/", k_ComponentPathSeparator);
+ string path = displayPath.Replace("/", k_ComponentPathSeparator);
+ if (!ShouldPrefixWithTypeName(componentType, propertyName))
+ return path;
+ return ObjectNames.NicifyVariableName(componentType.Name) + k_ComponentPathSeparator + path;
}
// Takes raw animation curve propertyname and makes it pretty
@@ -594,6 +603,12 @@ public static bool ShouldPrefixWithTypeName(Type animatableObjectType, string pr
if (animatableObjectType == typeof(SpriteRenderer) && propertyName == "m_Sprite")
return false;
+ // A registered handler may declare this curve component-less (e.g. binder-routed style
+ // channels with no owning component on a GameObject), in which case it gets no prefix.
+ foreach (var h in s_PropertyHandlers)
+ if (!h.ShouldPrefixWithTypeName(animatableObjectType, propertyName))
+ return false;
+
return true;
}
@@ -624,7 +639,7 @@ public static string GetNicePropertyDisplayName(EditorCurveBinding curveBinding,
if (!string.IsNullOrEmpty(curveBinding.propertyName) && curveBinding.propertyName.IndexOf('/') >= 0)
{
GetGroupDisplayPath(curveBinding.propertyName, out string displayPath, out fullPathForTooltip);
- return FormatComponentPathDisplayName(animatableObjectType, displayPath);
+ return FormatComponentPathDisplayName(animatableObjectType, curveBinding.propertyName, displayPath);
}
fullPathForTooltip = null;
return GetNicePropertyDisplayName(curveBinding, so);
@@ -665,7 +680,7 @@ public static string GetNicePropertyGroupDisplayName(EditorCurveBinding curveBin
if (!string.IsNullOrEmpty(curveBinding.propertyName) && curveBinding.propertyName.IndexOf('/') >= 0)
{
GetGroupDisplayPath(curveBinding.propertyName, out string displayPath, out fullPathForTooltip);
- return FormatComponentPathDisplayName(animatableObjectType, displayPath);
+ return FormatComponentPathDisplayName(animatableObjectType, curveBinding.propertyName, displayPath);
}
fullPathForTooltip = null;
return GetNicePropertyGroupDisplayName(curveBinding, so);
@@ -875,7 +890,7 @@ public static float GetPreviousKeyframeTime(IEnumerable cu
public static int GetPropertyNodeID(int setId, string path, System.Type type, string propertyName)
{
- return (setId + path + type.Name + propertyName).GetHashCode();
+ return (setId + path + type.Name + RotationCurveInterpolation.GetPropertyNameForHashing(type, propertyName)).GetHashCode();
}
public static void SyncTimeArea(TimeArea from, TimeArea to)
diff --git a/Modules/AnimationWindow/Editor/DopeSheetEditor.cs b/Modules/AnimationWindow/Editor/DopeSheetEditor.cs
index 8a603261a9..efc9dce826 100644
--- a/Modules/AnimationWindow/Editor/DopeSheetEditor.cs
+++ b/Modules/AnimationWindow/Editor/DopeSheetEditor.cs
@@ -890,11 +890,14 @@ public EditorCurveBinding[] GetAnimatableProperties(IAnimationWindowSelectionIte
private void SelectTypeForCreatingNewPptrDopeline(object userData, string[] options, int selected)
{
+ if (selected < 0)
+ return;
+
List userDataList = userData as List;
var clip = userDataList[0] as IAnimationWindowClip;
- List bindings = userDataList[1] as List;
+ var bindings = userDataList[1] as EditorCurveBinding[];
- if (bindings.Count > selected)
+ if (bindings.Length > selected)
DoSpriteDropAfterGeneratingNewDopeline(clip, bindings[selected]);
}
@@ -1384,7 +1387,7 @@ internal class DopeSheetSelectionRect
enum SelectionType { Normal, Additive, Subtractive }
public readonly GUIStyle createRect = "U2D.createRect";
- static int s_RectSelectionID = GUIUtility.GetPermanentControlID();
+ readonly int m_RectSelectionID = GUIUtility.GetPermanentControlID();
public DopeSheetSelectionRect(DopeSheetEditor owner)
{
@@ -1395,7 +1398,7 @@ public void OnGUI(Rect position)
{
Event evt = Event.current;
Vector2 mousePos = evt.mousePosition;
- int id = s_RectSelectionID;
+ int id = m_RectSelectionID;
switch (evt.GetTypeForControl(id))
{
case EventType.MouseDown:
diff --git a/Modules/AnimationWindow/Editor/IAnimationWindowPropertyHandler.cs b/Modules/AnimationWindow/Editor/IAnimationWindowPropertyHandler.cs
index 5cdb99f56b..dab6eb5548 100644
--- a/Modules/AnimationWindow/Editor/IAnimationWindowPropertyHandler.cs
+++ b/Modules/AnimationWindow/Editor/IAnimationWindowPropertyHandler.cs
@@ -18,6 +18,11 @@ internal interface IAnimationWindowPropertyHandler
// Returns the group name (prefix before the channel suffix), or null if not handled.
string GetPropertyGroupName(string propertyName);
+ // Returns false when this curve has no owning component to name so the Animation Window omits
+ // the component-name prefix from its hierarchy row.
+ // Return true to keep the default behaviour of prefixing with the owning component's type name.
+ bool ShouldPrefixWithTypeName(Type animatableObjectType, string propertyName);
+
// --- Value field rendering (called inside BeginChangeCheck/EndChangeCheck) ---
// Renders a custom value control for the given curve.
// animatableObjectType is the node's component type; handlers should
diff --git a/Modules/AnimationWindow/Editor/RotationCurveInterpolation.cs b/Modules/AnimationWindow/Editor/RotationCurveInterpolation.cs
index 26f6527822..ae2fb9dfe6 100644
--- a/Modules/AnimationWindow/Editor/RotationCurveInterpolation.cs
+++ b/Modules/AnimationWindow/Editor/RotationCurveInterpolation.cs
@@ -44,6 +44,31 @@ public static string GetPrefixForInterpolation(Mode newInterpolationMode)
return null;
}
+ // Maps all rotation euler interpolation variants to their m_LocalRotation equivalent
+ // so that node IDs stay stable when the interpolation mode changes.
+ private static readonly Dictionary s_PropertyNameForHashing = new Dictionary(StringComparer.Ordinal)
+ {
+ { "localEulerAnglesRaw", "m_LocalRotation" },
+ { "localEulerAnglesRaw.x", "m_LocalRotation.x" },
+ { "localEulerAnglesRaw.y", "m_LocalRotation.y" },
+ { "localEulerAnglesRaw.z", "m_LocalRotation.z" },
+ { "localEulerAnglesBaked", "m_LocalRotation" },
+ { "localEulerAnglesBaked.x", "m_LocalRotation.x" },
+ { "localEulerAnglesBaked.y", "m_LocalRotation.y" },
+ { "localEulerAnglesBaked.z", "m_LocalRotation.z" },
+ { "localEulerAngles", "m_LocalRotation" },
+ { "localEulerAngles.x", "m_LocalRotation.x" },
+ { "localEulerAngles.y", "m_LocalRotation.y" },
+ { "localEulerAngles.z", "m_LocalRotation.z" },
+ };
+
+ internal static string GetPropertyNameForHashing(System.Type type, string propertyName)
+ {
+ if (type != typeof(UnityEngine.Transform) || !propertyName.StartsWith("localEuler"))
+ return propertyName;
+ return s_PropertyNameForHashing.TryGetValue(propertyName, out string canonical) ? canonical : propertyName;
+ }
+
static List s_BindingsCache;
const string s_PropertyWithSuffixRegex = @"(?\.[xyz])$";
internal static EditorCurveBinding[] ConvertRotationPropertiesToInterpolationType(ReadOnlySpan selection, Mode newInterpolationMode)
diff --git a/Modules/AnimationWindow/Editor/Widgets/PlayControls.cs b/Modules/AnimationWindow/Editor/Widgets/PlayControls.cs
index c75317d93a..c615d2723a 100644
--- a/Modules/AnimationWindow/Editor/Widgets/PlayControls.cs
+++ b/Modules/AnimationWindow/Editor/Widgets/PlayControls.cs
@@ -71,6 +71,9 @@ public void Dispose()
public void Update()
{
+ if (playToggle.enabledSelf != m_State.canPlay)
+ playToggle.SetEnabled(m_State.canPlay);
+
if (playToggle.value != m_State.playing)
playToggle.SetValueWithoutNotify(m_State.playing);
diff --git a/Modules/AssetBundle/Managed/AssetBundle.bindings.cs b/Modules/AssetBundle/Managed/AssetBundle.bindings.cs
index 92e3696344..858acbec5a 100644
--- a/Modules/AssetBundle/Managed/AssetBundle.bindings.cs
+++ b/Modules/AssetBundle/Managed/AssetBundle.bindings.cs
@@ -35,7 +35,7 @@ public enum AssetBundleLoadResult
[NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadFromManagedStreamAsyncOperation.h")]
[NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadAssetOperation.h")]
[NativeHeader("Runtime/Scripting/ScriptingExportUtility.h")]
- [NativeHeader("Runtime/Scripting/ScriptingUtility.h")]
+ [NativeHeader("Scripting/ScriptingUtility.h")]
[NativeHeader("AssetBundleScriptingClasses.h")]
[NativeHeader("Modules/AssetBundle/Public/AssetBundleSaveAndLoadHelper.h")]
[NativeHeader("Modules/AssetBundle/Public/AssetBundleUtility.h")]
diff --git a/Modules/AssetDatabase/Editor/V2/Managed/ImportActivityWindow.cs b/Modules/AssetDatabase/Editor/V2/Managed/ImportActivityWindow.cs
index 55f51776e0..e91e2c1b72 100644
--- a/Modules/AssetDatabase/Editor/V2/Managed/ImportActivityWindow.cs
+++ b/Modules/AssetDatabase/Editor/V2/Managed/ImportActivityWindow.cs
@@ -904,7 +904,10 @@ private void RevealSelectedArtifactInfinder()
const string kUDSTempFolder = "Temp/UDS";
Directory.CreateDirectory(kUDSTempFolder);
var tempPath = Path.Combine(kUDSTempFolder, Path.GetFileName(entry.libraryPath));
- FileUtil.CopyFileOrDirectory(entry.libraryPath, tempPath);
+
+ if (!File.Exists(tempPath))
+ FileUtil.CopyFileOrDirectory(entry.libraryPath, tempPath);
+
EditorUtility.RevealInFinder(tempPath);
}
else
diff --git a/Modules/AssetPackageEditor/Managed/SignatureService.cs b/Modules/AssetPackageEditor/Managed/SignatureService.cs
index 4005c35524..dbb8a48e57 100644
--- a/Modules/AssetPackageEditor/Managed/SignatureService.cs
+++ b/Modules/AssetPackageEditor/Managed/SignatureService.cs
@@ -38,7 +38,7 @@ internal class SignatureService
public SignatureService()
{
// We get those here while in the main thread to make sure UnityConnect is properly initialized and we have the correct access token and base url even if they change during the editor session
- m_BaseUrl = UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudPackagesApi);
+ m_BaseUrl = UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.EcosystemApi);
// This should only be called in the main thread as it relies on UnityConnect which is not thread safe, but we want to be able to update the access token in case it changes during the editor session
m_AccessToken = UnityConnect.instance.GetAccessToken();
diff --git a/Modules/AssetPackageEditor/Managed/SignedAssetPackage.cs b/Modules/AssetPackageEditor/Managed/SignedAssetPackage.cs
index d735ce8e5b..3e9528d286 100644
--- a/Modules/AssetPackageEditor/Managed/SignedAssetPackage.cs
+++ b/Modules/AssetPackageEditor/Managed/SignedAssetPackage.cs
@@ -3,6 +3,7 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
+using System.Security.Cryptography;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Scripting;
@@ -40,27 +41,27 @@ public static void CreateSignedAssetPackage(string sourcePath, string destinatio
internal static async Task InsertAttestationFileIntoTarball(string sourcePath, string destinationPath, string ownerOrgId, SignatureService signatureService)
{
- var tarball = Tarball.GetUncompressedTarball(sourcePath);
-
- using (var sha256 = System.Security.Cryptography.SHA256.Create())
+ byte[] hash;
+ using (var sha256 = SHA256.Create())
+ using (var tarball = Tarball.OpenUncompressedTarball(sourcePath))
{
- var hash = sha256.ComputeHash(tarball.Span.ToArray());
- var integrity = GetIntegrityStringFromSha256Digest(hash);
-
- var attestation = await signatureService.RequestAttestationFromPackageRegistry(integrity, ownerOrgId);
+ hash = sha256.ComputeHash(tarball);
+ }
+ var integrity = GetIntegrityStringFromSha256Digest(hash);
- byte[] attestationFile;
- try
- {
- attestationFile = Convert.FromBase64String(attestation);
- }
- catch (FormatException)
- {
- throw new FormatException("Attestation file is not a valid base64 string");
- }
+ var attestation = await signatureService.RequestAttestationFromPackageRegistry(integrity, ownerOrgId);
- Tarball.InsertFileAtStart(tarball, destinationPath, AttestationFilename, attestationFile);
+ byte[] attestationFile;
+ try
+ {
+ attestationFile = Convert.FromBase64String(attestation);
+ }
+ catch (FormatException)
+ {
+ throw new FormatException("Attestation file is not a valid base64 string");
}
+
+ Tarball.InsertFileAtStart(sourcePath, destinationPath, AttestationFilename, attestationFile, expectedSourceSha256: hash);
}
internal static string GetIntegrityStringFromSha256Digest(ReadOnlySpan digest)
diff --git a/Modules/AssetPackageEditor/Managed/Tarball.cs b/Modules/AssetPackageEditor/Managed/Tarball.cs
index 38a8f0fa23..a2d2a5bec9 100644
--- a/Modules/AssetPackageEditor/Managed/Tarball.cs
+++ b/Modules/AssetPackageEditor/Managed/Tarball.cs
@@ -5,18 +5,19 @@
using System;
using System.IO;
using System.IO.Compression;
+using System.Security.Cryptography;
namespace UnityEditor.AssetPackage
{
- using ContentHandler = System.Action;
-
- internal class MalformedTarball : Exception;
+ internal class MalformedTarballException(string message) : Exception(message);
///
/// Contains methods for working with tarballs.
///
internal static class Tarball
{
+ const int k_CopyBufferSize = 100 * 1024;
+
///
/// Creates a GZip-compressed tarball from a folder.
///
@@ -27,54 +28,109 @@ public static void CreateTarballFromFolder(string sourceDirectory, string output
if (!Directory.Exists(sourceDirectory))
throw new DirectoryNotFoundException($"Source directory not found: {sourceDirectory}");
- using var outStream = File.Create(outputTarGzPath);
- using var gzip = new GZipStream(outStream, CompressionLevel.Fastest);
-
- var files = Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories);
- foreach (var filePath in files)
+ // Write through a temporary file so a failure never leaves a partial tarball at the output path
+ var tempPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(outputTarGzPath)), Path.GetRandomFileName());
+ try
+ {
+ using (var outStream = File.Create(tempPath))
+ using (var gzip = new GZipStream(outStream, CompressionLevel.Fastest))
+ {
+ var files = Directory.EnumerateFiles(sourceDirectory, "*", SearchOption.AllDirectories);
+ foreach (var filePath in files)
+ {
+ var relativePath = Path.GetRelativePath(sourceDirectory, filePath).Replace('\\', '/');
+ // Use last write time as file mod time (Unix timestamp, clamped as pre-1970 times are not encodable)
+ var fileModTime = Math.Max(0, new DateTimeOffset(File.GetLastWriteTimeUtc(filePath)).ToUnixTimeSeconds());
+ using var file = File.OpenRead(filePath);
+ TarballCore.WriteEntry(gzip, relativePath, file, file.Length, fileModTime);
+ }
+ // Write two empty blocks at the end of the tarball (standard tar format)
+ gzip.Write(new byte[TarballCore.RecordSize * 2]);
+ }
+ if (File.Exists(outputTarGzPath))
+ File.Replace(tempPath, outputTarGzPath, null);
+ else
+ File.Move(tempPath, outputTarGzPath);
+ }
+ catch
{
- var relativePath = Path.GetRelativePath(sourceDirectory, filePath).Replace('\\', '/');
- var fileBytes = File.ReadAllBytes(filePath);
- // Use last write time as file mod time (Unix timestamp)
- var fileModTime = new DateTimeOffset(File.GetLastWriteTimeUtc(filePath)).ToUnixTimeSeconds();
- TarballCore.WriteEntry(gzip, relativePath, fileBytes, fileModTime);
+ try
+ {
+ File.Delete(tempPath);
+ }
+ catch (IOException)
+ {
+ // Never mask the original exception with a cleanup failure
+ }
+ throw;
}
- // Write two empty blocks at the end of the tarball (standard tar format)
- gzip.Write(new byte[TarballCore.RecordSize * 2]);
}
///
- /// Inserts a file at the start of a tarball.
+ /// Inserts a file at the start of a compressed tarball.
///
- /// The tarball.
- /// The path to the tarball.
+ /// The path to the source tarball.
+ /// The output tarball path (may be the same as the source path).
/// The filename of the file to insert.
/// The file to insert.
- public static void InsertFileAtStart(ReadOnlyMemory tarball, string path, string filename, ReadOnlySpan file, long fileModTime = 0)
+ /// The inserted file modification time (seconds since the Unix epoch).
+ /// When non-empty, the SHA-256 digest the uncompressed source content must
+ /// match; the destination is left untouched on mismatch.
+ public static void InsertFileAtStart(string tarballPath, string destinationPath, string filename, ReadOnlySpan file, long fileModTime = 0, ReadOnlySpan expectedSourceSha256 = default)
{
- using var output = new GZipStream(File.Create(path), CompressionLevel.Fastest);
- TarballCore.WriteEntry(output, filename, file, fileModTime);
- output.Write(tarball.Span);
+ // Stream through a temporary file so the source is never buffered in memory
+ // and the destination can safely be the source itself.
+ var tempPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(destinationPath)), Path.GetRandomFileName());
+ try
+ {
+ using (var sha256 = SHA256.Create())
+ using (var tarball = OpenUncompressedTarball(tarballPath))
+ using (var output = new GZipStream(File.Create(tempPath), CompressionLevel.Fastest))
+ {
+ TarballCore.WriteEntry(output, filename, file, fileModTime);
+
+ long copied = 0;
+ var buffer = new byte[k_CopyBufferSize];
+ int read;
+ while ((read = tarball.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ output.Write(buffer, 0, read);
+ sha256.TransformBlock(buffer, 0, read, null, 0);
+ copied += read;
+ }
+ if (copied < 2 * TarballCore.RecordSize)
+ throw new MalformedTarballException($"Input is not a tarball: {tarballPath}");
+
+ sha256.TransformFinalBlock(Array.Empty(), 0, 0);
+ if (!expectedSourceSha256.IsEmpty && !expectedSourceSha256.SequenceEqual(sha256.Hash))
+ throw new IOException($"'{tarballPath}' changed after its content digest was computed");
+ }
+ // Atomically replace the destination so a failure cannot destroy an existing file (e.g. an in-place source)
+ if (File.Exists(destinationPath))
+ File.Replace(tempPath, destinationPath, null);
+ else
+ File.Move(tempPath, destinationPath);
+ }
+ catch
+ {
+ try
+ {
+ File.Delete(tempPath);
+ }
+ catch (IOException)
+ {
+ // Never mask the original exception with a cleanup failure
+ }
+ throw;
+ }
}
///
- /// Gets the content of a compressed tarball.
+ /// Opens a read-only stream over the uncompressed content of a compressed tarball.
///
/// The path to the tarball.
- /// The content of the tarball.
- public static ReadOnlyMemory GetUncompressedTarball(string tarballPath)
- {
- using var ms = new MemoryStream();
- using (var gz = new GZipStream(File.OpenRead(tarballPath), CompressionMode.Decompress))
- {
- gz.CopyTo(ms);
- }
- var output = ms.ToArray();
-
- if (output.Length < 2*TarballCore.RecordSize)
- throw new ArgumentException("input is not a tarball", tarballPath);
-
- return new ReadOnlyMemory(output);
- }
+ /// A stream over the uncompressed content of the tarball.
+ public static Stream OpenUncompressedTarball(string tarballPath)
+ => new GZipStream(File.OpenRead(tarballPath), CompressionMode.Decompress);
}
}
diff --git a/Modules/AssetPackageEditor/Managed/TarballCore.cs b/Modules/AssetPackageEditor/Managed/TarballCore.cs
index a7b162735e..8ee393c4c2 100644
--- a/Modules/AssetPackageEditor/Managed/TarballCore.cs
+++ b/Modules/AssetPackageEditor/Managed/TarballCore.cs
@@ -92,8 +92,8 @@ private static void EncodeEntryHeader(Span dest, string filename, long fil
///
/// The size of the file.
/// The padding size.
- private static int GetTarFilePaddingSize(int fileSize)
- => 511 - (fileSize + 511) % 512;
+ private static int GetTarFilePaddingSize(long fileSize)
+ => (int)(511 - (fileSize + 511) % 512);
/// Writes a tar entry (header, contents and padding) to a stream.
public static void WriteEntry(Stream stream, string filename, ReadOnlySpan fileData, long fileModTime)
@@ -106,5 +106,33 @@ public static void WriteEntry(Stream stream, string filename, ReadOnlySpan
padding.Clear();
stream.Write(padding);
}
+
+ /// Writes a tar entry (header, contents and padding) to a stream, streaming the contents.
+ /// Avoids buffering the file contents in memory, supporting entries up to the tar limit of 8.5 GB.
+ public static void WriteEntry(Stream stream, string filename, Stream fileData, long fileSize, long fileModTime)
+ {
+ if (fileSize > ElevenOctalDigitLimit)
+ throw new IOException($"'{filename}' is {fileSize} bytes, exceeding the tar entry limit of {ElevenOctalDigitLimit} bytes");
+
+ Span header = stackalloc byte[RecordSize];
+ EncodeEntryHeader(header, filename, fileSize, fileModTime);
+ stream.Write(header);
+
+ // Copy exactly fileSize bytes so a file mutated mid-copy cannot silently corrupt the archive
+ Span buffer = stackalloc byte[4096];
+ long remaining = fileSize;
+ while (remaining > 0)
+ {
+ var read = fileData.Read(buffer[..(int)Math.Min(buffer.Length, remaining)]);
+ if (read == 0)
+ throw new IOException($"'{filename}' ended after {fileSize - remaining} bytes, expected {fileSize} bytes");
+ stream.Write(buffer[..read]);
+ remaining -= read;
+ }
+
+ var padding = header[..GetTarFilePaddingSize(fileSize)];
+ padding.Clear();
+ stream.Write(padding);
+ }
}
}
diff --git a/Modules/AssetPackageUIEditor/Managed/PackageImport.cs b/Modules/AssetPackageUIEditor/Managed/PackageImport.cs
index 82d513f8bd..b3a8891ebe 100644
--- a/Modules/AssetPackageUIEditor/Managed/PackageImport.cs
+++ b/Modules/AssetPackageUIEditor/Managed/PackageImport.cs
@@ -68,7 +68,7 @@ public Constants()
[NativeHeader("Modules/AssetPackageEditor/AssetPackage.bindings.h")]
[FreeFunction("Marshalling::GetAssetPackageInfo")]
- private static extern AssetPackageInfo GetAssetPackageInfo(IntPtr nativeAssetPackageInfo);
+ internal static extern AssetPackageInfo GetAssetPackageInfo(IntPtr nativeAssetPackageInfo);
// Invoked from menu
[UsedByNativeCode]
@@ -607,8 +607,10 @@ internal sealed class PackageImportWizard : ScriptableSingleton m_AssetPackageInfo;
- public bool isAssetStorePackage => m_AssetOrigin.IsValid();
+ public bool isAssetStorePackage => m_AssetOrigin.IsValid() || m_IsNestedAssetStorePackage;
public void StartImport(string packagePath, ImportPackageItem[] items, string packageIconPath, AssetOrigin origin, string packageExtractedPath, AssetPackageInfo assetPackageInfo)
{
@@ -620,6 +622,7 @@ public void StartImport(string packagePath, ImportPackageItem[] items, string pa
m_AssetOrigin = origin;
m_PackageExtractedPath = packageExtractedPath;
m_AssetPackageInfo = assetPackageInfo;
+ m_IsNestedAssetStorePackage = !origin.IsValid() && IsPackageNestedInsideAssetStoreAsset(packagePath);
m_InitialImportItems = items;
foreach (var item in items)
@@ -720,6 +723,19 @@ private void ClearImportData()
m_IsMultiStepWizard = false;
m_IsProjectSettingStep = false;
m_AssetPackageInfo = null;
+ m_IsNestedAssetStorePackage = false;
+ }
+
+ // Some Asset Store packages bundle other .unitypackage files inside them (what we refer to as "nested" packages).
+ // We want to treat an inner one as asset-store-sourced so its import does not raise a trust warning for unsigned packages.
+ static bool IsPackageNestedInsideAssetStoreAsset(string packagePath)
+ {
+ if (string.IsNullOrEmpty(packagePath))
+ return false;
+ var guid = AssetDatabase.AssetPathToGUID(packagePath, AssetPathToGUIDOptions.OnlyExistingAssets);
+ if (string.IsNullOrEmpty(guid))
+ return false;
+ return AssetDatabase.GetAssetOrigin(guid).IsValid();
}
public bool AreAnyElementsSelected()
diff --git a/Modules/AssetPipelineEditor/ImportSettings/AssetImporterEditor.cs b/Modules/AssetPipelineEditor/ImportSettings/AssetImporterEditor.cs
index 922897d138..355bf63ae3 100644
--- a/Modules/AssetPipelineEditor/ImportSettings/AssetImporterEditor.cs
+++ b/Modules/AssetPipelineEditor/ImportSettings/AssetImporterEditor.cs
@@ -379,6 +379,23 @@ public virtual void OnEnable()
finishedDefaultHeaderGUI += DrawAssetHasIssuesNotification;
AssetImporterEditorPostProcessAsset.OnAssetbundleNameChanged += FixImporterAssetbundleName;
+ // A target importer's native object can be destroyed while this managed editor is still
+ // alive: the asset was deleted or its .meta guid was rewritten on disk, then a domain
+ // reload re-awakes this editor from backup (MonoBehaviour.DidReloadDomain -> OnEnable).
+ // Target-dependent initialization below would either dereference a dangling EntityId
+ // (native crash in CreateOrReloadInspectorCopy/WriteObjectToVector) or throw
+ // (GetAssetPaths().First() on an empty sequence). A destroyed target is a valid, inert
+ // state for an editor: subscribe/unsubscribe symmetrically, mark it enabled, and stop.
+ if (!AreImporterTargetsValid())
+ {
+ Debug.Log("AssetImporterEditor: one or more inspected importer targets no longer exist (asset deleted or its GUID changed); skipping inspector setup.");
+ m_Postprocessors = new List();
+ m_TargetsEntityId = new List();
+ m_OnEnableCalled = true;
+ isInspectorDirty = true;
+ return;
+ }
+
InitializeAvailableImporters();
InitializeUnsavedChangesCache();
InitializePostprocessors();
@@ -395,6 +412,22 @@ public virtual void OnEnable()
isInspectorDirty = true;
}
+ // True only when every target importer's native object still exists. A target can be
+ // destroyed (asset deleted, or its .meta GUID rewritten on disk) while this managed editor
+ // is still alive and later re-enabled by a domain reload. Subclasses must call this before
+ // accessing serializedObject or other target-dependent state; otherwise serializedObject
+ // throws SerializedObjectNotCreatableException and native code dereferences a stale EntityId.
+ protected bool AreImporterTargetsValid()
+ {
+ foreach (var t in targets)
+ {
+ var importer = t as AssetImporter;
+ if (importer == null) // UnityEngine.Object overloaded ==: true for null or destroyed
+ return false;
+ }
+ return true;
+ }
+
public virtual void OnDisable()
{
finishedDefaultHeaderGUI -= DrawAssetHasIssuesNotification;
diff --git a/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs b/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs
index 0f374e6005..ac7ce2a10e 100644
--- a/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs
+++ b/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs
@@ -24,6 +24,8 @@ internal abstract class AssetImporterTabbedEditor : AssetImporterEditor
public override void OnEnable()
{
base.OnEnable();
+ if (!AreImporterTargetsValid()) // asset gone: base already logged and bailed; do not enable tabs on a dead target
+ return;
foreach (var tab in m_Tabs)
{
diff --git a/Modules/AssetPipelineEditor/ImportSettings/AudioImporterInspector.cs b/Modules/AssetPipelineEditor/ImportSettings/AudioImporterInspector.cs
index 7876aa20bf..7aa441e053 100644
--- a/Modules/AssetPipelineEditor/ImportSettings/AudioImporterInspector.cs
+++ b/Modules/AssetPipelineEditor/ImportSettings/AudioImporterInspector.cs
@@ -187,6 +187,8 @@ public bool CurrentSelectionContainsHardwareSounds()
public override void OnEnable()
{
base.OnEnable();
+ if (!AreImporterTargetsValid()) // asset gone: base already logged and bailed
+ return;
m_ForceToMono = serializedObject.FindProperty("m_ForceToMono");
m_Normalize = serializedObject.FindProperty("m_Normalize");
diff --git a/Modules/AssetPipelineEditor/ImportSettings/PluginImporterInspector.cs b/Modules/AssetPipelineEditor/ImportSettings/PluginImporterInspector.cs
index 2ebbfc2677..8c364a8846 100644
--- a/Modules/AssetPipelineEditor/ImportSettings/PluginImporterInspector.cs
+++ b/Modules/AssetPipelineEditor/ImportSettings/PluginImporterInspector.cs
@@ -491,6 +491,8 @@ protected override void Awake()
public override void OnEnable()
{
base.OnEnable();
+ if (!AreImporterTargetsValid()) // asset gone: base already logged and bailed
+ return;
// this method is doing a lot of setup and it used to be called in awake for some old reasons, which is not the case anymore.
DiscardChanges();
diff --git a/Modules/Audio/Public/ScriptBindings/Audio.bindings.cs b/Modules/Audio/Public/ScriptBindings/Audio.bindings.cs
index 5a022fce8f..4f57a74fa0 100644
--- a/Modules/Audio/Public/ScriptBindings/Audio.bindings.cs
+++ b/Modules/Audio/Public/ScriptBindings/Audio.bindings.cs
@@ -59,7 +59,9 @@ public enum AudioSpeakerMode
// Channel count is set to 8. 7.1 speaker setup. This includes front left, front right, center, rear left, rear right, side left, side right and a subwoofer.
Mode7point1 = 6,
// Channel count is set to 2. Stereo output, but data is encoded in a way that is picked up by a Prologic/Prologic2 decoder and split into a 5.1 speaker setup.
- Prologic = 7
+ Prologic = 7,
+ // Channel count is set to 12. 7.1.4 speaker setup. This includes front left, front right, center, rear left, rear right, side left, side right, top front left, top front right, top rear left, top rear right and a subwoofer.This speaker mode is only available when the Enhanced Audio Foundation is active.
+ Mode7point1point4 = 13
}
internal enum AudioFoundation
@@ -108,7 +110,7 @@ public static int ChannelCount(this AudioSpeakerMode speakerMode)
case AudioSpeakerMode.Mode5point1: return 6;
case AudioSpeakerMode.Mode7point1: return 8;
case AudioSpeakerMode.Prologic: return 2;
- throw new ArgumentException($"{nameof(speakerMode)}");
+ case AudioSpeakerMode.Mode7point1point4: return 12;
}
throw new ArgumentException($"{nameof(speakerMode)}");
@@ -1067,6 +1069,14 @@ internal extern bool isContainerPlaying
get;
}
+ // Whether the source is in the audio manager's per-frame update list. Test-only: lets tests
+ // assert that an idle source is cleaned up again after external playback ends.
+ internal extern bool isRegisteredWithAudioManager
+ {
+ [NativeName("IsRegisteredWithAudioManager")]
+ get;
+ }
+
internal extern ActivePlayable[] containerActivePlayables { get; }
extern public bool isVirtual
diff --git a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ControlContext.cs b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ControlContext.cs
index fd6313de26..6ce4271957 100644
--- a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ControlContext.cs
+++ b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ControlContext.cs
@@ -229,30 +229,39 @@ public readonly GeneratorInstance AllocateGenerator(
{
m_Handle.CheckValidOrThrow();
- var generatorChunk = ProcessorExtensions.CAllocChunk.ControlStorage>();
-
- var header = &generatorChunk->HeaderAndProcessor.Header;
+ DualThreadHandle createdHandle;
+ {
+ // Stage the ControlStorage on the stack. Native memcpys it into the bridge slab tail; this local
+ // dies as soon as InitializeGeneratorHandle returns.
+ IGeneratorControlExtensions.JobStruct.ControlStorage storage;
- header->Processor.ProcessorReflectionData = IGeneratorProcessorExtensions.GetReflectionData();
- header->Processor.ControlReflectionData = IGeneratorControlExtensions.GetReflectionData();
+ storage.HeaderAndProcessor.Header = default;
+ storage.HeaderAndProcessor.Header.Processor.ProcessorReflectionData = IGeneratorProcessorExtensions.GetReflectionData();
+ storage.HeaderAndProcessor.Header.Processor.ControlReflectionData = IGeneratorControlExtensions.GetReflectionData();
- header->Configuration.IsRealtime = realtimeState.isRealtime;
- header->Configuration.IsFinite = realtimeState.isFinite;
+ storage.HeaderAndProcessor.Header.Configuration.IsRealtime = realtimeState.isRealtime;
+ storage.HeaderAndProcessor.Header.Configuration.IsFinite = realtimeState.isFinite;
- if (realtimeState.length is DiscreteTime time)
- {
- header->Configuration.ReportedLength = time;
- header->Configuration.HasKnownLength = true;
- }
+ if (realtimeState.length is DiscreteTime time)
+ {
+ storage.HeaderAndProcessor.Header.Configuration.ReportedLength = time;
+ storage.HeaderAndProcessor.Header.Configuration.HasKnownLength = true;
+ }
- generatorChunk->HeaderAndProcessor.UserProcessor = realtimeState;
- generatorChunk->UserControl = controlState;
+ storage.HeaderAndProcessor.UserProcessor = realtimeState;
+ storage.UserControl = controlState;
- var config = (nestedFormat ?? default).audioConfiguration;
+ var config = (nestedFormat ?? default).audioConfiguration;
- ScriptableGeneratorBindings.InitializeGeneratorHandle(header, m_Header, nestedFormat.HasValue ? &config : null, creationParameters.BuildInitializationFlags());
+ createdHandle = ScriptableGeneratorBindings.InitializeGeneratorHandle(
+ ref storage,
+ m_Header,
+ nestedFormat.HasValue ? &config : null,
+ creationParameters.BuildInitializationFlags()
+ );
+ }
- return new(header);
+ return new GeneratorInstance(GetProcessorHeader(createdHandle));
}
///
@@ -275,20 +284,28 @@ public readonly RootOutputInstance AllocateRootOutput(in TR
where TControl : unmanaged, RootOutputInstance.IControl
{
m_Handle.CheckValidOrThrow();
+ DualThreadHandle createdHandle;
- var outputChunk = ProcessorExtensions.CAllocChunk.ControlStorage>();
-
- var header = &outputChunk->HeaderAndProcessor.Header;
-
- header->ProcessorReflectionData = IRootOutputProcessorExtensions.GetReflectionData();
- header->ControlReflectionData = IRootOutputControlExtensions.GetReflectionData();
-
- outputChunk->HeaderAndProcessor.UserProcessor = realtimeState;
- outputChunk->UserControl = controlState;
-
- IRootOutputProcessorExtensions.InitializeRootOutputHandle(header, m_Header, creationParameters.BuildInitializationFlags());
+ {
+ // Stage the ControlStorage on the stack. Native memcpys it into the bridge slab tail; this local
+ // dies as soon as InitializeRootOutputHandle returns.
+ IRootOutputControlExtensions.JobStruct.ControlStorage storage;
+
+ storage.HeaderAndProcessor.Header = default;
+ storage.HeaderAndProcessor.Header.ProcessorReflectionData = IRootOutputProcessorExtensions.GetReflectionData();
+ storage.HeaderAndProcessor.Header.ControlReflectionData = IRootOutputControlExtensions.GetReflectionData();
+
+ storage.HeaderAndProcessor.UserProcessor = realtimeState;
+ storage.UserControl = controlState;
+
+ createdHandle = IRootOutputProcessorExtensions.InitializeRootOutputHandle(
+ ref storage,
+ m_Header,
+ creationParameters.BuildInitializationFlags()
+ );
+ }
- return new(header);
+ return new RootOutputInstance(GetProcessorHeader(createdHandle));
}
///
@@ -567,6 +584,18 @@ internal static unsafe void CleanupHeader(ref ControlHeader header)
}
}
+ ///
+ /// Transition API until a call is made on whether "headers" should be persistently available in "handle wrappers" or not.
+ /// Alternative being resolving on demand, making sure the handle is actually alive and available, at the expense of an ICall every time.
+ /// This is currently necessary to avoid a large number of changes across the codebase, but will likely be removed in the future.
+ ///
+ unsafe readonly THeader* GetProcessorHeader(DualThreadHandle handle)
+ where THeader : unmanaged
+ {
+ m_Handle.CheckValidOrThrow();
+ return (THeader*)ScriptableProcessorBindings.GetProcessorHeaderFromHandle(m_Header, handle);
+ }
+
[NativeMethod(Name = "audio::GetBuiltInControlHeader", IsFreeFunction = true)]
static extern unsafe internal void* InternalGetBuiltInControlHeader();
diff --git a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableGenerator.bindings.cs b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableGenerator.bindings.cs
index 740af3f8d0..f72022c470 100644
--- a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableGenerator.bindings.cs
+++ b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableGenerator.bindings.cs
@@ -714,10 +714,20 @@ internal static unsafe void InstantiateGeneratorFromObject(Object generatorObjec
}
}
- internal static unsafe void InitializeGeneratorHandle(GeneratorInstance.GeneratorHeader* header, ControlHeader* control, AudioConfiguration* nestedConfiguration, ProcessorInstance.InitializationFlags flags)
- => InternalInitializeGeneratorHandle(header, control, nestedConfiguration, flags);
+ internal static unsafe DualThreadHandle InitializeGeneratorHandle(
+ ref IGeneratorControlExtensions.JobStruct.ControlStorage storage,
+ ControlHeader* control,
+ AudioConfiguration* nestedConfiguration,
+ ProcessorInstance.InitializationFlags flags
+ )
+ where TRealtime : unmanaged, GeneratorInstance.IRealtime
+ where TControl : unmanaged, GeneratorInstance.IControl
+ {
+ fixed (GeneratorInstance.GeneratorHeader* headerPtr = &storage.HeaderAndProcessor.Header)
+ return InternalInitializeGeneratorHandle(headerPtr, sizeof(IGeneratorControlExtensions.JobStruct.ControlStorage), control, nestedConfiguration, flags);
+ }
[NativeMethod(Name = "audio::InitializeGeneratorHandle", IsFreeFunction = true, ThrowsException = true)]
- static extern unsafe void InternalInitializeGeneratorHandle(/*Generator.GeneratorHeader* */void* header, /*ControlHeader*/ void* control, AudioConfiguration* nestedConfiguration, ProcessorInstance.InitializationFlags flags);
+ static extern unsafe DualThreadHandle InternalInitializeGeneratorHandle(/*Generator.GeneratorHeader* */void* header, int tailSize, /*ControlHeader*/ void* control, AudioConfiguration* nestedConfiguration, ProcessorInstance.InitializationFlags flags);
}
}
diff --git a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableProcessor.bindings.cs b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableProcessor.bindings.cs
index 0b8e06b426..3b7cd6b712 100644
--- a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableProcessor.bindings.cs
+++ b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableProcessor.bindings.cs
@@ -751,6 +751,12 @@ public static unsafe ProcessorInstance.Response SendMessageToProcessor(Processor
return SendMessageToProcessorInternal(header, control, message);
}
+ public static unsafe ProcessorHeader* GetProcessorHeaderFromHandle(ControlHeader* control, DualThreadHandle handle)
+ {
+ return (ProcessorHeader*)GetProcessorHeaderFromHandleInternal(control, handle);
+ }
+ [NativeMethod(Name = "audio::GetProcessorHeaderFromHandle", IsFreeFunction = true)]
+ static extern unsafe /*ProcessorHeader*/ void* GetProcessorHeaderFromHandleInternal(/*ControlHeader*/ void* control, DualThreadHandle handle);
[NativeMethod(Name = "audio::SendMessageToProcessor", IsFreeFunction = true, ThrowsException = true)]
static extern unsafe ProcessorInstance.Response SendMessageToProcessorInternal(/*ProcessorHeader* */ void* header, /*ControlHeader* */ void* control, /* Message* */ void* message);
@@ -791,14 +797,6 @@ public static unsafe ProcessorInstance.Response SendMessageToProcessor(Processor
static class ProcessorExtensions
{
- internal static unsafe T* CAllocChunk()
- where T : unmanaged
- {
- var chunk = (T*)UnsafeUtility.MallocTracked(sizeof(T), UnsafeUtility.AlignOf(), Allocator.Persistent, 3);
- *chunk = default;
- return chunk;
- }
-
public static unsafe void DispatchGenericControl(ref TControl control, ref TRealtime realtime, in ProcessorHeader header, void* additionalPtr, ControlFunction function)
where TControl : unmanaged, ProcessorInstance.IControl
where TRealtime : unmanaged, ProcessorInstance.IRealtime
@@ -809,10 +807,8 @@ public static unsafe void DispatchGenericControl(ref TContr
{
var args = (DisposeArguments*)additionalPtr;
control.Dispose(new(args->ControlContext), ref realtime);
-
- fixed (ProcessorHeader* pHeader = &header)
- UnsafeUtility.FreeTracked(pHeader, Allocator.Persistent);
-
+ // No header free here: the header lives inside the bridge's native-owned slab, which
+ // the DTM frees with UNITY_FREE once this dispatch returns up through the destructor.
break;
}
case ControlFunction.Update:
diff --git a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableRootOutput.bindings.cs b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableRootOutput.bindings.cs
index 9c67cfff8c..044f8711c1 100644
--- a/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableRootOutput.bindings.cs
+++ b/Modules/Audio/Public/ScriptableProcessors/ScriptBindings/ScriptableRootOutput.bindings.cs
@@ -271,7 +271,7 @@ internal struct Storage
internal static unsafe void Initialize()
{
if (jobReflectionData.Data == IntPtr.Zero)
- jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(Storage), (ExecuteJobFunction)Execute);
+ jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(Storage), typeof(TUserProcessor), (ExecuteJobFunction)Execute);
}
internal delegate void ExecuteJobFunction(ref Storage storage, IntPtr additionalPtr, IntPtr additionalPtr2, ref JobRanges ranges, int jobIndex);
@@ -330,12 +330,22 @@ internal static IntPtr GetReflectionData()
return reflectionData;
}
- internal static unsafe void InitializeRootOutputHandle(ProcessorHeader* header, ControlHeader* control, ProcessorInstance.InitializationFlags flags)
- => InternalInitializeRootOutputHandle(header, control, flags);
+ internal static unsafe DualThreadHandle InitializeRootOutputHandle(
+ ref IRootOutputControlExtensions.JobStruct.ControlStorage storage,
+ ControlHeader* control,
+ ProcessorInstance.InitializationFlags flags
+ )
+ where TRealtime : unmanaged, RootOutputInstance.IRealtime
+ where TControl : unmanaged, RootOutputInstance.IControl
+
+ {
+ fixed (ProcessorHeader* header = &storage.HeaderAndProcessor.Header)
+ return InternalInitializeRootOutputHandle(header, sizeof(IRootOutputControlExtensions.JobStruct.ControlStorage), control, flags);
+ }
// Intermediate above exists because otherwise bindings layer will throw.
[NativeMethod(Name = "audio::InitializeRootOutputHandle", IsFreeFunction = true, ThrowsException = true)]
- static extern unsafe void InternalInitializeRootOutputHandle(/*ScriptingProcessorHeader*/ void* header, /*ControlHeader*/ void* control, ProcessorInstance.InitializationFlags flags);
+ static extern unsafe DualThreadHandle InternalInitializeRootOutputHandle(/*ScriptingProcessorHeader*/ void* header, int tailSize, /*ControlHeader*/ void* control, ProcessorInstance.InitializationFlags flags);
}
#endregion
diff --git a/Modules/BuildAnalysis/Data/Models/BuildAnalysis.cs b/Modules/BuildAnalysis/Data/Models/BuildAnalysis.cs
index 9124f364de..2f5545a646 100644
--- a/Modules/BuildAnalysis/Data/Models/BuildAnalysis.cs
+++ b/Modules/BuildAnalysis/Data/Models/BuildAnalysis.cs
@@ -16,6 +16,28 @@ internal class BuildAnalysis
public BuildAnalysisTables Tables = new BuildAnalysisTables();
public BuildAnalysisMessage[] Messages = Array.Empty();
public BuildAnalysisComputed Computed = new BuildAnalysisComputed();
+
+ // Where the Assets table came from. Populated when this build recorded no assets of its own
+ // (e.g. a scripts-only build) and the data was borrowed from an earlier complete build.
+ public BuildAnalysisAssetSource AssetSource = new BuildAnalysisAssetSource();
+ }
+
+ [Serializable]
+ internal class BuildAnalysisAssetSource
+ {
+ // The complete build this build reused content from (BuildReportSummary.ContentSourceBuildSessionGUID).
+ // Empty for builds that produced their own content; set for asset-less scripts-only / incremental builds.
+ public GUID ContentSourceBuildSessionGUID;
+
+ // The content-source build's start time; set only when that build was found and its assets borrowed.
+ public string BuildStartedAtUtc = string.Empty;
+
+ // The content-source build was found and its assets borrowed.
+ public bool IsBorrowed;
+
+ // A content source was declared but couldn't be resolved (pruned/deleted, or its report missing), so the
+ // reused assets are unknown.
+ public bool SourceUnavailable => !IsBorrowed && !ContentSourceBuildSessionGUID.Empty();
}
[Serializable]
@@ -84,6 +106,7 @@ internal struct BuildAnalysisRootAsset
public ulong DirectSizeBytes;
public int TotalAssetCount;
public ulong TotalSizeBytes;
+ public int[] ReferencedAssetIds;
}
[Serializable]
diff --git a/Modules/BuildAnalysis/Data/Models/RootAssetStats.cs b/Modules/BuildAnalysis/Data/Models/RootAssetStats.cs
index 13721bf8ce..4d79a3c5a6 100644
--- a/Modules/BuildAnalysis/Data/Models/RootAssetStats.cs
+++ b/Modules/BuildAnalysis/Data/Models/RootAssetStats.cs
@@ -19,5 +19,6 @@ internal struct RootAssetStats
public ulong DirectSize;
public int TotalAssets;
public ulong TotalSize;
+ public string[] ReferencedAssetPaths;
}
}
diff --git a/Modules/BuildAnalysis/Services/BuildAnalysisAssembler.cs b/Modules/BuildAnalysis/Services/BuildAnalysisAssembler.cs
new file mode 100644
index 0000000000..b2161c7e85
--- /dev/null
+++ b/Modules/BuildAnalysis/Services/BuildAnalysisAssembler.cs
@@ -0,0 +1,269 @@
+// Unity C# reference source
+// Copyright (c) Unity Technologies. For terms of use, see
+// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using UnityEngine;
+
+namespace UnityEditor.Build.Analysis
+{
+ internal static class BuildAnalysisAssembler
+ {
+ public static BuildAnalysis Assemble(
+ BuildReportSummary reportSummary,
+ BuildReportData reportData,
+ RootAssetStats[] rootStats,
+ SourceBuildAssets? sourceBuildAssets)
+ {
+ // An asset-less build (e.g. scripts-only) borrows the Assets table from an earlier complete build.
+ var assetData = sourceBuildAssets?.Assets ?? reportData.Assets;
+
+ // The content source this asset-less build declared, recorded even when it can't be resolved so the UI
+ // can tell "reused a build that's gone" from "genuinely has no assets". Empty for builds with own content.
+ var declaredContentSource = reportData.Assets.Length == 0
+ && !reportSummary.ContentSourceBuildSessionGUID.Empty()
+ && reportSummary.ContentSourceBuildSessionGUID != reportSummary.BuildSessionGUID
+ ? reportSummary.ContentSourceBuildSessionGUID
+ : default;
+
+ var stepTable = ConvertSteps(reportData.Steps);
+ var analysisMessages = ConvertMessages(reportData.Messages, stepTable.Length);
+ ConvertAssets(assetData, out var assetTable, out var importerTypeTable);
+ var rootAssetTable = ConvertRootAssets(rootStats, assetTable);
+ var computed = BuildComputed(
+ assetTable,
+ rootAssetTable,
+ analysisMessages,
+ reportData.CachedReusePercent);
+
+ var output = new BuildAnalysis
+ {
+ Version = BuildAnalysisConstants.k_SchemaVersion,
+ GeneratedAtUtc = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
+ Summary = new BuildAnalysisSummary
+ {
+ BuildSessionGUID = reportSummary.BuildSessionGUID.ToString(),
+ BuildName = reportSummary.BuildName ?? string.Empty,
+ BuildProfilePath = reportSummary.BuildProfilePath ?? string.Empty,
+ Platform = reportSummary.Platform.ToString(),
+ BuildResult = reportSummary.BuildResult.ToString(),
+ BuildStartedAtUtc = reportSummary.BuildStartedAt ?? string.Empty,
+ BuildType = reportSummary.BuildType.ToString(),
+ TotalSizeBytes = reportSummary.TotalSizeBytes,
+ TotalTimeMs = reportSummary.TotalTimeMs > 0 ? reportSummary.TotalTimeMs : reportData.TotalDurationMs,
+ TotalErrors = reportData.TotalErrors,
+ TotalWarnings = reportData.TotalWarnings,
+ BuildManifestHash = reportSummary.BuildManifestHash ?? string.Empty,
+ OutputPath = reportSummary.OutputPath ?? string.Empty,
+ BuildOptions = reportSummary.BuildOptions ?? Array.Empty(),
+ BuildContentOptions = reportSummary.BuildContentOptions ?? Array.Empty(),
+ },
+ Tables = new BuildAnalysisTables
+ {
+ Steps = stepTable,
+ Assets = assetTable,
+ ImporterTypes = importerTypeTable,
+ RootAssets = rootAssetTable,
+ },
+ Messages = analysisMessages,
+ Computed = computed,
+ AssetSource = BuildAssetSource(sourceBuildAssets, declaredContentSource),
+ };
+
+ return output;
+ }
+
+ private static BuildAnalysisAssetSource BuildAssetSource(SourceBuildAssets? sourceBuildAssets, GUID declaredContentSource)
+ {
+ // Not borrowed: keep the declared source so a still-unresolved one reads as source unavailable.
+ var borrowed = sourceBuildAssets.HasValue;
+ if (!borrowed)
+ return new BuildAnalysisAssetSource { ContentSourceBuildSessionGUID = declaredContentSource };
+
+ var source = sourceBuildAssets.Value;
+ return new BuildAnalysisAssetSource
+ {
+ ContentSourceBuildSessionGUID = source.BuildGuid,
+ BuildStartedAtUtc = source.BuildSummary.BuildStartedAt ?? string.Empty,
+ IsBorrowed = true,
+ };
+ }
+
+ private static BuildAnalysisStep[] ConvertSteps(BuildReportStepData[] steps)
+ {
+ var result = new BuildAnalysisStep[steps.Length];
+ for (var i = 0; i < steps.Length; i++)
+ {
+ var source = steps[i];
+ result[i] = new BuildAnalysisStep
+ {
+ Id = i,
+ Name = source.Name ?? string.Empty,
+ Depth = source.Depth,
+ DurationMs = source.DurationMs,
+ };
+ }
+
+ return result;
+ }
+
+ private static BuildAnalysisMessage[] ConvertMessages(BuildReportMessageData[] messages, int maxStepCount)
+ {
+ var result = new BuildAnalysisMessage[messages.Length];
+
+ for (var i = 0; i < messages.Length; i++)
+ {
+ var source = messages[i];
+ var stepIndex = source.StepIndex;
+ if (stepIndex < 0 || stepIndex >= maxStepCount)
+ stepIndex = -1;
+
+ result[i] = new BuildAnalysisMessage
+ {
+ Severity = source.Severity ?? string.Empty,
+ StepId = stepIndex,
+ Text = source.Content ?? string.Empty,
+ };
+ }
+
+ return result;
+ }
+
+ private static void ConvertAssets(
+ BuildReportAssetData[] sourceAssets,
+ out BuildAnalysisAsset[] assets,
+ out BuildAnalysisImporterType[] importerTypes)
+ {
+ if (sourceAssets.Length == 0)
+ {
+ assets = Array.Empty();
+ importerTypes = Array.Empty();
+ return;
+ }
+
+ var importerIdByName = new Dictionary(StringComparer.Ordinal);
+ var importerList = new List();
+
+ assets = new BuildAnalysisAsset[sourceAssets.Length];
+ for (var i = 0; i < sourceAssets.Length; i++)
+ {
+ var src = sourceAssets[i];
+ var importerKey = string.IsNullOrEmpty(src.ImporterTypeName) ? "Unknown" : src.ImporterTypeName;
+ if (!importerIdByName.TryGetValue(importerKey, out var importerId))
+ {
+ importerId = importerList.Count;
+ importerList.Add(new BuildAnalysisImporterType { Id = importerId, Name = importerKey });
+ importerIdByName[importerKey] = importerId;
+ }
+
+ assets[i] = new BuildAnalysisAsset
+ {
+ Id = i,
+ Path = src.Path ?? string.Empty,
+ GUID = src.GUID,
+ OutputSizeBytes = src.OutputSizeBytes,
+ ObjectCount = src.ObjectCount,
+ ResourceCount = src.ResourceCount,
+ ImporterTypeId = importerId,
+ };
+ }
+
+ importerTypes = importerList.ToArray();
+ }
+
+ private static BuildAnalysisRootAsset[] ConvertRootAssets(
+ RootAssetStats[] rootStats,
+ BuildAnalysisAsset[] assets)
+ {
+ if (rootStats.Length == 0)
+ return Array.Empty();
+
+ var pathToAssetId = new Dictionary(assets.Length, StringComparer.Ordinal);
+ foreach (var a in assets)
+ {
+ if (!string.IsNullOrEmpty(a.Path))
+ pathToAssetId[a.Path] = a.Id;
+ }
+
+ var result = new List(rootStats.Length);
+ foreach (var s in rootStats)
+ {
+ if (string.IsNullOrEmpty(s.AssetPath) || !pathToAssetId.TryGetValue(s.AssetPath, out var assetId))
+ {
+ // Root assets are project source assets that should appear in BuildReport.assetStats.
+ // Skip on the rare miss rather than emit a sentinel AssetId.
+ Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Root asset '{s.AssetPath}' not found in Assets table.");
+ continue;
+ }
+ result.Add(new BuildAnalysisRootAsset
+ {
+ Id = result.Count,
+ AssetId = assetId,
+ DirectAssetCount = s.DirectAssets,
+ DirectSizeBytes = s.DirectSize,
+ TotalAssetCount = s.TotalAssets,
+ TotalSizeBytes = s.TotalSize,
+ ReferencedAssetIds = ResolveReferencedAssetIds(s.ReferencedAssetPaths, pathToAssetId),
+ });
+ }
+ return result.ToArray();
+ }
+
+ private static int[] ResolveReferencedAssetIds(
+ string[] referencedAssetPaths,
+ Dictionary pathToAssetId)
+ {
+ if (referencedAssetPaths == null || referencedAssetPaths.Length == 0)
+ return Array.Empty();
+
+ var ids = new List(referencedAssetPaths.Length);
+ foreach (var path in referencedAssetPaths)
+ {
+ if (pathToAssetId.TryGetValue(path, out var id))
+ ids.Add(id);
+ }
+ return ids.Count == 0 ? Array.Empty() : ids.ToArray();
+ }
+
+ private static BuildAnalysisComputed BuildComputed(
+ BuildAnalysisAsset[] assets,
+ BuildAnalysisRootAsset[] rootAssets,
+ BuildAnalysisMessage[] messages,
+ float cacheReusePercent)
+ {
+ var counts = new BuildAnalysisCounts
+ {
+ AssetCount = assets.Length,
+ RootAssetCount = rootAssets.Length,
+ };
+
+ foreach (var asset in assets)
+ {
+ if (!string.IsNullOrEmpty(asset.Path)
+ && asset.Path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase))
+ {
+ counts.SceneCount++;
+ }
+ }
+
+ foreach (var t in messages)
+ {
+ var severity = t.Severity;
+ if (string.Equals(severity, BuildMessageSeverity.Error, StringComparison.Ordinal))
+ counts.ErrorMessageCount++;
+ else if (string.Equals(severity, BuildMessageSeverity.Warning, StringComparison.Ordinal))
+ counts.WarningMessageCount++;
+ else
+ counts.InfoMessageCount++;
+ }
+
+ return new BuildAnalysisComputed
+ {
+ Counts = counts,
+ CacheReusePercent = cacheReusePercent,
+ };
+ }
+ }
+}
diff --git a/Modules/BuildAnalysis/Services/BuildAnalysisService.cs b/Modules/BuildAnalysis/Services/BuildAnalysisService.cs
index fbaf7ea3ff..fe91d73e27 100644
--- a/Modules/BuildAnalysis/Services/BuildAnalysisService.cs
+++ b/Modules/BuildAnalysis/Services/BuildAnalysisService.cs
@@ -3,7 +3,11 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
+using System.Collections.Generic;
using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Unity.Profiling;
using UnityEngine;
namespace UnityEditor.Build.Analysis
@@ -11,37 +15,76 @@ namespace UnityEditor.Build.Analysis
///
/// Main service for build analysis functionality
///
- internal class BuildAnalysisService
+ internal class BuildAnalysisService : IDisposable
{
+ static readonly ProfilerMarker s_LoadFromDiskMarker = new ProfilerMarker("BuildAnalysisService.LoadFromDisk");
+
private readonly IBuildEnumerator m_Enumerator;
private readonly IBuildAnalyzer m_Analyzer;
private readonly IBuildAnalysisFileSystem m_FileSystem;
- private readonly IBuildAnalysisProgressReporter m_ProgressReporter;
private readonly IBuildHistoryProvider m_BuildHistory;
private readonly LRUCache m_Cache;
+ // In-flight de-duplication: a second request for a build that is already loading/generating awaits
+ // the same Task instead of recomputing.
+ private readonly Dictionary> m_InFlight = new Dictionary>();
+ private readonly object m_InFlightLock = new object();
+
+ // Cancels all in-flight work on teardown (window close / domain reload). The window builds a fresh
+ // service per OnEnable, so each session gets a fresh token (no reuse-after-cancel).
+ private readonly CancellationTokenSource m_Cts = new CancellationTokenSource();
+ private bool m_Disposed;
+
public BuildAnalysisService(
IBuildEnumerator enumerator,
IBuildAnalyzer analyzer,
IBuildAnalysisFileSystem fileSystem,
- IBuildAnalysisProgressReporter progressReporter,
IBuildHistoryProvider buildHistory)
{
m_Enumerator = enumerator ?? throw new ArgumentNullException(nameof(enumerator));
m_Analyzer = analyzer ?? throw new ArgumentNullException(nameof(analyzer));
m_FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
- m_ProgressReporter = progressReporter ?? throw new ArgumentNullException(nameof(progressReporter));
m_BuildHistory = buildHistory ?? throw new ArgumentNullException(nameof(buildHistory));
m_Cache = new LRUCache(20);
}
+ ///
+ /// Cancel any in-flight analysis without disposing (e.g. before a domain reload, where OnEnable
+ /// rebuilds the service afterwards).
+ ///
+ public void CancelPending()
+ {
+ if (m_Disposed)
+ return;
+ m_Cts.Cancel();
+ }
+
+ ///
+ /// Cancels in-flight analysis and releases the cancellation source. Call on window teardown.
+ ///
+ public void Dispose()
+ {
+ if (m_Disposed)
+ return;
+ m_Disposed = true;
+ m_Cts.Cancel();
+ m_Cts.Dispose();
+ }
+
///
/// Refresh the build history state from disk, then clear the cache.
/// Call this before GetBuilds when an explicit user-initiated refresh is needed.
///
public void Refresh()
{
- m_BuildHistory.Refresh();
+ try
+ {
+ m_BuildHistory.Refresh();
+ }
+ catch (Exception e)
+ {
+ Debug.LogError($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to refresh build history: {e.Message}");
+ }
ClearCache();
}
@@ -102,57 +145,38 @@ public void DeleteAllBuilds()
}
///
- /// Get analysis for a specific build
+ /// Get analysis for a specific build, off the main thread. Returns the cached instance synchronously
+ /// when available, joins an in-flight load/generation when one exists, otherwise starts one.
///
- public BuildAnalysis GetBuildAnalysis(GUID buildSessionGUID)
+ public Task GetBuildAnalysisAsync(GUID buildSessionGUID)
{
if (buildSessionGUID.Empty())
throw new ArgumentException("BuildSessionGUID is empty.", nameof(buildSessionGUID));
- var cachedAnalysis = m_Cache.Get(buildSessionGUID);
- if (cachedAnalysis != null)
- return cachedAnalysis;
+ var cached = m_Cache.Get(buildSessionGUID);
+ if (cached != null)
+ return Task.FromResult(cached);
- if (!m_Enumerator.TryGetBuild(buildSessionGUID, out var entry))
+ lock (m_InFlightLock)
{
- Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} No build found for BuildSessionGUID '{buildSessionGUID}'.");
- return null;
+ if (m_InFlight.TryGetValue(buildSessionGUID, out var inflight))
+ return inflight;
}
- try
- {
- BuildAnalysis analysis;
- if (TryGetBuildAnalysisPath(buildSessionGUID, out var analysisPath))
- {
- analysis = LoadBuildAnalysisFromDisk(analysisPath);
- }
- else
- {
- m_ProgressReporter.Show("Build Analysis", $"Generating analysis for '{entry.BuildName}'...", 0.5f);
- try
- {
- analysis = m_Analyzer.Generate(entry);
- }
- finally
- {
- m_ProgressReporter.Clear();
- }
- }
-
- m_Cache.Put(buildSessionGUID, analysis);
- return analysis;
- }
- catch (Exception e)
+ if (!m_Enumerator.TryGetBuild(buildSessionGUID, out var entry))
{
- Debug.LogError($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to get analysis for '{buildSessionGUID}': {e.Message}");
- return null;
+ Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} No build found for BuildSessionGUID '{buildSessionGUID}'.");
+ return Task.FromResult(null);
}
+
+ return Register(buildSessionGUID, () => LoadOrGenerateAsync(buildSessionGUID, entry, regenerate: false));
}
///
- /// Force regeneration of BuildAnalysis.json for the given build and update cache.
+ /// Force regeneration of BuildAnalysis.json for the given build and update the cache. Bypasses both the
+ /// memory cache and the on-disk file, and supersedes any in-flight load for the same build.
///
- public BuildAnalysis RegenerateBuildAnalysis(GUID buildSessionGUID)
+ public Task RegenerateBuildAnalysisAsync(GUID buildSessionGUID)
{
if (buildSessionGUID.Empty())
throw new ArgumentException("BuildSessionGUID is empty.", nameof(buildSessionGUID));
@@ -160,17 +184,9 @@ public BuildAnalysis RegenerateBuildAnalysis(GUID buildSessionGUID)
if (!m_Enumerator.TryGetBuild(buildSessionGUID, out var entry))
throw new ArgumentException($"No build found for BuildSessionGUID '{buildSessionGUID}'.", nameof(buildSessionGUID));
- m_ProgressReporter.Show("Build Analysis", $"Regenerating analysis for '{entry.BuildName}'...", 0.5f);
- try
- {
- var analysis = m_Analyzer.Generate(entry);
- m_Cache.Put(buildSessionGUID, analysis);
- return analysis;
- }
- finally
- {
- m_ProgressReporter.Clear();
- }
+ // Invalidate first so a concurrent GetBuildAnalysisAsync can't serve the stale entry we're replacing.
+ m_Cache.Remove(buildSessionGUID);
+ return Register(buildSessionGUID, () => LoadOrGenerateAsync(buildSessionGUID, entry, regenerate: true));
}
///
@@ -189,6 +205,71 @@ public bool HasBuildAnalysis(GUID buildSessionGUID)
return TryGetBuildAnalysisPath(buildSessionGUID, out _);
}
+ // Registers a freshly-started task as the in-flight entry for a build, and removes it on completion
+ private Task Register(GUID guid, Func> factory)
+ {
+ Task task = null;
+
+ async Task Tracked()
+ {
+ try
+ {
+ return await factory();
+ }
+ finally
+ {
+ lock (m_InFlightLock)
+ {
+ if (m_InFlight.TryGetValue(guid, out var current) && ReferenceEquals(current, task))
+ m_InFlight.Remove(guid);
+ }
+ }
+ }
+
+ task = Tracked();
+ if (!task.IsCompleted)
+ {
+ lock (m_InFlightLock)
+ m_InFlight[guid] = task;
+ }
+ return task;
+ }
+
+ private async Task LoadOrGenerateAsync(GUID guid, BuildEntry entry, bool regenerate)
+ {
+ try
+ {
+ BuildAnalysis analysis = null;
+ if (!regenerate && TryGetBuildAnalysisPath(guid, out var analysisPath))
+ {
+ var cached = await Task.Run(() => LoadBuildAnalysisFromDisk(analysisPath), m_Cts.Token);
+
+ // Only serve a cache written by the current schema. If not regenerate from the source
+ // BuildReport instead of serving stale data. Keeping this a simple version
+ // compare makes every future schema bump self-healing.
+ // If the source report has since been pruned, GenerateAsync throws and the catch below returns
+ // null; that rare stale-cache-without-report case degrades to empty, which is acceptable.
+ if (cached.Version == BuildAnalysisConstants.k_SchemaVersion)
+ analysis = cached;
+ }
+
+ if (analysis == null)
+ analysis = await m_Analyzer.GenerateAsync(entry, m_Cts.Token);
+
+ m_Cache.Put(guid, analysis);
+ return analysis;
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception e)
+ {
+ Debug.LogError($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to get analysis for '{guid}': {e.Message}");
+ return null;
+ }
+ }
+
private bool TryGetBuildAnalysisPath(GUID buildSessionGUID, out string path)
{
return m_BuildHistory.TryGetFilePath(buildSessionGUID, BuildAnalysisConstants.k_BuildAnalysisRelativePath, out path);
@@ -196,13 +277,16 @@ private bool TryGetBuildAnalysisPath(GUID buildSessionGUID, out string path)
private BuildAnalysis LoadBuildAnalysisFromDisk(string analysisPath)
{
- var json = m_FileSystem.ReadAllText(analysisPath);
- if (string.IsNullOrWhiteSpace(json))
- throw new InvalidDataException($"Build analysis file is empty: '{analysisPath}'.");
+ using (s_LoadFromDiskMarker.Auto())
+ {
+ var json = m_FileSystem.ReadAllText(analysisPath);
+ if (string.IsNullOrWhiteSpace(json))
+ throw new InvalidDataException($"Build analysis file is empty: '{analysisPath}'.");
- var analysis = JsonUtility.FromJson(json);
- ValidateBuildAnalysis(analysis, analysisPath);
- return analysis;
+ var analysis = JsonUtility.FromJson(json);
+ ValidateBuildAnalysis(analysis, analysisPath);
+ return analysis;
+ }
}
private static void ValidateBuildAnalysis(BuildAnalysis analysis, string path)
@@ -215,23 +299,4 @@ private static void ValidateBuildAnalysis(BuildAnalysis analysis, string path)
throw new InvalidDataException($"Build analysis has invalid Version '{analysis.Version}' in '{path}'.");
}
}
-
- internal interface IBuildAnalysisProgressReporter
- {
- void Show(string title, string info, float progress);
- void Clear();
- }
-
- internal sealed class BuildAnalysisProgressReporter : IBuildAnalysisProgressReporter
- {
- public void Show(string title, string info, float progress)
- {
- EditorUtility.DisplayProgressBar(title, info, progress);
- }
-
- public void Clear()
- {
- EditorUtility.ClearProgressBar();
- }
- }
}
diff --git a/Modules/BuildAnalysis/Services/BuildAnalyzer.cs b/Modules/BuildAnalysis/Services/BuildAnalyzer.cs
index 4bbe040883..4c4da3a6a6 100644
--- a/Modules/BuildAnalysis/Services/BuildAnalyzer.cs
+++ b/Modules/BuildAnalysis/Services/BuildAnalyzer.cs
@@ -3,9 +3,10 @@
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
-using System.Collections.Generic;
-using System.Globalization;
using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+using Unity.Profiling;
using UnityEditor.Build.Reporting;
using UnityEngine;
@@ -13,282 +14,174 @@ namespace UnityEditor.Build.Analysis
{
internal interface IBuildAnalyzer
{
- BuildAnalysis Generate(BuildEntry entry);
+ Task GenerateAsync(BuildEntry entry, CancellationToken ct);
}
internal sealed class BuildAnalyzer : IBuildAnalyzer
{
- private const int k_SchemaVersion = 1;
+ static readonly ProfilerMarker s_GenerateMarker = new ProfilerMarker("BuildAnalyzer.Generate");
+ static readonly ProfilerMarker s_LoadBuildReportMarker = new ProfilerMarker("BuildAnalyzer.LoadBuildReport");
+ static readonly ProfilerMarker s_ParseContentLayoutMarker = new ProfilerMarker("BuildAnalyzer.ParseContentLayout");
+ static readonly ProfilerMarker s_AssembleMarker = new ProfilerMarker("BuildAnalyzer.Assemble");
+ static readonly ProfilerMarker s_SerializeMarker = new ProfilerMarker("BuildAnalyzer.Serialize");
+ static readonly ProfilerMarker s_WriteMarker = new ProfilerMarker("BuildAnalyzer.Write");
private readonly IBuildReportConverter m_BuildReportConverter;
private readonly IBuildAnalysisFileSystem m_FileSystem;
private readonly IBuildHistoryProvider m_BuildHistory;
+ private readonly ISourceBuildAssetResolver m_AssetResolver;
public BuildAnalyzer(
IBuildReportConverter buildReportConverter,
IBuildAnalysisFileSystem fileSystem,
- IBuildHistoryProvider buildHistory)
+ IBuildHistoryProvider buildHistory,
+ ISourceBuildAssetResolver assetResolver)
{
m_BuildReportConverter = buildReportConverter ?? throw new ArgumentNullException(nameof(buildReportConverter));
m_FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
m_BuildHistory = buildHistory ?? throw new ArgumentNullException(nameof(buildHistory));
+ m_AssetResolver = assetResolver ?? throw new ArgumentNullException(nameof(assetResolver));
}
- public BuildAnalysis Generate(BuildEntry entry)
+ private readonly struct GatheredInputs
{
- ValidateEntry(entry);
-
- var reportSummary = m_BuildHistory.GetBuildSummary(entry.BuildSessionGUID);
-
- if (!m_BuildHistory.TryLoadBuildReport(entry.BuildSessionGUID, out var buildReport))
- throw new InvalidDataException($"Missing build report for build '{entry.BuildSessionGUID}'.");
- var reportData = m_BuildReportConverter.Convert(buildReport);
-
- if (!m_BuildHistory.TryGetBuildReportDirectory(entry.BuildSessionGUID, out var metadataPath))
- throw new InvalidDataException($"No build report directory available for build '{entry.BuildSessionGUID}'.");
-
- var rootStats = reportSummary.BuildType == BuildType.ContentDirectory
- ? LoadRootAssetStats(metadataPath)
- : Array.Empty();
-
- var analysis = BuildAnalysisFrom(reportSummary, reportData, rootStats);
+ public readonly BuildReportSummary ReportSummary;
+ public readonly BuildReportData ReportData;
+ public readonly string MetadataPath;
+ public readonly SourceBuildAssets? SourceBuildAssets;
- var analysisPath = Path.Combine(metadataPath, BuildAnalysisConstants.k_BuildAnalysisRelativePath);
- var json = JsonUtility.ToJson(analysis, true);
- m_FileSystem.WriteAllText(analysisPath, json);
-
- return analysis;
- }
-
- private RootAssetStats[] LoadRootAssetStats(string metadataPath)
- {
- var contentLayoutPath = Path.Combine(metadataPath, BuildAnalysisConstants.k_ContentLayoutFileName);
- if (!m_FileSystem.Exists(contentLayoutPath))
+ public GatheredInputs(BuildReportSummary reportSummary, BuildReportData reportData, string metadataPath, SourceBuildAssets? sourceBuildAssets)
{
- Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} ContentLayout.json not found at '{contentLayoutPath}'. RootAssets will be empty.");
- return Array.Empty();
+ ReportSummary = reportSummary;
+ ReportData = reportData;
+ MetadataPath = metadataPath;
+ SourceBuildAssets = sourceBuildAssets;
}
+ }
- try
- {
- // FromJson is preferred over ContentLayout.Load so all I/O stays behind
- // IBuildAnalysisFileSystem (testable). FromJson still emits the version-mismatch warning.
- var layout = ContentLayout.FromJson(m_FileSystem.ReadAllText(contentLayoutPath));
- if (layout == null)
- return Array.Empty();
- return RootAssetStatsCalculator.Calculate(layout);
- }
- catch (Exception e)
+ ///
+ /// Synchronous composition of the same three stages as . Not on
+ /// and not called in production (the UI uses );
+ /// it exists as the deterministic test seam for the full pipeline.
+ ///
+ public BuildAnalysis Generate(BuildEntry entry)
+ {
+ using (s_GenerateMarker.Auto())
{
- Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to read or parse ContentLayout.json at '{contentLayoutPath}': {e.Message}");
- return Array.Empty();
+ var inputs = GatherMainThreadInputs(entry);
+ var analysis = AssembleAnalysis(inputs);
+ PersistAnalysis(analysis, inputs.MetadataPath);
+ return analysis;
}
}
- private static BuildAnalysis BuildAnalysisFrom(BuildReportSummary reportSummary, BuildReportData reportData, RootAssetStats[] rootStats)
+ ///
+ /// Async generation: native build-report access stays on the main thread (pre-await); the heavy
+ /// pure-managed work (ContentLayout parse + root-asset BFS + assembly) runs on a background thread;
+ /// the disk cache is written fire-and-forget so the UI never waits on serialization.
+ ///
+ public async Task GenerateAsync(BuildEntry entry, CancellationToken ct)
{
- var stepTable = ConvertSteps(reportData.Steps);
- var analysisMessages = ConvertMessages(reportData.Messages, stepTable.Length);
- ConvertAssets(reportData.Assets, out var assetTable, out var importerTypeTable);
- var rootAssetTable = ConvertRootAssets(rootStats, assetTable);
- var computed = BuildComputed(
- assetTable,
- rootAssetTable,
- analysisMessages,
- reportData.CachedReusePercent);
+ // Already torn down before we started: skip the native gather entirely.
+ ct.ThrowIfCancellationRequested();
- var output = new BuildAnalysis
- {
- Version = k_SchemaVersion,
- GeneratedAtUtc = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
- Summary = new BuildAnalysisSummary
- {
- BuildSessionGUID = reportSummary.BuildSessionGUID.ToString(),
- BuildName = reportSummary.BuildName ?? string.Empty,
- BuildProfilePath = reportSummary.BuildProfilePath ?? string.Empty,
- Platform = reportSummary.Platform.ToString(),
- BuildResult = reportSummary.BuildResult.ToString(),
- BuildStartedAtUtc = reportSummary.BuildStartedAt ?? string.Empty,
- BuildType = reportSummary.BuildType.ToString(),
- TotalSizeBytes = reportSummary.TotalSizeBytes,
- TotalTimeMs = reportSummary.TotalTimeMs > 0 ? reportSummary.TotalTimeMs : reportData.TotalDurationMs,
- TotalErrors = reportData.TotalErrors,
- TotalWarnings = reportData.TotalWarnings,
- BuildManifestHash = reportSummary.BuildManifestHash ?? string.Empty,
- OutputPath = reportSummary.OutputPath ?? string.Empty,
- BuildOptions = reportSummary.BuildOptions ?? Array.Empty(),
- BuildContentOptions = reportSummary.BuildContentOptions ?? Array.Empty(),
- },
- Tables = new BuildAnalysisTables
- {
- Steps = stepTable,
- Assets = assetTable,
- ImporterTypes = importerTypeTable,
- RootAssets = rootAssetTable,
- },
- Messages = analysisMessages,
- Computed = computed,
- };
+ // Main thread (pre-await): native BuildReport load + convert + AssetDatabase importer lookup.
+ var inputs = GatherMainThreadInputs(entry);
- return output;
- }
+ // Off the main thread: all pure managed transform.
+ var analysis = await Task.Run(() => AssembleAnalysis(inputs), ct);
- private static BuildAnalysisStep[] ConvertSteps(BuildReportStepData[] steps)
- {
- var result = new BuildAnalysisStep[steps.Length];
- for (var i = 0; i < steps.Length; i++)
+ // Background, fire-and-forget: persisting the cache is not on the time-to-interactive path and is
+ // intentionally not tied to ct. A build the user navigated away from is still worth caching.
+ var metadataPath = inputs.MetadataPath;
+ var guid = entry.BuildSessionGUID;
+ _ = Task.Run(() =>
{
- var source = steps[i];
- result[i] = new BuildAnalysisStep
+ try
{
- Id = i,
- Name = source.Name ?? string.Empty,
- Depth = source.Depth,
- DurationMs = source.DurationMs,
- };
- }
+ PersistAnalysis(analysis, metadataPath);
+ }
+ catch (Exception e)
+ {
+ Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to persist analysis for '{guid}': {e.Message}");
+ }
+ });
- return result;
+ return analysis;
}
- private static BuildAnalysisMessage[] ConvertMessages(BuildReportMessageData[] messages, int maxStepCount)
+ private GatheredInputs GatherMainThreadInputs(BuildEntry entry)
{
- var result = new BuildAnalysisMessage[messages.Length];
-
- for (var i = 0; i < messages.Length; i++)
- {
- var source = messages[i];
- var stepIndex = source.StepIndex;
- if (stepIndex < 0 || stepIndex >= maxStepCount)
- stepIndex = -1;
-
- result[i] = new BuildAnalysisMessage
- {
- Severity = source.Severity ?? string.Empty,
- StepId = stepIndex,
- Text = source.Content ?? string.Empty,
- };
- }
+ ValidateEntry(entry);
- return result;
- }
+ var reportSummary = m_BuildHistory.GetBuildSummary(entry.BuildSessionGUID);
- private static void ConvertAssets(
- BuildReportAssetData[] sourceAssets,
- out BuildAnalysisAsset[] assets,
- out BuildAnalysisImporterType[] importerTypes)
- {
- if (sourceAssets.Length == 0)
+ BuildReport buildReport;
+ using (s_LoadBuildReportMarker.Auto())
{
- assets = Array.Empty();
- importerTypes = Array.Empty();
- return;
+ if (!m_BuildHistory.TryLoadBuildReport(entry.BuildSessionGUID, out buildReport))
+ throw new InvalidDataException($"Missing build report for build '{entry.BuildSessionGUID}'.");
}
+ var reportData = m_BuildReportConverter.Convert(buildReport);
- var importerIdByName = new Dictionary(StringComparer.Ordinal);
- var importerList = new List();
-
- assets = new BuildAnalysisAsset[sourceAssets.Length];
- for (var i = 0; i < sourceAssets.Length; i++)
- {
- var src = sourceAssets[i];
- var importerKey = string.IsNullOrEmpty(src.ImporterTypeName) ? "Unknown" : src.ImporterTypeName;
- if (!importerIdByName.TryGetValue(importerKey, out var importerId))
- {
- importerId = importerList.Count;
- importerList.Add(new BuildAnalysisImporterType { Id = importerId, Name = importerKey });
- importerIdByName[importerKey] = importerId;
- }
+ // A Player build that recorded no assets (scripts-only, or an incremental build that reused its data
+ // cache) borrows the asset table from the exact source build the pipeline recorded on this build's
+ // summary. The resolver limits itself to Player builds, so no build-type check is needed here.
+ SourceBuildAssets? sourceBuildAssets = null;
+ if (reportData.Assets.Length == 0 && m_AssetResolver.TryResolveSourceBuildAssets(reportSummary, out var resolved))
+ sourceBuildAssets = resolved;
- assets[i] = new BuildAnalysisAsset
- {
- Id = i,
- Path = src.Path ?? string.Empty,
- GUID = src.GUID,
- OutputSizeBytes = src.OutputSizeBytes,
- ObjectCount = src.ObjectCount,
- ResourceCount = src.ResourceCount,
- ImporterTypeId = importerId,
- };
- }
+ if (!m_BuildHistory.TryGetBuildReportDirectory(entry.BuildSessionGUID, out var metadataPath))
+ throw new InvalidDataException($"No build report directory available for build '{entry.BuildSessionGUID}'.");
- importerTypes = importerList.ToArray();
+ return new GatheredInputs(reportSummary, reportData, metadataPath, sourceBuildAssets);
}
- private static BuildAnalysisRootAsset[] ConvertRootAssets(
- RootAssetStats[] rootStats,
- BuildAnalysisAsset[] assets)
+ private BuildAnalysis AssembleAnalysis(GatheredInputs inputs)
{
- if (rootStats.Length == 0)
- return Array.Empty();
-
- var pathToAssetId = new Dictionary(assets.Length, StringComparer.Ordinal);
- foreach (var a in assets)
- {
- if (!string.IsNullOrEmpty(a.Path))
- pathToAssetId[a.Path] = a.Id;
- }
+ var rootStats = inputs.ReportSummary.BuildType == BuildType.ContentDirectory
+ ? LoadRootAssetStats(inputs.MetadataPath)
+ : Array.Empty();
- var result = new List(rootStats.Length);
- foreach (var s in rootStats)
- {
- if (string.IsNullOrEmpty(s.AssetPath) || !pathToAssetId.TryGetValue(s.AssetPath, out var assetId))
- {
- // Root assets are project source assets that should appear in BuildReport.assetStats.
- // Skip on the rare miss rather than emit a sentinel AssetId.
- Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Root asset '{s.AssetPath}' not found in Assets table.");
- continue;
- }
- result.Add(new BuildAnalysisRootAsset
- {
- Id = result.Count,
- AssetId = assetId,
- DirectAssetCount = s.DirectAssets,
- DirectSizeBytes = s.DirectSize,
- TotalAssetCount = s.TotalAssets,
- TotalSizeBytes = s.TotalSize,
- });
- }
- return result.ToArray();
+ using (s_AssembleMarker.Auto())
+ return BuildAnalysisAssembler.Assemble(inputs.ReportSummary, inputs.ReportData, rootStats, inputs.SourceBuildAssets);
}
- private static BuildAnalysisComputed BuildComputed(
- BuildAnalysisAsset[] assets,
- BuildAnalysisRootAsset[] rootAssets,
- BuildAnalysisMessage[] messages,
- float cacheReusePercent)
+ private void PersistAnalysis(BuildAnalysis analysis, string metadataPath)
{
- var counts = new BuildAnalysisCounts
- {
- AssetCount = assets.Length,
- RootAssetCount = rootAssets.Length,
- };
+ var analysisPath = Path.Combine(metadataPath, BuildAnalysisConstants.k_BuildAnalysisRelativePath);
+ string json;
+ using (s_SerializeMarker.Auto())
+ json = JsonUtility.ToJson(analysis, false);
+ using (s_WriteMarker.Auto())
+ m_FileSystem.WriteAllText(analysisPath, json);
+ }
- foreach (var asset in assets)
+ private RootAssetStats[] LoadRootAssetStats(string metadataPath)
+ {
+ var contentLayoutPath = Path.Combine(metadataPath, BuildAnalysisConstants.k_ContentLayoutFileName);
+ if (!m_FileSystem.Exists(contentLayoutPath))
{
- if (!string.IsNullOrEmpty(asset.Path)
- && asset.Path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase))
- {
- counts.SceneCount++;
- }
+ Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} ContentLayout.json not found at '{contentLayoutPath}'. RootAssets will be empty.");
+ return Array.Empty();
}
- foreach (var t in messages)
+ try
{
- var severity = t.Severity;
- if (string.Equals(severity, BuildMessageSeverity.Error, StringComparison.Ordinal))
- counts.ErrorMessageCount++;
- else if (string.Equals(severity, BuildMessageSeverity.Warning, StringComparison.Ordinal))
- counts.WarningMessageCount++;
- else
- counts.InfoMessageCount++;
+ // FromJson is preferred over ContentLayout.Load so all I/O stays behind
+ // IBuildAnalysisFileSystem (testable). FromJson still emits the version-mismatch warning.
+ ContentLayout layout;
+ using (s_ParseContentLayoutMarker.Auto())
+ layout = ContentLayout.FromJson(m_FileSystem.ReadAllText(contentLayoutPath));
+ if (layout == null)
+ return Array.Empty();
+ return RootAssetStatsCalculator.Calculate(layout);
}
-
- return new BuildAnalysisComputed
+ catch (Exception e)
{
- Counts = counts,
- CacheReusePercent = cacheReusePercent,
- };
+ Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to read or parse ContentLayout.json at '{contentLayoutPath}': {e.Message}");
+ return Array.Empty();
+ }
}
private static void ValidateEntry(BuildEntry entry)
diff --git a/Modules/BuildAnalysis/Services/BuildEnumerator.cs b/Modules/BuildAnalysis/Services/BuildEnumerator.cs
index 4be34afb30..b6fb54a665 100644
--- a/Modules/BuildAnalysis/Services/BuildEnumerator.cs
+++ b/Modules/BuildAnalysis/Services/BuildEnumerator.cs
@@ -4,7 +4,6 @@
using System;
using System.Collections.Generic;
-using System.Globalization;
using System.IO;
using UnityEngine;
@@ -95,8 +94,8 @@ private BuildEntry BuildEntryFromSummary(BuildReportSummary summary, GUID guid)
private static DateTime ParseBuildStartedAtLocal(string buildStartedAt)
{
- if (DateTimeOffset.TryParseExact(buildStartedAt, "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsedDateTime))
- return parsedDateTime.ToLocalTime().DateTime;
+ if (FormatUtility.TryParseBuildTimestamp(buildStartedAt, out var parsed))
+ return parsed.ToLocalTime().DateTime;
throw new FormatException($"Invalid BuildStartedAt value: '{buildStartedAt}'.");
}
diff --git a/Modules/BuildAnalysis/Services/BuildReportConverter.cs b/Modules/BuildAnalysis/Services/BuildReportConverter.cs
index 18e14cacce..ecab3d79a6 100644
--- a/Modules/BuildAnalysis/Services/BuildReportConverter.cs
+++ b/Modules/BuildAnalysis/Services/BuildReportConverter.cs
@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
+using Unity.Profiling;
using UnityEditor.Build.Reporting;
using UnityEngine;
@@ -16,6 +17,9 @@ internal interface IBuildReportConverter
internal sealed class BuildReportConverter : IBuildReportConverter
{
+ static readonly ProfilerMarker s_ExtractAssetsMarker = new ProfilerMarker("BuildReportConverter.ExtractAssets");
+ static readonly ProfilerMarker s_GetImporterTypesMarker = new ProfilerMarker("BuildReportConverter.GetImporterTypes");
+
public BuildReportData Convert(BuildReport buildReport)
{
if (buildReport == null)
@@ -91,40 +95,45 @@ private static float ComputeCachedReusePercent(BuildReport buildReport)
private static BuildReportAssetData[] ExtractAssets(BuildReport buildReport)
{
- if (buildReport == null)
- return Array.Empty();
+ using (s_ExtractAssetsMarker.Auto())
+ {
+ if (buildReport == null)
+ return Array.Empty();
- var contentSummary = buildReport.contentSummary;
- if (contentSummary == null)
- return Array.Empty();
+ var contentSummary = buildReport.contentSummary;
+ if (contentSummary == null)
+ return Array.Empty();
- var assetStats = contentSummary.assetStats;
- if (assetStats.Length == 0)
- return Array.Empty();
+ var assetStats = contentSummary.assetStats;
+ if (assetStats.Length == 0)
+ return Array.Empty();
- var guids = new GUID[assetStats.Length];
- for (var i = 0; i < assetStats.Length; i++)
- guids[i] = assetStats[i].sourceAssetGUID;
+ var guids = new GUID[assetStats.Length];
+ for (var i = 0; i < assetStats.Length; i++)
+ guids[i] = assetStats[i].sourceAssetGUID;
- var importerTypes = AssetDatabase.GetImporterTypes(guids);
- Debug.Assert(importerTypes.Length == assetStats.Length);
+ Type[] importerTypes;
+ using (s_GetImporterTypesMarker.Auto())
+ importerTypes = AssetDatabase.GetImporterTypes(guids);
+ Debug.Assert(importerTypes.Length == assetStats.Length);
- var assets = new BuildReportAssetData[assetStats.Length];
- for (var i = 0; i < assetStats.Length; i++)
- {
- var stats = assetStats[i];
- assets[i] = new BuildReportAssetData
+ var assets = new BuildReportAssetData[assetStats.Length];
+ for (var i = 0; i < assetStats.Length; i++)
{
- Path = stats.sourceAssetPath ?? string.Empty,
- GUID = stats.sourceAssetGUID,
- OutputSizeBytes = stats.size,
- ObjectCount = stats.objectCount,
- ResourceCount = stats.resourceCount,
- ImporterTypeName = importerTypes[i]?.Name,
- };
- }
+ var stats = assetStats[i];
+ assets[i] = new BuildReportAssetData
+ {
+ Path = stats.sourceAssetPath ?? string.Empty,
+ GUID = stats.sourceAssetGUID,
+ OutputSizeBytes = stats.size,
+ ObjectCount = stats.objectCount,
+ ResourceCount = stats.resourceCount,
+ ImporterTypeName = importerTypes[i]?.Name,
+ };
+ }
- return assets;
+ return assets;
+ }
}
private static string ToSeverityString(LogType messageType)
diff --git a/Modules/BuildAnalysis/Services/RootAssetStatsCalculator.cs b/Modules/BuildAnalysis/Services/RootAssetStatsCalculator.cs
index fdb43bc2b4..4dd871f404 100644
--- a/Modules/BuildAnalysis/Services/RootAssetStatsCalculator.cs
+++ b/Modules/BuildAnalysis/Services/RootAssetStatsCalculator.cs
@@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
+using Unity.Profiling;
using UnityEngine;
namespace UnityEditor.Build.Analysis
@@ -15,13 +16,16 @@ namespace UnityEditor.Build.Analysis
///
internal static class RootAssetStatsCalculator
{
+ static readonly ProfilerMarker s_CalculateMarker = new ProfilerMarker("RootAssetStatsCalculator.Calculate");
+
public static RootAssetStats[] Calculate(ContentLayout layout)
{
if (layout == null)
throw new ArgumentNullException(nameof(layout));
try
{
- return new Context(layout).Calculate();
+ using (s_CalculateMarker.Auto())
+ return new Context(layout).Calculate();
}
catch (Exception e)
{
@@ -102,6 +106,14 @@ public RootAssetStats[] Calculate()
var direct = Traverse(rootSfIndex, includeLoadables: false);
var total = Traverse(rootSfIndex, includeLoadables: true);
+ // References mirror the Total reachable set: after the includeLoadables pass,
+ // m_UniqueSources holds the root's full reachable closure. Drop the root's own
+ // path and copy the rest now, before the next root's Traverse clears the set.
+ if (assetPath != null)
+ m_UniqueSources.Remove(assetPath);
+ var references = new string[m_UniqueSources.Count];
+ m_UniqueSources.CopyTo(references);
+
results.Add(new RootAssetStats
{
AssetPath = assetPath ?? string.Empty,
@@ -109,6 +121,7 @@ public RootAssetStats[] Calculate()
DirectSize = direct.SizeBytes,
TotalAssets = total.AssetCount,
TotalSize = total.SizeBytes,
+ ReferencedAssetPaths = references,
});
}
return results.ToArray();
diff --git a/Modules/BuildAnalysis/Services/SourceBuildAssetResolver.cs b/Modules/BuildAnalysis/Services/SourceBuildAssetResolver.cs
new file mode 100644
index 0000000000..5aa9ac2aa6
--- /dev/null
+++ b/Modules/BuildAnalysis/Services/SourceBuildAssetResolver.cs
@@ -0,0 +1,102 @@
+// Unity C# reference source
+// Copyright (c) Unity Technologies. For terms of use, see
+// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
+
+using System;
+using UnityEditor.Build.Reporting;
+using UnityEngine;
+
+namespace UnityEditor.Build.Analysis
+{
+ ///
+ /// The assets of a previous complete Player build, used to stand in for an asset-less Player build
+ /// (a scripts-only build, or an incremental build that reused its data cache and recorded no assets).
+ ///
+ internal readonly struct SourceBuildAssets
+ {
+ /// The source build the assets came from.
+ public readonly GUID BuildGuid;
+
+ /// Summary of the source build (build name, start time, …).
+ public readonly BuildReportSummary BuildSummary;
+
+ /// The source build's asset rows; may be empty if the source recorded none.
+ public readonly BuildReportAssetData[] Assets;
+
+ public SourceBuildAssets(GUID buildGuid, BuildReportSummary buildSummary, BuildReportAssetData[] assets)
+ {
+ BuildGuid = buildGuid;
+ BuildSummary = buildSummary;
+ Assets = assets;
+ }
+ }
+
+ internal interface ISourceBuildAssetResolver
+ {
+ ///
+ /// Follows the source-build pointer the build pipeline stamped for an asset-less
+ /// and loads that exact source build's assets. No history scan — a result exists only when a valid pointer does.
+ ///
+ ///
+ /// Main-thread only: this loads build reports and runs the importer lookup inside
+ /// , both of which require the main thread.
+ ///
+ ///
+ /// True with set (its asset rows may be empty) when the target has a
+ /// recorded source build whose report still loads; false otherwise.
+ ///
+ bool TryResolveSourceBuildAssets(BuildReportSummary target, out SourceBuildAssets sourceBuildAssets);
+ }
+
+ ///
+ /// Resolves the exact previous build whose data cache an asset-less Player build reused, by following the
+ /// pointer the build pipeline stamps into the build's metadata folder
+ ///
+ internal sealed class SourceBuildAssetResolver : ISourceBuildAssetResolver
+ {
+ readonly IBuildHistoryProvider m_BuildHistory;
+ readonly IBuildReportConverter m_BuildReportConverter;
+
+ public SourceBuildAssetResolver(IBuildHistoryProvider buildHistory, IBuildReportConverter buildReportConverter)
+ {
+ m_BuildHistory = buildHistory ?? throw new ArgumentNullException(nameof(buildHistory));
+ m_BuildReportConverter = buildReportConverter ?? throw new ArgumentNullException(nameof(buildReportConverter));
+ }
+
+ public bool TryResolveSourceBuildAssets(BuildReportSummary target, out SourceBuildAssets sourceBuildAssets)
+ {
+ sourceBuildAssets = default;
+
+ // Only Player builds source assets from another build. ContentDirectory builds pack their own content.
+ if (target.BuildType != BuildType.Player)
+ return false;
+
+ // The build pipeline records the exact source build whose content this one reused, on the summary.
+ // An empty value means the build produced its own (empty) content. The target's own BuildResult is
+ // intentionally not gated: an asset-less Player build shows whatever content it actually reused, the
+ // same way a build's own assets are shown regardless of result (the header still flags the failure).
+ var sourceGuid = target.ContentSourceBuildSessionGUID;
+ if (sourceGuid.Empty() || sourceGuid == target.BuildSessionGUID)
+ return false;
+
+ BuildReportSummary sourceSummary;
+ try
+ {
+ sourceSummary = m_BuildHistory.GetBuildSummary(sourceGuid);
+ }
+ catch (ArgumentException)
+ {
+ // Source build was pruned from history since the pointer was written.
+ return false;
+ }
+
+ // Borrow the source recorded, even an empty table - its assets are exactly the content the target reused.
+ if (!m_BuildHistory.TryLoadBuildReport(sourceGuid, out var report))
+ return false;
+
+ var data = m_BuildReportConverter.Convert(report);
+ sourceBuildAssets = new SourceBuildAssets(sourceGuid, sourceSummary, data.Assets);
+ return true;
+ }
+ }
+}
diff --git a/Modules/BuildAnalysis/UI/BuildAnalysisTabHost.cs b/Modules/BuildAnalysis/UI/BuildAnalysisTabHost.cs
index d97ed453e5..5900a9b4f9 100644
--- a/Modules/BuildAnalysis/UI/BuildAnalysisTabHost.cs
+++ b/Modules/BuildAnalysis/UI/BuildAnalysisTabHost.cs
@@ -4,12 +4,16 @@
using System;
using System.Collections.Generic;
+using Unity.Profiling;
+using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Build.Analysis
{
internal class BuildAnalysisTabHost
{
+ static readonly ProfilerMarker s_SetSelectionMarker = new ProfilerMarker("BuildAnalysisTabHost.SetSelection");
+
private readonly TabView m_TabView;
private readonly List m_TabRegistrations = new List();
@@ -49,10 +53,30 @@ public void Register(Tab tab, IBuildAnalysisTabView tabView)
});
}
+ public void RegisterShortcuts(VisualElement root)
+ {
+ if (root == null)
+ return;
+
+ root.RegisterCallback(evt =>
+ {
+ if (evt.keyCode != KeyCode.Tab || !evt.ctrlKey)
+ return;
+
+ SelectNextTab(evt.shiftKey);
+
+ // Consume it so the tab character isn't typed into a focused field.
+ evt.StopPropagation();
+ }, TrickleDown.TrickleDown);
+ }
+
public void SetSelection(BuildEntry selection, BuildAnalysis analysis)
{
- foreach (var registration in m_TabRegistrations)
- registration.TabView.SetSelection(selection, analysis);
+ using (s_SetSelectionMarker.Auto())
+ {
+ foreach (var registration in m_TabRegistrations)
+ registration.TabView.SetSelection(selection, analysis);
+ }
}
public void NotifyCurrentTabVisibility()
@@ -74,5 +98,24 @@ private void OnActiveTabChanged(Tab previousTab, Tab newTab)
registration.TabView.OnTabVisibilityChanged(isVisible);
}
}
+
+ private void SelectNextTab(bool reverse)
+ {
+ if (m_TabView == null || m_TabRegistrations.Count == 0)
+ return;
+
+ var count = m_TabRegistrations.Count;
+ var current = m_TabRegistrations.FindIndex(r => ReferenceEquals(r.Tab, m_TabView.activeTab));
+ if (current < 0)
+ current = 0;
+
+ var next = current + (reverse ? -1 : 1);
+ if (next < 0)
+ next = count - 1;
+ else if (next >= count)
+ next = 0;
+
+ m_TabView.activeTab = m_TabRegistrations[next].Tab;
+ }
}
}
diff --git a/Modules/BuildAnalysis/UI/BuildAnalysisWindow.cs b/Modules/BuildAnalysis/UI/BuildAnalysisWindow.cs
index 6ddb06bb57..65cd0d0ace 100644
--- a/Modules/BuildAnalysis/UI/BuildAnalysisWindow.cs
+++ b/Modules/BuildAnalysis/UI/BuildAnalysisWindow.cs
@@ -4,6 +4,7 @@
using System;
using System.IO;
+using System.Threading.Tasks;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
@@ -19,12 +20,11 @@ internal interface IBuildListActions
void RegenerateAnalysis(BuildEntry build);
}
- [EditorWindowTitle(title = "Build Analysis", icon = "UnityEditor.ProfilerWindow")]
+ [EditorWindowTitle(title = "Build Analysis", icon = "BuildAnalysisWindow")]
internal class BuildAnalysisWindow : EditorWindow, IBuildListActions
{
private const string k_OpenWindowCommand = "ContentBuild/OpenBuildAnalysisWindow";
- private const string k_WindowTitle = "Build Analysis";
private const string k_UxmlPath = "BuildAnalysis/UXML/BuildAnalysisWindow.uxml";
private const string k_UssPath = "BuildAnalysis/StyleSheets/BuildAnalysisWindow.uss";
private const string k_UssClassDark = "build-analysis-window--dark";
@@ -35,30 +35,77 @@ internal class BuildAnalysisWindow : EditorWindow, IBuildListActions
private const string k_SplitterKey = k_KeyPrefix + "SplitterPosition";
private const string k_InspectorOpenKey = k_KeyPrefix + "InspectorPanelOpen";
+ private const string k_InspectorToggleTooltip = "Toggle Inspector";
+ private const string k_InspectorToggleDisabledTooltip = "The inspector is only available on the Assets tab";
+
+ private const string k_HelpButtonTooltip = "Open Build Analysis documentation";
+ // Manual topic slug (Documentation/ManualDocs/md/build-analysis-window-reference.md).
+ private const string k_DocumentationPage = "build-analysis-window-reference";
+
+ private const string k_LoadingMessage = "Analyzing build…";
+
private TwoPaneSplitView m_SplitView;
private ToolbarToggle m_InspectorToggle;
private TabView m_TabView;
private Tab m_OverviewTab;
private Tab m_AssetsTab;
+ private LoadingOverlay m_LoadingOverlay;
private BuildListPanel m_BuildListPanel;
private BuildAnalysisService m_Service;
private BuildAnalysisTabHost m_TabHost;
private BuildHistoryWatcher m_Watcher;
- private BuildAnalysis m_SelectedBuildAnalysis;
+
+ private SelectionGate m_Gate;
+
+ private GUID m_PendingSelection;
[MenuItem("Window/Analysis/Build Analysis")]
internal static void ShowWindow()
+ {
+ ShowWindow(default);
+ }
+
+ ///
+ /// Open the Build Analysis window and select the build with the given session GUID.
+ /// Pass an empty GUID to open the window without changing the current selection.
+ /// If no build matches the GUID, the window still opens and a warning is logged.
+ ///
+ internal static void ShowWindow(GUID buildSessionGUID)
{
if (CommandService.Exists(k_OpenWindowCommand))
{
- CommandService.Execute(k_OpenWindowCommand, CommandHint.Menu);
+ CommandService.Execute(k_OpenWindowCommand, CommandHint.Menu, buildSessionGUID);
return;
}
var window = GetWindow(false);
- window.titleContent = new GUIContent(k_WindowTitle);
window.minSize = new Vector2(750, 400);
+
+ // Request the build selection. The UI may not be built yet (CreateGUI can be deferred to a
+ // later editor tick), in which case this no-ops now and CreateGUI re-runs it once the
+ // build list exists. An empty GUID leaves the current selection untouched.
+ window.m_PendingSelection = buildSessionGUID;
+ window.ApplyPendingSelection();
+ }
+
+ private void ApplyPendingSelection()
+ {
+ // m_BuildListPanel is null until CreateGUI runs, keep the request pending until then.
+ if (m_PendingSelection.Empty() || m_BuildListPanel == null)
+ return;
+
+ var buildSessionGUID = m_PendingSelection;
+ m_PendingSelection = default;
+
+ // Force a refresh from BuildHistory.
+ // A caller can link to a build it just produced. BuildHistoryWatcher only polls
+ // ~1Hz, so m_BuildListPanel's list can be stale and would not yet contain that build session guid.
+ m_Service.Refresh();
+ RefreshBuildList();
+
+ if (!m_BuildListPanel.SelectBuild(buildSessionGUID))
+ Debug.LogWarning($"{BuildAnalysisConstants.k_ConsoleLogPrefix} No build session GUID found for '{buildSessionGUID}'.");
}
private void OnEnable()
@@ -67,21 +114,34 @@ private void OnEnable()
var fileSystem = new BuildAnalysisFileSystem();
var enumerator = new BuildEnumerator(buildHistory);
- var analyzer = new BuildAnalyzer(new BuildReportConverter(), fileSystem, buildHistory);
- m_Service = new BuildAnalysisService(enumerator, analyzer, fileSystem, new BuildAnalysisProgressReporter(), buildHistory);
+ var converter = new BuildReportConverter();
+ var assetResolver = new SourceBuildAssetResolver(buildHistory, converter);
+ var analyzer = new BuildAnalyzer(converter, fileSystem, buildHistory, assetResolver);
+ m_Service = new BuildAnalysisService(enumerator, analyzer, fileSystem, buildHistory);
m_Watcher = new BuildHistoryWatcher(buildHistory);
m_Watcher.BuildHistoryChanged += RefreshBuildList;
m_Watcher.Enable();
+
+ AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
}
private void OnDisable()
{
+ AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
+ m_Service?.Dispose();
m_Watcher.Disable();
m_Watcher.BuildHistoryChanged -= RefreshBuildList;
SavePersistedState();
}
+ // Cancel in-flight analysis before the domain is torn down so continuations don't run against a
+ // half-dead window. OnEnable rebuilds a fresh service (and cancellation token) after the reload.
+ private void OnBeforeAssemblyReload()
+ {
+ m_Service?.CancelPending();
+ }
+
public void CreateGUI()
{
var visualTree = EditorGUIUtility.LoadRequired(k_UxmlPath) as VisualTreeAsset;
@@ -101,6 +161,8 @@ public void CreateGUI()
m_OverviewTab = rootVisualElement.Q("overview-tab");
m_AssetsTab = rootVisualElement.Q("assets-tab");
+ m_Gate = new SelectionGate(() => rootVisualElement?.panel != null);
+
var buildListHost = rootVisualElement.Q("build-list-host");
m_BuildListPanel = new BuildListPanel(this);
m_BuildListPanel.SelectionChanged += OnBuildSelectionChanged;
@@ -109,10 +171,16 @@ public void CreateGUI()
SetupInspectorToggle();
SetupTabs();
+ // Ctrl+Tab / Ctrl+Shift+Tab cycles the content tabs, from anywhere in the window.
+ m_TabHost.RegisterShortcuts(rootVisualElement);
+
var splitterPos = EditorPrefs.GetFloat(k_SplitterKey, 100);
m_SplitView.fixedPaneInitialDimension = splitterPos;
+ // BuildHistoryWatcher only runs while the window is open, so builds added while it was closed are not cached yet.
+ m_Service.Refresh();
RefreshBuildList();
+ ApplyPendingSelection();
}
private void SetupInspectorToggle()
@@ -121,15 +189,17 @@ private void SetupInspectorToggle()
if (tabViewport == null)
throw new InvalidOperationException($"{BuildAnalysisConstants.k_ConsoleLogPrefix} TabView content viewport .unity-tab-view__content-viewport not found.");
+ SetupHelpButton(tabViewport);
+
m_InspectorToggle = new ToolbarToggle
{
name = "inspector-toggle",
- tooltip = "Toggle Inspector",
+ tooltip = k_InspectorToggleTooltip,
};
m_InspectorToggle.AddToClassList("inspector-toggle");
tabViewport.Add(m_InspectorToggle);
- m_InspectorToggle.SetValueWithoutNotify(EditorPrefs.GetBool(k_InspectorOpenKey, false));
+ m_InspectorToggle.SetValueWithoutNotify(EditorPrefs.GetBool(k_InspectorOpenKey, true));
m_InspectorToggle.RegisterValueChangedCallback(evt =>
{
EditorPrefs.SetBool(k_InspectorOpenKey, evt.newValue);
@@ -137,20 +207,51 @@ private void SetupInspectorToggle()
});
}
+ private void SetupHelpButton(VisualElement tabViewport)
+ {
+ var helpButton = new ToolbarButton(() => Help.BrowseURL(GetDocumentationUrl()))
+ {
+ name = "help-button",
+ tooltip = k_HelpButtonTooltip,
+ };
+ helpButton.AddToClassList("help-button");
+ tabViewport.Add(helpButton);
+ }
+
+ private static string GetDocumentationUrl()
+ {
+ var version = UnityEditorInternal.InternalEditorUtility.GetUnityVersion();
+ return $"https://docs.unity3d.com/{version.Major}.{version.Minor}/Documentation/Manual/{k_DocumentationPage}.html";
+ }
+
private void SetupTabs()
{
m_TabHost = new BuildAnalysisTabHost(m_TabView);
m_TabHost.Register(m_OverviewTab, new OverviewTabView());
- var assetsTabView = new AssetsTabView();
- assetsTabView.InspectorOpenRequested += () => m_InspectorToggle.value = true;
- m_TabHost.Register(m_AssetsTab, assetsTabView);
+ m_TabHost.Register(m_AssetsTab, new AssetsTabView());
+
+ // Only the Assets tab has an inspector; disable the toggle on tabs that don't.
+ m_TabView.activeTabChanged += (_, activeTab) => UpdateInspectorToggleEnabled(activeTab);
+ UpdateInspectorToggleEnabled(m_TabView.activeTab);
+
+ m_LoadingOverlay = new LoadingOverlay();
+ m_TabView.contentContainer.Add(m_LoadingOverlay);
m_TabHost.NotifyCurrentTabVisibility();
m_TabHost.SetInspectorOpen(m_InspectorToggle.value);
m_TabHost.SetSelection(null, null);
}
+ private void UpdateInspectorToggleEnabled(Tab activeTab)
+ {
+ var supportsInspector = activeTab == m_AssetsTab;
+ m_InspectorToggle.SetEnabled(supportsInspector);
+ m_InspectorToggle.tooltip = supportsInspector
+ ? k_InspectorToggleTooltip
+ : k_InspectorToggleDisabledTooltip;
+ }
+
private static void ApplyThemeClass(VisualElement view)
{
view.RemoveFromClassList(k_UssClassDark);
@@ -163,21 +264,75 @@ private void RefreshBuildList()
m_BuildListPanel.SetBuilds(m_Service.GetBuilds(), BuildHistory.BuildHistoryLimit);
}
- private void OnBuildSelectionChanged(BuildEntry selection)
+ private async void OnBuildSelectionChanged(BuildEntry selection)
{
if (selection == null)
{
- m_SelectedBuildAnalysis = null;
+ // Invalidate any in-flight load (so its continuation is dropped as stale) and clear the view.
+ m_Gate.Clear();
m_TabHost.SetSelection(null, null);
+ m_LoadingOverlay.Hide();
+ return;
+ }
+
+ // Already loading or showing this build (e.g. a build-list refresh re-fired selection) — skip.
+ if (m_Gate.IsCurrentTarget(selection.BuildSessionGUID))
return;
+
+ await LoadAndApplyAsync(selection, () => m_Service.GetBuildAnalysisAsync(selection.BuildSessionGUID));
+ }
+
+ // Apply for both selection and regenerate: show the overlay, await the result, and
+ // update the tabs only if this is still the latest request and the window is still alive.
+ private async Task LoadAndApplyAsync(BuildEntry build, Func> load)
+ {
+ var seq = m_Gate.Begin(build.BuildSessionGUID);
+
+ // Show the loading overlay over the active tab's content before we await.
+ m_LoadingOverlay.Show(k_LoadingMessage);
+
+ BuildAnalysis analysis;
+ try
+ {
+ analysis = await load();
}
+ catch (OperationCanceledException)
+ {
+ // Service was torn down / reloaded mid-load (Dispose or CancelPending cancelled the token
+ // before the off-thread work started). Swallow so the async-void caller doesn't log it; the
+ // window is gone or being rebuilt, so there's nothing to update.
+ return;
+ }
+ catch (Exception e)
+ {
+ if (!m_Gate.IsStale(seq))
+ {
+ m_TabHost.SetSelection(null, null); // clear to no-selection
+ m_LoadingOverlay.Hide();
+ m_Gate.Clear(); // a failed load isn't shown — drop the target so re-selecting retries
+ Debug.LogError($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to analyze build: {e.Message}");
+ }
+ return;
+ }
+
+ if (m_Gate.IsStale(seq))
+ return;
- m_SelectedBuildAnalysis = m_Service.GetBuildAnalysis(selection.BuildSessionGUID);
- m_TabHost.SetSelection(selection, m_SelectedBuildAnalysis);
+ m_TabHost.SetSelection(build, analysis);
+ m_LoadingOverlay.Hide();
+
+ // A build that produced no analysis isn't shown — drop the target so re-selecting retries.
+ if (analysis == null)
+ m_Gate.Clear();
}
private void SavePersistedState()
{
+ // OnEnable/OnDisable can run without CreateGUI in between: on unmaximize Unity
+ // deserializes the maximize backup window (firing OnEnable) and immediately destroys
+ // it (firing OnDisable), but never shows it, so CreateGUI never assigns m_SplitView.
+ if (m_SplitView == null)
+ return;
EditorPrefs.SetFloat(k_SplitterKey, m_SplitView.fixedPaneInitialDimension);
}
@@ -189,8 +344,8 @@ void IBuildListActions.DeleteBuild(BuildEntry build)
return;
var confirm = EditorUtility.DisplayDialog(
- "Delete Build",
- $"Delete build data for '{build.BuildName}'?\nThis cannot be undone.",
+ "Delete Build Report Directory",
+ $"Delete Build Report Directory from {BuildHistory.BuildHistoryDirectory}?\n\nThis does not delete asset database artifacts nor build outputs. This cannot be undone.",
"Delete",
"Cancel");
if (!confirm)
@@ -218,10 +373,10 @@ void IBuildListActions.DeleteAllBuilds()
if (builds.Length == 0)
return;
- var buildNoun = builds.Length == 1 ? "build" : "builds";
+ var directoryNoun = builds.Length == 1 ? "Build Report Directory" : "Build Report Directories";
var confirm = EditorUtility.DisplayDialog(
- "Delete All Builds",
- $"Delete all {builds.Length} {buildNoun} from {BuildHistory.BuildHistoryDirectory}?\nThis cannot be undone.",
+ "Delete All Build Report Directories",
+ $"Delete all {builds.Length} {directoryNoun} from {BuildHistory.BuildHistoryDirectory}?\n\nThis does not delete asset database artifacts nor build outputs. This cannot be undone.",
"Delete All",
"Cancel");
if (!confirm)
@@ -258,20 +413,37 @@ void IBuildListActions.CopyPath(BuildEntry build)
EditorGUIUtility.systemCopyBuffer = build.FolderPath;
}
- void IBuildListActions.RegenerateAnalysis(BuildEntry build)
+ async void IBuildListActions.RegenerateAnalysis(BuildEntry build)
{
if (build == null)
return;
+ await LoadAndApplyAsync(build, () => m_Service.RegenerateBuildAnalysisAsync(build.BuildSessionGUID));
+ }
+ }
- try
- {
- m_SelectedBuildAnalysis = m_Service.RegenerateBuildAnalysis(build.BuildSessionGUID);
- m_TabHost.SetSelection(build, m_SelectedBuildAnalysis);
- }
- catch (Exception e)
- {
- Debug.LogError($"{BuildAnalysisConstants.k_ConsoleLogPrefix} Failed to re-generate analysis: {e.Message}");
- }
+ // Decides which async selection/regenerate result is still worth applying.
+ internal sealed class SelectionGate
+ {
+ private readonly Func m_IsAlive;
+ private int m_Seq;
+ private GUID m_TargetGuid;
+
+ public SelectionGate(Func isAlive) => m_IsAlive = isAlive;
+
+ public int Begin(GUID target)
+ {
+ m_TargetGuid = target;
+ return ++m_Seq;
+ }
+
+ public bool IsStale(int seq) => seq != m_Seq || !m_IsAlive();
+
+ public bool IsCurrentTarget(GUID guid) => guid == m_TargetGuid;
+
+ public void Clear()
+ {
+ m_Seq++;
+ m_TargetGuid = default;
}
}
}
diff --git a/Modules/BuildAnalysis/UI/BuildListPanel.cs b/Modules/BuildAnalysis/UI/BuildListPanel.cs
index 5aa486705d..ffd219c522 100644
--- a/Modules/BuildAnalysis/UI/BuildListPanel.cs
+++ b/Modules/BuildAnalysis/UI/BuildListPanel.cs
@@ -17,9 +17,9 @@ internal sealed class BuildListPanel : VisualElement
internal const string k_SelectedBuildKey = "BuildAnalysisWindow.SelectedBuildSessionGUID";
internal const string k_FooterWarningClass = "build-list-footer--warning";
- private const double k_FooterWarnThreshold = 0.8;
- private const string k_FooterWarningTooltip = "Build limit approaching. To edit the limit, go to Project Settings > Build Pipeline.";
- private const string k_FooterExceededTooltip = "Build limit exceeded. Older builds will be removed on the next build. To edit the limit, go to Project Settings > Build Pipeline.";
+ private const double k_FooterWarnThreshold = 0.7;
+ internal const string k_FooterWarningTooltip = "Build limit approaching. Older builds will be automatically deleted once the limit is hit. To edit the limit, go to Project Settings > Build Pipeline.";
+ internal const string k_FooterExceededTooltip = "Build limit exceeded. Older builds will be automatically deleted on the next build. To edit the limit, go to Project Settings > Build Pipeline.";
public event Action SelectionChanged;
@@ -28,16 +28,19 @@ internal sealed class BuildListPanel : VisualElement
private readonly ToolbarMenu m_SettingsMenu;
private readonly ListView m_BuildListView;
private readonly VisualElement m_EmptyState;
- private readonly Label m_EmptyStateTitle;
private readonly Label m_EmptyStateDescription;
private readonly VisualElement m_FooterRoot;
+ private readonly VisualElement m_FooterLimit;
private readonly Label m_FooterLabel;
+ private readonly Label m_FooterSearchCount;
private BuildEntry[] m_AllBuilds = Array.Empty();
+ private int m_BuildHistoryLimit;
private string[] m_AllPlatformNames = Array.Empty();
private BuildEntry[] m_FilteredBuilds = Array.Empty();
private string m_CurrentSearchText = string.Empty;
private BuildEntry m_SelectedBuild;
+ private int m_PendingScrollIndex = -1;
public BuildEntry SelectedBuild => m_SelectedBuild;
@@ -52,10 +55,11 @@ public BuildListPanel(IBuildListActions actions)
m_SettingsMenu = this.Q("build-settings-menu");
m_BuildListView = this.Q("build-list");
m_EmptyState = this.Q("empty-state");
- m_EmptyStateTitle = this.Q