Skip to content

Instantly share code, notes, and snippets.

@Arakade
Created April 23, 2020 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arakade/9ae21a4fb39efe48db73bb60eec43656 to your computer and use it in GitHub Desktop.
Save Arakade/9ae21a4fb39efe48db73bb60eec43656 to your computer and use it in GitHub Desktop.
Log and provide a UnityEvent for when `Rigidbody.IsSleeping` changes.
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Events;
namespace UGS.unityutils {
/// <summary>
/// Log and provide a UnityEvent for when `Rigidbody.IsSleeping` changes.
/// </summary>
public sealed class SleepHelper : MonoBehaviour {
#if UNITY_EDITOR
[SerializeField]
private Rigidbody rb = null;
public void OnValidate() {
if (null == rb) {
Undo.RecordObject(this, "Set RB");
rb = GetComponent<Rigidbody>();
}
Assert.IsNotNull(rb, $"{name} has no rb");
}
public void OnEnable() {
lastSleeping = rb.IsSleeping();
}
public void FixedUpdate() {
var newSleeping = rb.IsSleeping();
if (newSleeping != lastSleeping) {
Debug.Log($"{Time.frameCount}: {name}.sleeping:{lastSleeping}->{newSleeping}", this);
lastSleeping = newSleeping;
SleepingChanged.Invoke(newSleeping);
}
}
[Tooltip("Invoked with the new status")]
public UnityBoolEvent SleepingChanged;
[Serializable]
public sealed class UnityBoolEvent : UnityEvent<bool> {}
private bool lastSleeping;
#endif // UNITY_EDITOR
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment