0
\$\begingroup\$

I have a RawImage and an AspectRatioFitter attached to it so I want to change the aspect ratio to fit the image in the texture field of the raw image.
But I need to avoid checking for it in the update as much as possible.
Is there an event for when the texture of a RawImage element has changed? Something like OnTextureChanged().

\$\endgroup\$
1
\$\begingroup\$

I would create a script responsible for changing the Texture instead of calling rawImage.texture. You will be able to raise an event when the texture changes thanks to this.

using UnityEngine;
using UnityEngine.UI;

[System.Serializable]
public class FloatEvent : UnityEngine.Events.UnityEvent<float> { };

public class RawImageManager : MonoBehaviour
{
    // Drag & Drop the RawImage component
    [SerializeField]
    private RawImage target ;

    // Select the `AspectRatio` component and the `aspectRatio` dynamic variable
    [SerializeField]
    private FloatEvent onAspectRatioChanged ;

    public Texture Texture
    {
        get { return target.texture ; }
        set
        {
             target.texture = value ;
            if( onAspectRatioChanged != null )
                onAspectRatioChanged.Invoke( value.width / value.height ) ;
        }
    }    
}

And then, call GetComponent<RawImageManager>().Texture = texture ; instead of GetComponent<RawImage>().texture = texture ;

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.