버전:2021.3+
이 예제는 바인딩된 직렬화된 오브젝트의 프로퍼티가 변경될 때 콜백을 수신하는 방법을 보여줍니다.
이 예제에서는 두 개의 필드가 있는 커스텀 인스펙터를 만듭니다.필드 값이 특정 범위를 벗어나는 경우 사용자에게 경고합니다.
이 예제에서 생성한 완성된 파일은 GitHub 저장소에서 확인할 수 있습니다.
이 가이드는 Unity 에디터, UI 툴킷, C# 스크립팅에 익숙한 개발자용입니다.시작하기 전에 먼저 다음을 숙지하십시오.
m_BaseDamage
및 m_HardModeModifier
프로퍼티를 가진 ‘Weapon’ 클래스를 ’MonoBehaviour’로 정의하는 C# 스크립트를 작성합니다.
템플릿을 사용하여 Unity에서 프로젝트를 생성합니다.
프로젝트 창에서 파일을 저장할 폴더 이름을 ’callback-any-SerializedProperty-changes’로 지정합니다.
Weapon.cs
라는 이름의 C# 스크립트를 생성하고 해당 콘텐츠를 다음과 같이 바꿉니다.
using UnityEngine;
namespace UIToolkitExamples
{
public class Weapon :MonoBehaviour
{
public const float maxDamage = 9999f;
[SerializeField]
float m_BaseDamage;
[SerializeField]
float m_HardModeModifier;
public float GetDamage(bool hardMode)
{
return hardMode ? m_BaseDamage * m_HardModeModifier : m_BaseDamage;
}
}
}
Weapon
에 대한 커스텀 인스펙터를 정의하고 TrackSerializedObjectValue()
메서드를 사용하여 m_BaseDamage
및 m_HardModeModifier
프로퍼티의 변경 사항을 확인하는 C# 스크립트를 생성합니다.
callback-any-SerializedProperty-changes 폴더에 Editor
라는 이름의 폴더를 생성합니다.
Editor 폴더에서 WeaponCustomEditor.cs
라는 이름의 C# 스크립트를 생성하고 해당 콘텐츠를 다음과 같이 바꿉니다.
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
namespace UIToolkitExamples
{
[CustomEditor(typeof(Weapon))]
public class WeaponCustomEditor :Editor
{
// This is text used for the warning labels.
const string k_NegativeWarningText =
"This weapon has a negative final damage on at least 1 difficulty level.";
static readonly string k_DamageCapWarningText =
"This weapon has an excessive final damage that is capped to " + Weapon.maxDamage +
" on at least 1 difficulty level.";
// These are labels to warn users about negative damage and excessive damage.
Label m_NegativeWarning, m_DamageCapWarning;
public override VisualElement CreateInspectorGUI()
{
VisualElement root = new();
// Create FloatFields for serialized properties.
var baseDamageField = new FloatField("Base Damage") { bindingPath = "m_BaseDamage" };
var modifierField = new FloatField("Hard Mode Modifier") { bindingPath = "m_HardModeModifier" };
root.Add(baseDamageField);
root.Add(modifierField);
// Create warning labels and style them so they stand out.
var warnings = new VisualElement();
m_NegativeWarning = new(k_NegativeWarningText);
m_DamageCapWarning = new(k_DamageCapWarningText);
warnings.style.color = Color.red;
warnings.style.unityFontStyleAndWeight = FontStyle.Bold;
warnings.Add(m_NegativeWarning);
warnings.Add(m_DamageCapWarning);
root.Add(warnings);
// Determine whether to show the warnings at the start.
CheckForWarnings(serializedObject);
// Whenever any serialized property on this serialized object changes its value, call CheckForWarnings.
root.TrackSerializedObjectValue(serializedObject, CheckForWarnings);
return root;
}
// Check the current values of the serialized properties to either display or hide the warnings.
void CheckForWarnings(SerializedObject serializedObject)
{
// For each possible damage values of the weapon, determine whether it's negative and whether it's above the
// maximum damage value.
var weapon = serializedObject.targetObject as Weapon;
var damages = new float[] { weapon.GetDamage(true), weapon.GetDamage(false) };
var foundNegativeDamage = false;
var foundCappedDamage = false;
foreach (var damage in damages)
{
foundNegativeDamage = foundNegativeDamage || damage < 0;
foundCappedDamage = foundCappedDamage || damage > Weapon.maxDamage;
}
// Display or hide warnings depending on the values of the damages.
m_NegativeWarning.style.display = foundNegativeDamage ?DisplayStyle.Flex :DisplayStyle.None;
m_DamageCapWarning.style.display = foundCappedDamage ?DisplayStyle.Flex :DisplayStyle.None;
}
}
}
씬에서 빈 게임 오브젝트를 만듭니다.
해당 게임 오브젝트를 선택합니다.
인스펙터에서 Weapon 컴포넌트를 추가합니다.
Weapon 컴포넌트에서 필드의 값을 다음과 같이 변경합니다.
Base Damage 또는 Base Damage에 Hard Mode Modifier를 곱한 값이 음수이면 경고 메시지가 표시됩니다. Base Damage 또는 Base Damage에 Hard Mode Modifier를 곱한 값이 9999보다 크면 다른 경고 메시지가 표시됩니다.
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.