'Run event when GameObject scale changes in Unity3D

I want to trigger an event when the scale of a GameObject changes. I didn't find anything about this online. Maybe someone can help me out here.



Solution 1:[1]

There isn't really something built-in.

You can either poll check like e.g.

private Vector3 _currentLocalScale;
public delegate void ScaledChangedDelegate(Vector3 from, Vector3 to);
public event ScaledChangedDelegate ScaleChanged;

private void Update()
{
    var newLocalScale = transform.localScale;

    // Depending on you required precision
    // Vector3 == has a precision of 0.00001
    if(_currentLocalScale != newLocalScale)
    // If for some reason you need it more exact
    //if(Vector3.Distance(_currentLocalScale, newLocalScale) <= Mathf.Epsilon)
    {
        ScaledChangedDelegate?.Invoke(_currentLocalScale, newLocalScale );

        _currentLocalScale = newLocalScale ;
    }
}

The alternatives - for the freeks ;)

  • use the TransformSetterInterceptor which is quite hack and overwrites the way how Transform is compiled and injects callback events for all the property setters.

  • use MissingUnityEvents which more or less does the same but even more flexible by basically adding some generic callbacks for the property changes. It can simply be imported as a Package and allows you to generate such weaved-in callbacks for any type and property you like.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1