Created
April 23, 2020 13:03
-
-
Save Arakade/9ae21a4fb39efe48db73bb60eec43656 to your computer and use it in GitHub Desktop.
Log and provide a UnityEvent for when `Rigidbody.IsSleeping` changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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