简体   繁体   中英

Trigger a function when array values are changed

I am adding a set of array values through inspector window. I am trying to achieve to trigger a function, when I change my array values. That is, my script should check if the new values are not equal to old values and then call this function. I do not want to use Update as it will take more memory and processing power, so what could be the alternative?


public class SetValues : MonoBehaviour {

    [Serializable]
    public struct SetValues
    {
        public float Position;
        public float Value;
    }
 
    public SetValues[] setValues;


    void Function_ValuesChanged()
    {
        Debug.Log("The Value is changed");
        //Do Something
    }

}

Try MonoBehavior.OnValidate()

Example:

public class SetValues : MonoBehaviour {

[Serializable]
public struct SetValues
{
    public float Position;
    public float Value;
}

public SetValues[] setValues;


void OnValidate()
{
    Debug.Log("The Value is changed");
    //Do Something
}

}

If something happens in game and you want to notify other scripts use events. Events are lightweight and easy to implement.

In class that contain array, create property and change array value, only from property. Never directly interact with array field.

// Create Event Arguments
    public class OnArrayValueChangedEventArgs : EventArgs
    {
        public float Position;
        public float Value;
    }
    // Crate Event
    public event EventHandler<OnArrayValueChangedEventArgs> OnArrayValueChanged;
    
    Array[] myArray;
    // Change Array value only from this property, so when you change value, event will be called
    public Array[] MyArray
    {
        get { return myArray; }
        set { myArray = value; OnArrayValueChangedEvent(this, new OnArrayValueChangedEventArgs() { Position = myArray.Position, Value = myArray.Value };}
    }

From second class you should just subscribe to this event and do the thing. I will call this event from my GameManager Singleton class.

private void Awake()
{
    GameManager.Instance.OnArrayValueChanged += Instance_OnArrayValueChanged;
}

private void Instance_OnArrayValueChanged(object sender, GameManager.OnArrayValueChangedEventArgs e)
{
    // Do the thing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM