IComponentModifiedCallbackReceiver

  06. Attributes No Comments

Interface for attributes that can be added to component classes to receive callbacks when components of a certain type are added or modified through the inspector.

OnComponentAdded is called whenever a new component of type TComponent is added to the GameObject that contains the component with this attribute.

OnComponentModified is called whenever an existing component of type TComponent is modified on the GameObject that contains the component with this attribute.

Interface Implementer

Attribute targeting a component class.

Example

using System;
using UnityEngine;

/// <summary>
/// When added before a component class causes the transform component to be locked to default state for all GameObjects that contain the component with this attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public sealed class LockTransformAttribute : Attribute, IComponentModifiedCallbackReceiver<Transform>
{
	/// <inheritdoc/>
	public void OnComponentAdded(Component attributeHolder, Transform addedComponent)
	{
		addedComponent.hideFlags = HideFlags.NotEditable;
		addedComponent.localPosition = Vector3.zero;
		addedComponent.localEulerAngles = Vector3.zero;
		addedComponent.localScale = Vector3.one;
	}

	/// <inheritdoc/>
	public void OnComponentModified(Component attributeHolder, Transform modifiedComponent)
	{
		if(modifiedComponent.localPosition != Vector3.zero || modifiedComponent.localEulerAngles != Vector3.zero || modifiedComponent.localScale != Vector3.one)
		{
			Debug.LogWarning(attributeHolder.GetType().Name + " requires that " + modifiedComponent.GetType().Name + " remains at default state.");

			modifiedComponent.localPosition = Vector3.zero;
			modifiedComponent.localEulerAngles = Vector3.zero;
			modifiedComponent.localScale = Vector3.one;
		}
	}
}