1+ #if ODIN_INSPECTOR
2+ using Sirenix . OdinInspector ;
3+ #endif
14#if UNITY_EDITOR
25using UnityEditor ;
36#endif
47using UnityEngine ;
58
69namespace ToolBox . Tags
710{
8- [ DisallowMultipleComponent , DefaultExecutionOrder ( - 150 ) ]
11+ [ DisallowMultipleComponent , DefaultExecutionOrder ( - 9000 ) , ExecuteInEditMode ]
912 public sealed class Taggable : MonoBehaviour
1013 {
14+ #if ODIN_INSPECTOR
15+ [ Required , AssetList ]
16+ #endif
1117 [ SerializeField ] private Tag [ ] _tags = default ;
1218
13- private Tag [ ] _all = null ;
19+ private static Tag [ ] _all = null ;
1420 private int _hash = 0 ;
1521
1622 private void Awake ( )
1723 {
1824#if UNITY_EDITOR
19- _all = Resources . FindObjectsOfTypeAll < Tag > ( ) ;
20-
21- if ( _tags == null )
22- _tags = new Tag [ 0 ] ;
25+ SetupEditorData ( ) ;
2326#endif
2427
2528 _hash = gameObject . GetHashCode ( ) ;
26-
27- for ( int i = 0 ; i < _tags . Length ; i ++ )
28- _tags [ i ] . Add ( _hash ) ;
29+ AddAll ( ) ;
2930 }
3031
31- private void OnEnable ( )
32+ private void OnDestroy ( ) =>
33+ RemoveAll ( ) ;
34+
35+ private void AddAll ( )
3236 {
3337 for ( int i = 0 ; i < _tags . Length ; i ++ )
3438 _tags [ i ] . Add ( _hash ) ;
3539 }
3640
37- private void OnDisable ( )
41+ private void RemoveAll ( )
3842 {
3943 for ( int i = 0 ; i < _tags . Length ; i ++ )
4044 _tags [ i ] . Remove ( _hash ) ;
4145 }
4246
4347#if UNITY_EDITOR
44- public void Add ( Tag tag )
48+ public void AddTagInEditor ( Tag tag )
4549 {
4650 if ( ! ArrayUtility . Contains ( _tags , tag ) )
4751 ArrayUtility . Add ( ref _tags , tag ) ;
4852 }
4953
50- public void Remove ( Tag tag )
54+ public void RemoveTagInEditor ( Tag tag )
5155 {
5256 if ( ArrayUtility . Contains ( _tags , tag ) )
5357 ArrayUtility . Remove ( ref _tags , tag ) ;
5458 }
5559
60+ // Handle Inspector Changes
5661 private void OnValidate ( )
5762 {
58- if ( ! Application . isPlaying || _all == null )
59- return ;
60-
63+ SetupEditorData ( ) ;
6164 var obj = gameObject ;
65+ AddAll ( ) ;
6266
63- foreach ( var tag in _all )
67+ for ( int i = 0 ; i < _all . Length ; i ++ )
6468 {
69+ var tag = _all [ i ] ;
70+
6571 if ( ArrayUtility . Contains ( _tags , tag ) )
6672 {
6773 if ( ! obj . HasTag ( tag ) )
@@ -74,6 +80,18 @@ private void OnValidate()
7480 }
7581 }
7682 }
83+
84+ private void SetupEditorData ( )
85+ {
86+ if ( _all == null )
87+ _all = Resources . FindObjectsOfTypeAll < Tag > ( ) ;
88+
89+ if ( _tags == null )
90+ _tags = new Tag [ 0 ] ;
91+
92+ if ( _hash == 0 )
93+ _hash = gameObject . GetHashCode ( ) ;
94+ }
7795#endif
7896 }
7997}
0 commit comments