4
\$\begingroup\$

It is a usual pattern when creating a new component, to load references to other components of the same GameObject. Here is an extreme case:

    [RequireComponent(typeof(Animator))]
    [RequireComponent(typeof(SpriteRenderer))]
    [RequireComponent(typeof(Stats))]
    [RequireComponent(typeof(Hunger))]
    [RequireComponent(typeof(Thirst))]
    [RequireComponent(typeof(Navigator))]
    [RequireComponent(typeof(LocationDevice))]
    [RequireComponent(typeof(AttacksManager))]
    [RequireComponent(typeof(ShieldEffect))]
    public class EnemyController : MonoBehaviour
    {
        Animator animator;
        SpriteRenderer spriteRenderer;
        Stats stats;
        Hunger hunger;
        Thirst thirst;
        Navigator navigator;
        LocationDevice locationDevice;
        AttacksManager attacksManager;
        ShieldEffect shieldEffect;


        void Awake()
        {
            animator = GetComponent<Animator>();
            spriteRenderer = GetComponent<SpriteRenderer>();
            stats = GetComponent<Stats>();
            hunger = GetComponent<Hunger>();
            thirst = GetComponent<Thirst>();
            navigator = GetComponent<Navigator>();
            locationDevice = GetComponent<LocationDevice>();
            attacksManager = GetComponent<AttacksManager>();
            shieldEffect = GetComponent<ShieldEffect>();
        }
    }

Is there a way to write this better?

\$\endgroup\$
  • 1
    \$\begingroup\$ Greetings, we don't review stub code on CodeReview, but actual code. Please place some actual code in your question. Otherwise this question will be put on hold pretty quickly. \$\endgroup\$ – konijn Nov 5 '19 at 17:55
  • \$\begingroup\$ @konijn Ok, corrected \$\endgroup\$ – Enrique Moreno Tent Nov 5 '19 at 17:58
  • \$\begingroup\$ Thanks! Also, sorry! I was not clear enough, this would not compile and still does not fit the guidelines, can you put the entire EnemyController class ? \$\endgroup\$ – konijn Nov 5 '19 at 18:06
  • \$\begingroup\$ Now it does compile. Notice that I am not really asking a review on the code itself, but on a pattern that repeats itself a lot in my daily routine \$\endgroup\$ – Enrique Moreno Tent Nov 5 '19 at 21:55
  • 1
    \$\begingroup\$ Got ya, thanks! It's a CodeReview community thing, I am looking forward to the review of this. \$\endgroup\$ – konijn Nov 5 '19 at 21:58

Browse other questions tagged or ask your own question.