Binding to Intervals
As a convenience, you can bind an action to get called periodically on Update, FixedUpdate, EndOfFrame or a custom time interval:
Tip
This sample is in the Bindables Package at: Samples/Scenes/07_Intervals
#if UNITY_UI
using TMPro;
using UnityEngine;
namespace Bindables.Samples
{
public class Example_Intervals : MonoBehaviour
{
[SerializeField]
private RectTransform _mouseFollower;
[SerializeField]
private TextMeshProUGUI _timeText;
[SerializeField]
private Rigidbody _rigidBody;
void Start()
{
// Bind a callback to capture mousePosition as a Bindable every frame, so we can use it for bindings.
var mousePosition = new Bindable<Vector3>();
#if UNITY_INPUT_SYSTEM
this.BindUpdate(() => mousePosition.Value = UnityEngine.InputSystem.Mouse.current.position.ReadValue());
#else
this.BindUpdate(() => mousePosition.Value = Input.mousePosition);
#endif
_mouseFollower.BindPosition(mousePosition);
// Update the current time every second.
this.BindInterval(1f, () => _timeText.text = System.DateTime.Now.ToLongTimeString());
// You should make physics updates in FixedUpdate.
this.BindFixedUpdate(() =>
{
var towardsMouse = mousePosition.Value - _rigidBody.transform.position;
_rigidBody.AddForce(towardsMouse * 2);
});
// Sometimes you need to make sure an update happens at the end of the frame.
this.BindEndOfFrame(() => _rigidBody.transform.Rotate(new Vector3(0, 0, 1)));
}
}
}
#endif
Unlike regular Update loop, these will get called as long as this is not destroyed, even if it is enabled.
If you only want these to get called when enabled, or based on some other criteria, use a custom BindContext. See BindContext.