This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,171 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// Example script controlling a BlurredHexagon Material with <see cref="Slider"/>s.
/// </summary>
[RequireComponent(typeof(Graphic))]
public class BlurredHexagonController : UIBehaviour, IMaterialModifier
{
const string _saturationRef = "_Background_Saturation", _tintRef = "_Tint", _hexagonDissolveRef = "_Hexagon_Dissolve",
_hexagonTilesRef = "_Hexagon_Tiles", _blurRef = "_Blur", _blurCyclesRef = "_Blur_Cycles", _blurSamplesPerCycleRef = "_Blur_Samples_Per_Cycle";
[SerializeField] Slider _saturationSlider, _tintRedSlider, _tintGreenSlider, _tintBlueSlider,
_hexagonDissolveSlider, _hexagonTilesSlider, _blurSlider, _blurCyclesSlider, _blurSamplesPerCycleSlider;
static int _saturationId, _tintId, _hexagonDissolveId, _hexagonTilesId, _blurId, _blurCyclesId, _blurSamplesPerCycleId;
private float _saturation, _hexagonDissolve, _hexagonTiles, _blur, _blurCycles, _blurSamplesPerCycle;
private Color _tint = Color.gray;
public float Saturation
{
get => _saturation;
set
{
_saturation = value;
Graphic.SetMaterialDirty();
}
}
public Color Tint
{
get => _tint;
set
{
_tint = value;
Graphic.SetMaterialDirty();
}
}
public float TintRed { get => Tint.r; set => Tint = new Color(value, _tint.g, _tint.b); }
public float TintGreen { get => Tint.g; set => Tint = new Color(_tint.r, value, _tint.b); }
public float TintBlue { get => Tint.b; set => Tint = new Color(_tint.r, _tint.g, value); }
public float HexagonDissolve
{
get => _hexagonDissolve;
set
{
_hexagonDissolve = value;
Graphic.SetMaterialDirty();
}
}
public float HexagonTiles
{
get => _hexagonTiles;
set
{
_hexagonTiles = value;
Graphic.SetMaterialDirty();
}
}
public float Blur
{
get => _blur;
set
{
_blur = value;
Graphic.SetMaterialDirty();
}
}
public float BlurCycles
{
get => _blurCycles;
set
{
_blurCycles = value;
Graphic.SetMaterialDirty();
}
}
public float BlurSamplesPerCycle
{
get => _blurSamplesPerCycle;
set
{
_blurSamplesPerCycle = value;
Graphic.SetMaterialDirty();
}
}
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
protected override void Awake()
{
base.Awake();
// get ids from prop names
_saturationId = Shader.PropertyToID(_saturationRef);
_tintId = Shader.PropertyToID(_tintRef);
_hexagonDissolveId = Shader.PropertyToID(_hexagonDissolveRef);
_hexagonTilesId = Shader.PropertyToID(_hexagonTilesRef);
_blurId = Shader.PropertyToID(_blurRef);
_blurCyclesId = Shader.PropertyToID(_blurCyclesRef);
_blurSamplesPerCycleId = Shader.PropertyToID(_blurSamplesPerCycleRef);
// initialize values with the material's values
var mat = Graphic.material;
_saturation = mat.GetFloat(_saturationId);
_tint = mat.GetColor(_tintId);
_hexagonDissolve = mat.GetFloat(_hexagonDissolveId);
_hexagonTiles = mat.GetFloat(_hexagonTilesId);
_blur = mat.GetFloat(_blurId);
_blurCycles = mat.GetFloat(_blurCyclesId);
_blurSamplesPerCycle = mat.GetFloat(_blurSamplesPerCycleId);
// initialize the sliders with the material's values
_saturationSlider?.SetValueWithoutNotify(Saturation);
_tintRedSlider?.SetValueWithoutNotify(TintRed);
_tintGreenSlider?.SetValueWithoutNotify(TintGreen);
_tintBlueSlider?.SetValueWithoutNotify(TintBlue);
_hexagonDissolveSlider?.SetValueWithoutNotify(HexagonDissolve);
_hexagonTilesSlider?.SetValueWithoutNotify(HexagonTiles);
_blurSlider?.SetValueWithoutNotify(Blur);
_blurCyclesSlider?.SetValueWithoutNotify(BlurCycles);
_blurSamplesPerCycleSlider?.SetValueWithoutNotify(BlurSamplesPerCycle);
// add listeners to sliders' value changed events
_saturationSlider?.onValueChanged.AddListener((x) => { Saturation = x; });
_tintRedSlider?.onValueChanged?.AddListener((x) => { TintRed = x; });
_tintGreenSlider?.onValueChanged?.AddListener((x) => { TintGreen = x; });
_tintBlueSlider?.onValueChanged?.AddListener((x) => { TintBlue = x; });
_hexagonDissolveSlider?.onValueChanged.AddListener((x) => { HexagonDissolve = x; });
_hexagonTilesSlider?.onValueChanged.AddListener((x) => { HexagonTiles = x; });
_blurSlider?.onValueChanged.AddListener((x) => { Blur = x; });
_blurCyclesSlider?.onValueChanged.AddListener((x) => { BlurCycles = x; });
_blurSamplesPerCycleSlider?.onValueChanged.AddListener((x) => { BlurSamplesPerCycle = x; });
}
public Material GetModifiedMaterial(Material baseMaterial)
{
// nothing's initialized unless we're in play mode
if (!Application.isPlaying || enabled == false)
return baseMaterial;
baseMaterial.SetFloat(_saturationId, Saturation);
baseMaterial.SetColor(_tintId, Tint);
baseMaterial.SetFloat(_hexagonDissolveId, HexagonDissolve);
baseMaterial.SetFloat(_hexagonTilesId, HexagonTiles);
baseMaterial.SetFloat(_blurId, Blur);
baseMaterial.SetFloat(_blurCyclesId, BlurCycles);
baseMaterial.SetFloat(_blurSamplesPerCycleId, BlurSamplesPerCycle);
return baseMaterial;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9f19c97b36748f849a73a3321b7e3c64
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 993fe007a55f1af498ed451a65450d22
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,29 @@
using UnityEngine;
using UnityEditor;
using UnityEditor.UI;
namespace Unity.UI.Shaders.Sample.Editor
{
[CustomEditor(typeof(CustomToggle))]
public class CustomToggleEditor : ToggleEditor
{
SerializedProperty m_OnStateChangedProperty;
protected override void OnEnable()
{
base.OnEnable();
m_OnStateChangedProperty = serializedObject.FindProperty("onStateChanged");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_OnStateChangedProperty);
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1ab1c9b915235414cb5fc563370fcddf
@@ -0,0 +1,31 @@
using UnityEngine;
using UnityEditor;
namespace Unity.UI.Shaders.Sample.Editor
{
[CustomPropertyDrawer(typeof(MinMaxSliderAttribute))]
public class MinMaxSliderDrawer : PropertyDrawer
{
MinMaxSliderAttribute range => (MinMaxSliderAttribute)attribute;
Vector2 _value;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.propertyType == SerializedPropertyType.Vector2)
{
_value = property.vector2Value;
EditorGUI.BeginChangeCheck();
EditorGUI.MinMaxSlider(position, label, ref _value.x, ref _value.y, range.min, range.max);
if (EditorGUI.EndChangeCheck())
{
property.vector2Value = _value;
}
}
else
{
EditorGUI.PropertyField(position, property, label);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 173897d9cfd2ff445912c20f991e22e8
@@ -0,0 +1,18 @@
using UnityEditor;
using UnityEngine;
using TMPro;
namespace Unity.UI.Shaders.Sample.Editor
{
public static class TMProResourcesCheck
{
[InitializeOnLoadMethod]
static void Init()
{
var tmProSettings = TMP_Settings.instance; // getting the instance should be enough
//var tmProStettings = Resources.Load<TMP_Settings>("TMP Settings");
//if (tmProStettings == null)
// TMP_PackageResourceImporterWindow.ShowPackageImporterWindow();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e9ec04bf20ec56e4ea9b5ee986bfe9e8
@@ -0,0 +1,30 @@
{
"name": "Unity.UI.Shaders.Sample.Editor",
"rootNamespace": "Unity.UI.Shaders.Sample.Editor",
"references": [
"GUID:2bafac87e7f4b9b418d9448d219b01ab",
"GUID:343deaaf83e0cee4ca978e7df0b80d21",
"GUID:6055be8ebefd69e48b49212b09b47b2f",
"GUID:6546d7765b4165b40850b3667f981c26",
"GUID:b3f345a8790ef4c419a5d3ea60e9f97d"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [
"UGUI"
],
"versionDefines": [
{
"name": "com.unity.ugui",
"expression": "",
"define": "UGUI"
}
],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7a3378c8f903ad844b18cfbbba053b88
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f17fe3cdd71a5244891e2c20169e5fea
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0d7a45b2c5b65d5419f1a6bb6d885487
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
using UnityEngine;
namespace Unity.UI.Shaders.Sample
{
public class MinMaxSliderAttribute : PropertyAttribute
{
public float min;
public float max;
public MinMaxSliderAttribute(float min, float max)
{
this.min = min;
this.max = max;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bddc2c3c9675f9945acfdfc2dd2a4702
@@ -0,0 +1,128 @@
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Events;
using UnityEditor.SceneManagement;
#endif
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// A component that works like a <see cref="Button"/> implementing <see cref="IMaterialModifier"/> to update the <see cref="Graphic.material"/> when
/// <see cref="Selectable.DoStateTransition(Selectable.SelectionState, bool)"/> is called.
/// <para>Implemented as a <see cref="Selectable"/>.</para>
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/Button")]
public class CustomButton : Selectable, IPointerClickHandler, ISubmitHandler /*Button*/, IMaterialModifier
{
public UnityEvent onClick;
public UnityEvent<int> onStateChanged;
private static readonly string _statePropertyName = "_State";
private Material _material;
private int? _statePropertyId;
private int StatePropertyId
{
get
{
if (!_statePropertyId.HasValue)
_statePropertyId = Shader.PropertyToID(_statePropertyName);
return _statePropertyId.Value;
}
}
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
#if UNITY_EDITOR
[SerializeField, HideInInspector] Material defaultMaterial;
protected internal void AssignDefaultMaterial()
{
if (defaultMaterial != null)
Graphic.material = defaultMaterial;
}
protected override void Reset()
{
base.Reset();
// we don't need a transition by default
transition = Transition.None;
}
#endif
protected override void DoStateTransition(SelectionState state, bool instant)
{
base.DoStateTransition(state, instant);
onStateChanged?.Invoke((int)state);
Graphic.SetMaterialDirty();
}
void Click()
{
if (IsActive() && IsInteractable())
onClick?.Invoke();
}
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left)
return;
Click();
}
public void OnSubmit(BaseEventData eventData)
{
Click();
}
public virtual Material GetModifiedMaterial(Material baseMaterial)
{
_material ??= new(baseMaterial);
_material.CopyPropertiesFromMaterial(baseMaterial);
if (_material.HasFloat(StatePropertyId))
_material.SetFloat(StatePropertyId, (int)currentSelectionState);
return _material;
}
#if UNITY_EDITOR
[MenuItem("GameObject/UI (Canvas)/ShaderGraph Samples/Button", false, 30)]
static void CreateButtonGameObject(MenuCommand command)
{
GameObject go = ObjectFactory.CreateGameObject("SG Button", new Type[] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(CustomButton) });
StageUtility.PlaceGameObjectInCurrentStage(go);
go.GetComponent<CustomButton>().AssignDefaultMaterial();
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
GameObject contextObject = command.context as GameObject;
if (contextObject != null)
{
GameObjectUtility.SetParentAndAlign(go, contextObject);
Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name);
}
Selection.activeGameObject = go;
}
#endif
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 457b592a913195e4b8cb0804abbe40de
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- m_TargetGraphic: {instanceID: 0}
- defaultMaterial: {fileID: -876546973899608171, guid: 9166601a958188e4caa2b1418d72baaf, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,311 @@
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// A custom Slider.
/// <para>Unlike a <see cref="Slider"/>, this uses only a single RectTransform.</para>
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/Slider")]
[RequireComponent(typeof(Graphic))]
[DisallowMultipleComponent]
public class CustomSlider : Selectable, IDragHandler, IInitializePotentialDragHandler, IMaterialModifier
{
public enum Direction { LeftToRight, RightToLeft, BottomToTop, TopToBottom }
static Vector2 FromDirection(Direction direction) => direction switch
{
Direction.LeftToRight => Vector2.right,
Direction.RightToLeft => Vector2.left,
Direction.BottomToTop => Vector2.up,
Direction.TopToBottom => Vector2.down,
_ => Vector2.zero
};
[SerializeField] Direction _direction;
[SerializeField, Range(0f, 1f)] float _value = 0.5f;
public UnityEvent<int> onStateChanged;
public UnityEvent<float> onValueChanged;
private static readonly string _statePropertyName = "_State";
private static readonly string _sliderValuePropertyName = "_SliderValue";
private Material _material;
float stepSize = 0.1f;
Vector2 _rangeOffset = Vector2.zero;
public Direction direction => _direction;
private int? _statePropertyId, _sliderValuePropertyId;
private int StatePropertyId
{
get
{
if (!_statePropertyId.HasValue)
_statePropertyId = Shader.PropertyToID(_statePropertyName);
return _statePropertyId.Value;
}
}
private int SliderValuePropertyId
{
get
{
if (!_sliderValuePropertyId.HasValue)
_sliderValuePropertyId = Shader.PropertyToID(_sliderValuePropertyName);
return _sliderValuePropertyId.Value;
}
}
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
private Canvas RootCanvas => Graphic.canvas.rootCanvas;
private RectTransform rectTransform => Graphic.rectTransform;
public float Value
{
get => _value;
private set
{
_value = value;
Graphic.SetMaterialDirty();
onValueChanged?.Invoke(value);
}
}
Vector2 DirectionVector => FromDirection(direction);
Vector3 Vector => new Vector3(Value, DirectionVector.x, DirectionVector.y);
#if UNITY_EDITOR
[SerializeField, HideInInspector] Material defaultMaterial;
protected internal void AssignDefaultMaterial()
{
if (defaultMaterial != null)
Graphic.material = defaultMaterial;
}
protected override void Reset()
{
base.Reset();
// we don't need a transition by default
transition = Transition.None;
Value = _value;
}
protected override void OnValidate()
{
base.OnValidate();
//Graphic.SetMaterialDirty(); // this makes the Editor hick up when changing the value
// So instead, we just change the material, but if another IMaterialModifier was added after this,
// this will have no visible effect.
if (_material != null && _material.HasVector(SliderValuePropertyId))
_material.SetVector(SliderValuePropertyId, Vector);
}
#endif
protected override void DoStateTransition(SelectionState state, bool instant)
{
base.DoStateTransition(state, instant);
onStateChanged?.Invoke((int)state);
Graphic.SetMaterialDirty();
}
public virtual Material GetModifiedMaterial(Material baseMaterial)
{
_material ??= new(baseMaterial);
_material.CopyPropertiesFromMaterial(baseMaterial);
if (_material.HasFloat(StatePropertyId))
_material.SetFloat(StatePropertyId, (int)currentSelectionState);
if (_material.HasVector(SliderValuePropertyId))
_material.SetVector(SliderValuePropertyId, Vector);
return _material;
}
/// <summary>
/// <see cref="Slider.UpdateDrag(PointerEventData, Camera)"/>
/// </summary>
void UpdateDrag(PointerEventData eventData, Camera cam)
{
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, cam, out Vector2 localPoint))
{
Debug.LogWarning("missed!?");
return;
}
float pivot = rectTransform.pivot[(int)axis];
float size = rectTransform.rect.size[(int)axis];
(float min, float max) range = (size * -pivot, size * (1 - pivot));
float val = Mathf.InverseLerp(range.min, range.max, localPoint[(int)axis]);
Value = reverseValue ? 1 - val : val;
}
/// <summary>
/// <see cref="Slider.MayDrag(PointerEventData eventData)"/>
/// </summary>
private bool MayDrag(PointerEventData eventData)
{
return IsActive() && IsInteractable() && eventData.button == PointerEventData.InputButton.Left;
}
public override void OnPointerDown(PointerEventData eventData)
{
if (!MayDrag(eventData))
return;
base.OnPointerDown(eventData);
UpdateDrag(eventData, eventData.pressEventCamera);
}
public virtual void OnDrag(PointerEventData eventData)
{
if (!MayDrag(eventData))
return;
UpdateDrag(eventData, eventData.pressEventCamera);
}
enum Axis
{
Horizontal = 0,
Vertical = 1
}
Axis axis { get { return (direction == Direction.LeftToRight || direction == Direction.RightToLeft) ? Axis.Horizontal : Axis.Vertical; } }
bool reverseValue { get { return direction == Direction.RightToLeft || direction == Direction.TopToBottom; } }
/// <summary>
/// See <see cref="Slider.OnMove(AxisEventData)"/>
/// </summary>
public override void OnMove(AxisEventData eventData)
{
if (!IsActive() || !IsInteractable())
{
base.OnMove(eventData);
return;
}
switch (eventData.moveDir)
{
case MoveDirection.Left:
if (axis == Axis.Horizontal && FindSelectableOnLeft() == null)
Value = reverseValue ? Value + stepSize : Value - stepSize;
else
base.OnMove(eventData);
break;
case MoveDirection.Right:
if (axis == Axis.Horizontal && FindSelectableOnRight() == null)
Value = reverseValue ? Value - stepSize : Value + stepSize;
else
base.OnMove(eventData);
break;
case MoveDirection.Up:
if (axis == Axis.Vertical && FindSelectableOnUp() == null)
Value = reverseValue ? Value - stepSize : Value + stepSize;
else
base.OnMove(eventData);
break;
case MoveDirection.Down:
if (axis == Axis.Vertical && FindSelectableOnDown() == null)
Value = reverseValue ? Value + stepSize : Value - stepSize;
else
base.OnMove(eventData);
break;
}
}
/// <summary>
/// See <see cref="Selectable.FindSelectableOnLeft"/>
/// </summary>
public override Selectable FindSelectableOnLeft()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Horizontal)
return null;
return base.FindSelectableOnLeft();
}
/// <summary>
/// See <see cref="Selectable.FindSelectableOnRight"/>
/// </summary>
public override Selectable FindSelectableOnRight()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Horizontal)
return null;
return base.FindSelectableOnRight();
}
/// <summary>
/// See <see cref="Selectable.FindSelectableOnUp"/>
/// </summary>
public override Selectable FindSelectableOnUp()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Vertical)
return null;
return base.FindSelectableOnUp();
}
/// <summary>
/// See <see cref="Selectable.FindSelectableOnDown"/>
/// </summary>
public override Selectable FindSelectableOnDown()
{
if (navigation.mode == Navigation.Mode.Automatic && axis == Axis.Vertical)
return null;
return base.FindSelectableOnDown();
}
public virtual void OnInitializePotentialDrag(PointerEventData eventData)
{
eventData.useDragThreshold = false;
}
#if UNITY_EDITOR
[MenuItem("GameObject/UI (Canvas)/ShaderGraph Samples/Slider", false, 30)]
static void CreateToggleGameObject(MenuCommand command)
{
GameObject go = ObjectFactory.CreateGameObject("Slider", new Type[] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(RectTransformSize), typeof(CustomSlider) });
StageUtility.PlaceGameObjectInCurrentStage(go);
go.GetComponent<CustomSlider>().AssignDefaultMaterial();
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
GameObject contextObject = command.context as GameObject;
if (contextObject != null)
{
GameObjectUtility.SetParentAndAlign(go, contextObject);
Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name);
}
Selection.activeGameObject = go;
}
#endif
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: fb201a23cacc2a7479c31ac9c37407c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- m_TargetGraphic: {instanceID: 0}
- defaultMaterial: {fileID: -876546973899608171, guid: de30334590ae15848ad2c227d0913253, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,152 @@
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// A custom version of <see cref="Toggle"/> implementing <see cref="IMaterialModifier"/> to update the <see cref="Graphic.material"/> when
/// <see cref="Selectable.DoStateTransition(Selectable.SelectionState, bool)"/> is called, or when
/// <see cref="Toggle.isOn"/> changes.
/// <para>Implemented as a variant of <see cref="Toggle"/> to make it work nicely with <see cref="ToggleGroup"/>.</para>
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/Toggle")]
[RequireComponent(typeof(Graphic))]
public class CustomToggle : Toggle, IMaterialModifier
{
public UnityEvent<int> onStateChanged;
private static readonly string _isOnPropertyName = "_isOn", _statePropertyName = "_State";
private Material _material;
private int? _isOnPropertyId;
private int IsOnPropertyId
{
get
{
if (!_isOnPropertyId.HasValue)
_isOnPropertyId = Shader.PropertyToID(_isOnPropertyName);
return _isOnPropertyId.Value;
}
}
private int? _statePropertyId;
private int StatePropertyId
{
get
{
if (!_statePropertyId.HasValue)
_statePropertyId = Shader.PropertyToID(_statePropertyName);
return _statePropertyId.Value;
}
}
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
protected override void Awake()
{
base.Awake();
onValueChanged.AddListener((x) => UpdateMaterial());
}
#if UNITY_EDITOR
[SerializeField, HideInInspector] Material defaultMaterial;
protected internal void AssignDefaultMaterial()
{
if (defaultMaterial != null)
Graphic.material = defaultMaterial;
}
protected override void Reset()
{
base.Reset();
// we don't need a transition by default
transition = Transition.None;
}
protected override void OnValidate()
{
//base.OnValidate(); // not calling base not to trigger DoStateTransition()
if (!PrefabUtility.IsPartOfPrefabAsset(this) && !Application.isPlaying)
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
UpdateMaterial();
}
#endif
public void UpdateMaterial()
{
Graphic.SetMaterialDirty();
}
protected override void DoStateTransition(SelectionState state, bool instant)
{
base.DoStateTransition(state, instant);
onStateChanged?.Invoke((int)state);
UpdateMaterial();
}
public virtual Material GetModifiedMaterial(Material baseMaterial)
{
_material ??= new(baseMaterial);
_material.CopyPropertiesFromMaterial(baseMaterial);
if (_material.HasFloat(StatePropertyId))
_material.SetFloat(StatePropertyId, (int)currentSelectionState);
if (_material.HasFloat(IsOnPropertyId))
_material.SetFloat(IsOnPropertyId, isOn ? 1 : 0);
return _material;
}
public override void OnPointerClick(PointerEventData eventData)
{
base.OnPointerClick(eventData);
UpdateMaterial();
}
public override void OnSubmit(BaseEventData eventData)
{
base.OnSubmit(eventData);
UpdateMaterial();
}
#if UNITY_EDITOR
[MenuItem("GameObject/UI (Canvas)/ShaderGraph Samples/Toggle", false, 30)]
static void CreateToggleGameObject(MenuCommand command)
{
GameObject go = ObjectFactory.CreateGameObject("SG Toggle", new Type[] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(CustomToggle) });
StageUtility.PlaceGameObjectInCurrentStage(go);
go.GetComponent<CustomToggle>().AssignDefaultMaterial();
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
GameObject contextObject = command.context as GameObject;
if (contextObject != null)
{
GameObjectUtility.SetParentAndAlign(go, contextObject);
Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name);
}
Selection.activeGameObject = go;
}
#endif
}
}
@@ -0,0 +1,15 @@
fileFormatVersion: 2
guid: 09b396209d787044689d4233300d5339
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- m_TargetGraphic: {instanceID: 0}
- graphic: {instanceID: 0}
- m_Group: {instanceID: 0}
- defaultMaterial: {fileID: -876546973899608171, guid: 5f95e685c3fcab34cbb2e790a728ed03, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,40 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Unity.UI.Shaders.Sample
{
/// <summary>
///
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/Graphic Color")]
[RequireComponent(typeof(Graphic))]
public class GraphicColor : UIBehaviour
{
[SerializeField] Color _normal = Color.white, _highlighted = Color.white, _pressed = Color.white, _selected = Color.white, _disabled = Color.gray;
Graphic _graphic;
Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
public void SetColor(int state)
{
Graphic.color = state switch
{
0 => _normal,
1 => _highlighted,
2 => _pressed,
3 => _selected,
4 => _disabled,
_ => _normal,
};
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7648e529c37fa1f409b74db6c6bbdbb2
@@ -0,0 +1,131 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// A simple Meter.
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/Meter")]
[RequireComponent(typeof(Graphic))]
[DisallowMultipleComponent]
public class Meter : UIBehaviour, IMaterialModifier
{
[SerializeField, Range(0f, 1f)] private float _value = 0.5f;
private static readonly string _sliderValuePropertyName = "_MeterValue";
protected Material _material;
private int? _meterValuePropertyId;
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
public float Value
{
get => _value;
set
{
_value = value;
Graphic.SetMaterialDirty();
}
}
protected int MeterValuePropertyId
{
get
{
if (!_meterValuePropertyId.HasValue)
_meterValuePropertyId = Shader.PropertyToID(_sliderValuePropertyName);
return _meterValuePropertyId.Value;
}
}
#if UNITY_EDITOR
[SerializeField, HideInInspector] Material defaultMaterial;
protected internal void AssignDefaultMaterial()
{
if (defaultMaterial != null)
Graphic.material = defaultMaterial;
}
protected override void Reset()
{
base.Reset();
Value = _value;
}
protected override void OnValidate()
{
base.OnValidate();
//Graphic.SetMaterialDirty(); // this makes the Editor hick up when changing the value
// So instead, we just change the material, but if another IMaterialModifier was added after this,
// this will have no visible effect.
if (_material != null && _material.HasFloat(MeterValuePropertyId))
_material.SetFloat(MeterValuePropertyId, Value);
}
#endif
protected override void Start()
{
base.Start();
Value = _value;
}
protected override void OnDidApplyAnimationProperties()
{
base.OnDidApplyAnimationProperties();
Value = _value;
}
public virtual Material GetModifiedMaterial(Material baseMaterial)
{
_material ??= new(baseMaterial);
_material.CopyPropertiesFromMaterial(baseMaterial);
if (_material.HasFloat(MeterValuePropertyId))
_material.SetFloat(MeterValuePropertyId, Value);
return _material;
}
#if UNITY_EDITOR
[MenuItem("GameObject/UI (Canvas)/ShaderGraph Samples/Meter", false, 30)]
static void CreateToggleGameObject(MenuCommand command)
{
GameObject go = ObjectFactory.CreateGameObject("Meter", new System.Type[] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(RectTransformSize), typeof(Meter) });
StageUtility.PlaceGameObjectInCurrentStage(go);
go.GetComponent<Meter>().AssignDefaultMaterial();
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
GameObject contextObject = command.context as GameObject;
if (contextObject != null)
{
GameObjectUtility.SetParentAndAlign(go, contextObject);
Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name);
}
Selection.activeGameObject = go;
}
#endif
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ea0e4892b6614c84bb5a0598a1e20167
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- defaultMaterial: {fileID: -876546973899608171, guid: 384567c6b4021a441a3ee7156745b2e6, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,160 @@
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
#endif
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// A simple ProgressBar.
/// <para>Becomes interactable when associated with a <see cref="CustomSlider"/></para>
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/Range Bar")]
[RequireComponent(typeof(Graphic))]
[DisallowMultipleComponent]
public class RangeBar : UIBehaviour, IMaterialModifier
{
public enum Direction { LeftToRight, RightToLeft, BottomToTop, TopToBottom }
public struct Range
{
public float min, max;
}
static Vector2 FromDirection(Direction direction) => direction switch
{
Direction.LeftToRight => Vector2.right,
Direction.RightToLeft => Vector2.left,
Direction.BottomToTop => Vector2.up,
Direction.TopToBottom => Vector2.down,
_ => Vector2.zero
};
[SerializeField, MinMaxSlider(0f, 1f)] private Vector2 _value = Vector2.up;
[SerializeField] Direction _direction;
private static readonly string _rangeBarValuePropertyName = "_RangeBarValue";
protected Material _material;
private int? _rangeBarValuePropertyId;
public Direction direction => _direction;
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
public Vector2 Value
{
get => _value;
set
{
_value.x = Mathf.Clamp01(value.x);
_value.y = Mathf.Clamp01(value.y);
_value.y = _value.y > _value.x ? _value.y : _value.x;
Graphic.SetMaterialDirty();
}
}
public float Min { get => Value.x; set => Value = new Vector2(value, Value.y); }
public float Max { get => Value.y; set => Value = new Vector2(Value.x, value); }
Vector2 DirectionVector => FromDirection(direction);
Vector4 Vector => new Vector4(Value.x, Value.y, DirectionVector.x, DirectionVector.y);
protected int RangeBarValuePropertyId
{
get
{
if (!_rangeBarValuePropertyId.HasValue)
_rangeBarValuePropertyId = Shader.PropertyToID(_rangeBarValuePropertyName);
return _rangeBarValuePropertyId.Value;
}
}
#if UNITY_EDITOR
[SerializeField, HideInInspector] Material defaultMaterial;
protected internal void AssignDefaultMaterial()
{
if (defaultMaterial != null)
Graphic.material = defaultMaterial;
}
protected override void Reset()
{
base.Reset();
Value = _value;
}
protected override void OnValidate()
{
base.OnValidate();
//Graphic.SetMaterialDirty(); // this makes the Editor hick up when changing the value
// So instead, we just change the material, but if another IMaterialModifier was added after this,
// this will have no visible effect.
if (_material != null && _material.HasVector(RangeBarValuePropertyId))
_material.SetVector(RangeBarValuePropertyId, Vector);
}
#endif
protected override void Start()
{
base.Start();
Value = _value;
}
protected override void OnDidApplyAnimationProperties()
{
base.OnDidApplyAnimationProperties();
Value = _value;
}
public virtual Material GetModifiedMaterial(Material baseMaterial)
{
_material ??= new(baseMaterial);
_material.CopyPropertiesFromMaterial(baseMaterial);
if (_material.HasVector(RangeBarValuePropertyId))
_material.SetVector(RangeBarValuePropertyId, Vector);
return _material;
}
#if UNITY_EDITOR
[MenuItem("GameObject/UI (Canvas)/ShaderGraph Samples/Range Bar", false, 30)]
static void CreateToggleGameObject(MenuCommand command)
{
GameObject go = ObjectFactory.CreateGameObject("Range Bar", new System.Type[] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(RectTransformSize), typeof(RangeBar) });
StageUtility.PlaceGameObjectInCurrentStage(go);
go.GetComponent<RangeBar>().AssignDefaultMaterial();
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
GameObject contextObject = command.context as GameObject;
if (contextObject != null)
{
GameObjectUtility.SetParentAndAlign(go, contextObject);
Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name);
}
Selection.activeGameObject = go;
}
#endif
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 33236b32a07827145b40a42b9033672e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences:
- defaultMaterial: {fileID: -876546973899608171, guid: 671c5a7d7c5e6bc40bbae6edd1955c32, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,126 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace Unity.UI.Shaders.Sample
{
/// <summary>
/// Sets the UI Material's Property to the <see cref="UnityEngine.RectTransform"/>'s screen size.
/// </summary>
[AddComponentMenu("UI (Canvas)/ShaderGraph Samples/RectTransform Size")]
[ExecuteAlways]
[RequireComponent(typeof(RectTransform), typeof(Graphic))]
[DisallowMultipleComponent]
public class RectTransformSize : UIBehaviour, IMaterialModifier
{
private static readonly string _propertyName = "_RectTransformInfo";
Material _material;
private RectTransform _rectTransform;
private RectTransform RectTransform
{
get
{
_rectTransform = _rectTransform != null ? _rectTransform : GetComponent<RectTransform>();
return _rectTransform;
}
}
private Canvas _rootCanvas;
private Canvas RootCanvas
{
get
{
if (_rootCanvas == null)
_rootCanvas = GetComponentInParent<Canvas>()?.rootCanvas;
return _rootCanvas;
}
}
private Graphic _graphic;
public Graphic Graphic
{
get
{
if (_graphic == null)
_graphic = GetComponent<Graphic>();
return _graphic;
}
}
int? _propertyId;
int PropertyId
{
get
{
if (!_propertyId.HasValue)
_propertyId = Shader.PropertyToID(_propertyName);
return _propertyId.Value;
}
}
private Vector2 RectSize => RectTransformUtility.PixelAdjustRect(RectTransform, RootCanvas).size;
private Vector4 RectTransformInfo
{
get
{
Vector4 rectTransformInfo = RectSize;
rectTransformInfo.z = RootCanvas.scaleFactor;
rectTransformInfo.w = RootCanvas.referencePixelsPerUnit;
return rectTransformInfo;
}
}
protected override void Start()
{
base.Start();
UpdateMaterial();
}
#if UNITY_EDITOR
protected override void Reset()
{
base.Reset();
UpdateMaterial();
}
protected override void OnValidate()
{
base.OnValidate();
UpdateMaterial();
}
#endif
protected override void OnDidApplyAnimationProperties()
{
base.OnDidApplyAnimationProperties();
UpdateMaterial();
}
protected override void OnRectTransformDimensionsChange()
{
base.OnRectTransformDimensionsChange();
UpdateMaterial();
}
[ContextMenu("Update Material")]
public void UpdateMaterial()
{
Graphic.SetMaterialDirty();
}
public Material GetModifiedMaterial(Material baseMaterial)
{
_material ??= new(baseMaterial);
_material.CopyPropertiesFromMaterial(baseMaterial);
if (_material.HasVector(PropertyId))
_material.SetVector(PropertyId, RectTransformInfo);
return _material;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a0fdf6750a7499e4faef09a8cc8ddfde
@@ -0,0 +1,25 @@
{
"name": "Unity.UI.Shaders.Sample",
"rootNamespace": "Unity.UI.Shaders.Sample",
"references": [
"GUID:2bafac87e7f4b9b418d9448d219b01ab",
"GUID:6055be8ebefd69e48b49212b09b47b2f"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [
"UGUI"
],
"versionDefines": [
{
"name": "com.unity.ugui",
"expression": "",
"define": "UGUI"
}
],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: b3f345a8790ef4c419a5d3ea60e9f97d
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,41 @@
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// A simple Timer to demonstrate Progress Bars
/// </summary>
public class Timer : MonoBehaviour
{
[SerializeField] float timerMin = 3f, timerMax = 10f;
float timer = 10f;
[SerializeField] bool randomStart;
public UnityEvent<float> timerEvent;
float _time = 0;
public float TheTime
{
get => _time;
set
{
_time = value;
if (_time > 1f)
_time = 0;
timerEvent?.Invoke(_time);
}
}
private void Start()
{
timer = Random.Range(timerMin, timerMax);
if (randomStart)
TheTime = Random.Range(0f, 1f);
}
private void Update()
{
TheTime += Time.deltaTime / timer;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 79b50977186a90a47b494f47e1537ca5