Unity 6.3
0 онлайн 53 гостей 3 в системе
Вход

TerrainPaintToolWithOverlays<T0>

класс в UnityEditor.TerrainTools

Наследуется от:TerrainTools.TerrainPaintToolWithOverlaysBase

Описание

Базовый класс для инструментов рисования по Terrain, наследующих от Editor Tools.

Унаследуйтесь от этого класса, чтобы реализовать собственные инструменты рисования по ландшафту, которые также появятся в оверлее Terrain Tools.

using UnityEngine;
using UnityEditor;
using UnityEditor.TerrainTools;

class CustomTerrainToolWithOverlays : TerrainPaintToolWithOverlays<CustomTerrainToolWithOverlays> { private float m_BrushRotation; // Return true for this property to show the brush selector overlay public override bool HasBrushMask => true;

// Return true for this property to show the tool settings overlay public override bool HasToolSettings => true; // Return true for this property to display the brush attributes overlay public override bool HasBrushAttributes => true; // File names of the light theme icons - prepending d_ to the file name generates dark theme variants. // public override string OnIcon => "Assets/Icon_on.png"; // public override string OffIcon => "Assets/Icon_off.png";

// The toolbar category the icon appears under public override TerrainCategory Category => TerrainCategory.CustomBrushes;

// Where in the icon list the icon appears public override int IconIndex => 100; // Name of the Terrain Tool. This appears in the tool UI public override string GetName() { return "Examples/Basic Custom Terrain Tool"; }

// Description for the Terrain Tool. This appears in the tool UI public override string GetDescription() { return "This Terrain Tool shows how to add custom UI to a tool and paint height."; }

// Override this function to add UI elements to the inspector public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) { EditorGUILayout.HelpBox("In Terrain Inspector", MessageType.None); editContext.ShowBrushesGUI(5, BrushGUIEditFlags.All); m_BrushRotation = EditorGUILayout.Slider("Rotation", m_BrushRotation, 0, 360); }

// Override this function to add UI elements to the tool settings overlay public override void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext) { EditorGUILayout.HelpBox("In Overlays", MessageType.None); m_BrushRotation = EditorGUILayout.Slider("Rotation", m_BrushRotation, 0, 360); }

// Ease of use function for rendering modified Terrain Texture data into a PaintContext. Both OnRenderBrushPreview and OnPaint use this. private void RenderIntoPaintContext(UnityEngine.TerrainTools.PaintContext paintContext, Texture brushTexture, float brushOpacity, UnityEngine.TerrainTools.BrushTransform brushXform) { // Get the built-in painting Material reference Material mat = UnityEngine.TerrainTools.TerrainPaintUtility.GetBuiltinPaintMaterial(); // Bind the current brush texture mat.SetTexture("_BrushTex", brushTexture); // Bind the tool-specific shader properties var opacity = Event.current.control ? -brushOpacity : brushOpacity; mat.SetVector("_BrushParams", new Vector4(opacity, 0.0f, 0.0f, 0.0f)); // Set up the material for reading from/writing into the PaintContext texture data. This step is necessary to set up the correct shader properties for appropriately transforming UVs and sampling textures within the shader UnityEngine.TerrainTools.TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); // Render into the PaintContext's destinationRenderTexture using the built-in painting Material. The ID for the Raise/Lower pass is 0 Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, 0); } // Render Tool previews in the Scene view public override void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext) { // Don't render preview if this isn't a Repaint if (Event.current.type != EventType.Repaint) return;

// Only do the rest if user mouse hits valid terrain if (!editContext.hitValidTerrain) return;

// Get the current BrushTransform under the mouse position relative to the Terrain UnityEngine.TerrainTools.BrushTransform brushXform = UnityEngine.TerrainTools.TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, m_BrushRotation); // Get the PaintContext for the current BrushTransform. This has a sourceRenderTexture from which to read existing Terrain texture data. UnityEngine.TerrainTools.PaintContext paintContext = UnityEngine.TerrainTools.TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); // Get the built-in Material for rendering Brush Previews Material previewMaterial = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(); // Render the brush preview for the sourceRenderTexture. This shows up as a projected brush mesh rendered on top of the Terrain TerrainPaintUtilityEditor.DrawBrushPreview(paintContext, TerrainBrushPreviewMode.SourceRenderTexture, editContext.brushTexture, brushXform, previewMaterial, 0); // Render changes into the PaintContext destinationRenderTexture RenderIntoPaintContext(paintContext, editContext.brushTexture, editContext.brushStrength, brushXform); // Restore old render target RenderTexture.active = paintContext.oldRenderTexture; // Bind the sourceRenderTexture to the preview Material. This is used to compute deltas in height previewMaterial.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture); // Render a procedural mesh displaying the delta/displacement in height from the source Terrain texture data. When you modify Terrain height, this shows how much the next paint operation alters the Terrain height TerrainPaintUtilityEditor.DrawBrushPreview(paintContext, TerrainBrushPreviewMode.DestinationRenderTexture, editContext.brushTexture, brushXform, previewMaterial, 1); // Cleanup resources UnityEngine.TerrainTools.TerrainPaintUtility.ReleaseContextResources(paintContext); } // Perform painting operations that modify the Terrain texture data public override bool OnPaint(Terrain terrain, IOnPaint editContext) { // Get the current BrushTransform under the mouse position relative to the Terrain UnityEngine.TerrainTools.BrushTransform brushXform = UnityEngine.TerrainTools.TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, m_BrushRotation); // Get the PaintContext for the current BrushTransform. This has a sourceRenderTexture from which to read existing Terrain texture data // and a destinationRenderTexture into which to write new Terrain texture data UnityEngine.TerrainTools.PaintContext paintContext = UnityEngine.TerrainTools.TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds()); // Call the common rendering function that OnRenderBrushPreview and OnPaint use RenderIntoPaintContext(paintContext, editContext.brushTexture, editContext.brushStrength, brushXform); // Commit the modified PaintContext with a provided string for tracking Undo operations. This function handles Undo and resource cleanup for you UnityEngine.TerrainTools.TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Raise or Lower Height");

// Return whether Trees and Details should be hidden while you paint with this Terrain Tool return true; } }
Унаследованные члены 5

Свойства

СвойствоОписание
gridSnapEnabledИспользуйте это свойство, чтобы разрешить текущему EditorTool включать или отключать привязку к сетке.
isHiddenВозвращает true, если пользовательский редактор скрыт. Возвращает false в противном случае. Редактор не отображает скрытые инструменты в накладке Инструменты представления Scene.
targetИнспектируемый объект.
targetsМассив проверяемых объектов.
toolbarIconЗначок и tooltip для этого инструмента пользовательского редактора. Если эта функция не реализована, на панели инструментов отображается значок Inspector для типа цели. Если тип цели не определен, на панели инструментов отображается значок Режим инструмента.
hideFlagsДолжен ли объект быть скрытым, сохраняться с Scene или изменяться пользователем?
nameИмя объекта.
CategoryTerrainCategory, к которому принадлежит инструмент Terrain Tool.
HasBrushAttributesTrue, если у инструмента Terrain имеются атрибуты brush, false в противном случае.
HasBrushMaskTrue, если инструмент Terrain Tool имеет маски кисти, false в противном случае.
HasToolSettingsTrue, если у инструмента Terrain Tool есть пользовательские настройки, false в противном случае.
IconIndexИндекс, на котором вы должны разместить инструмент «Теннисный корт» в накладке «Теннисный корт».
OffIconЗначок, отображаемый в накладке Инструменты местности, когда инструмент местности не выбран.
OnIconЗначок, отображаемый в накладке Инструменты местности при выборе инструмента местности.
TerrainПоследняя обнаруженная местность или последний активный экземпляр объекта местности.

Открытые методы

МетодОписание
IsAvailableПроверяет доступность пользовательского инструмента редактора исходя из состояния редактора. Недоступные инструменты отображаются как отключённые в оверлее Tools окна Scene.
OnActivatedПосле этого EditorTool становится активным инструментом.
OnToolGUIИспользуйте этот метод для реализации настраиваемого редактора.
OnWillBeDeactivatedВызванный до этого EditorTool перестает быть активным инструментом.
PopulateMenuДобавление пунктов меню в контекстное меню Scene.
SetHiddenЗадаёт скрытое состояние пользовательского инструмента редактора. Скрытые инструменты редактор не показывает в оверлее Tools окна Scene.
GetInstanceIDПолучает экземпляр ID объекта.
ToStringВозвращает имя объекта.
GetDescriptionОписание инструмента &quot; Рельеф &quot;.
GetNameИмя инструмента «Территория».
OnActivatedЭта функция вызывается при активации инструмента.
OnDisableВызывается при уничтожении инструмента.
OnEnableВызывается при создании инструмента.
OnEnterToolModeЭта функция вызывается при активации инструмента «Территория».
OnExitToolModeЭта функция вызывается, когда Инструмент Территория становится неактивным.
OnInspectorGUIОбратный вызов OnInspectorGUI.
OnPaintОбратный вызов рисунка инструмента «Настраиваемый рельеф».
OnRenderBrushPreviewИспользуйте этот метод для реализации предварительного просмотра настраиваемого инструмента и поведения UI, которое отображается только когда мышка находится в пределах SceneView или когда вы активно используете этот инструмент.
OnSceneGUIОбратный вызов OnSceneGUI.
OnToolGUIЭтот метод используется для реализации настраиваемого инструмента рисования редактора рельефа.
OnToolSettingsGUIСодержит код IMGUI для пользовательских настроек, помимо общих настроек.
OnWillBeDeactivatedВызывается до того, как инструмент рисования рельефа с накладками перестанет быть активным инструментом.

Статические методы

МетодОписание
DestroyУдаляет GameObject, компонент или ресурс.
DestroyImmediateНемедленно уничтожает указанный объект. Используйте с осторожностью и только в режиме редактирования.
DontDestroyOnLoadНе уничтожать целевой Объект при загрузке нового Scene.
FindAnyObjectByTypeПолучает любой активный загруженный объект типа Type.
FindFirstObjectByTypeПолучает первый активный загруженный объект типа Type.
FindObjectsByTypeПолучает список всех загруженных объектов типа Type.
InstantiateКлонирует исходный объект и возвращает клон.
InstantiateAsyncЗахватывает моментальный снимок первоначального объекта (который должен быть связан с каким-либо GameObject) и возвращает AsyncInstantiateOperation.
CreateInstanceСоздает экземпляр скриптового объекта.

Операторы

ОператорОписание
boolСуществует ли объект?
оператор!=Сравнивает, если два объекта ссылаются на разные объекты.
оператор ==Сравнение двух ссылок на объекты для определения того, относятся ли они к одному и тому же объекту.

Сообщения

СообщениеОписание
AwakeВызывается при создании экземпляра ScriptableObject.
OnDestroyЭта функция вызывается, когда скриптовый объект будет уничтожен.
OnDisableЭта функция вызывается, когда скриптовый объект выходит за пределы области действия.
OnEnableЭта функция вызывается при загрузке объекта.
OnValidateФункция только для редактора, которую вызывает Unity при загрузке скрипта или изменении значения в Inspector.
ResetСброс значений по умолчанию.