You’re attempting to initialize a constant with a variable. That won’t work, for obvious reasons.
You MAY initialize a variable with a constant if you like.
Beware about wantonly splattering initialization code all over your fields. Here’s why:
Serialized / public fields in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:
-
what the class constructor makes (either default(T) or else field initializers, eg “what’s in your code”)
-
what may be saved with the prefab
-
what may be saved with the prefab override(s)/variant(s)
-
what may be saved in the scene and not applied to the prefab
-
what may be changed in the scene and not yet saved to disk
-
what may be changed in OnEnable(), Awake(), Start(), or even later
Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.
Here’s the official discussion: Serialization in Unity
If you must initialize fields, then do so in the void Reset()
method, which ONLY runs in the UnityEditor.
Field initializers versus using Reset() function and Unity serialization:
To avoid complexity in your prefabs / scenes, I recommend NEVER using the FormerlySerializedAsAttribute
And in all cases…
You can fix your own typing mistakes. Here’s how:
Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.
The complete error message contains everything you need to know to fix the error yourself.
The important parts of the error message are:
- the description of the error itself (google this; you are NEVER the first one!)
- the file it occurred in (critical!)
- the line number and character position (the two numbers in parentheses)
- also possibly useful is the stack trace (all the lines of text in the lower console window)
Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.
Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!
All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.