Skip to content

Instantly share code, notes, and snippets.

@spajus
Last active April 30, 2020 19:51
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 spajus/21f0a1556cd4b74d752f89a25af78209 to your computer and use it in GitHub Desktop.
Save spajus/21f0a1556cd4b74d752f89a25af78209 to your computer and use it in GitHub Desktop.
A component that tracks other Unity GameObject components, and reports when and what exactly is missing
using UnityEngine;
namespace KL.Utils.Behaviours {
[DefaultExecutionOrder(int.MinValue)]
[ExecuteInEditMode]
public class GameObjectMetadata : MonoBehaviour {
[SerializeField] private string[] components;
private void Start() {
#if !UNITY_EDITOR
Destroy(this);
#endif
}
#if UNITY_EDITOR
void Update() {
if (!UnityEditor.EditorApplication.isPlaying) {
var comps = gameObject.GetComponents<Component>();
if (!HasMissingComponents(comps)) {
UpdateKnownComponents(comps);
}
}
}
#endif
private bool HasMissingComponents(Component[] comps) {
for (int i = 0; i < comps.Length; i++) {
if (comps[i] == null) {
Debug.LogErrorFormat(gameObject,
"Missing component {0} on game object {1}", components[i], name);
return true;
}
}
return false;
}
private void UpdateKnownComponents(Component[] comps) {
components = new string[comps.Length];
for (int i = 0; i < comps.Length; i++) {
var ct = comps[i].GetType().ToString();
Dbg.LogF("Setting component: {0}: {1}", i, ct);
components[i] = ct;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment