5

I have made an attribute that automatically assigns value to a variable at runtime as such:

    [Assign(AssignmentTime.Awake)]
    private Rigidbody _rigidBody;

However, compiler gives out a warning, understandably, that this value is never assigned and will always be null. Is there a way to make the attribute disable the warning automatically? I don't really want to write that warning suppression #pragma every time I want to use that attribute.

2 Answers2

3

To be explicit: no, you cannot suppress a warning via a custom attribute. You can use:

  • [SuppressMessage(...)] in addition to your attribute
  • #pragma warning {disable|enable} {codes}

Both of which are available via the warning's popup in the IDE

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

You can assign a default value, like null. That will make the warning disappear. Your assignment and also inspector assignments will overwrite the default value later on.

[Assign(AssignmentTime.Awake)]
private Rigidbody _rigidBody = null;
aalmigthy
  • 1,261
  • 8
  • 19
  • I can't believe this is actually working. It still underlines it in IDE but Unity no longer shows it as a warning. Not ideal, but will do. Thanks! – Arseni Natapov Apr 18 '20 at 14:30
  • Yes, the warning is either in the ide or the unity console. i prefer the unity console to be as free as possible. – aalmigthy Apr 18 '20 at 15:26
  • Explicitly assigning null now causes a different warning: CS0649: Field 'field' is never assigned to, and will always have its default value 'value' – DoomGoober Oct 18 '22 at 02:24