- Home /
LayerMask.NameToLayer is not allowed
This has been a really long project, I started out in unity 3 and upgraded through 4 and now 5. This is one of the most strange things that I have encountered so far. Basically when upgrading from Unity 4 to 5, they made it so that we shouldn't call functions like NameToLayer anywhere( which was perfectly fine in Unity 4), they restrict it to be only called in functions like Awake(), Start()...etc. Funny thing is, now I've removed every single call to LayerMask.NameToLayer in my entire project:
As you can see there are no references to the LayerMask.NameToLayer function at all in my project anymore. However, I'm still getting this every time I save a script and go back to the Unity Editor: NameToLayer is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'GameSingleton' on game object 'GameSingleton'. See "Script Serialization" page in the Unity Manual for further details. UnityEngine.LayerMask:GetMask(String[]) GameSingleton:.cctor()
You're looking in the wrong script file - the error says the problem is in GameSingleton, so please post the code for that..
Answer by Bunny83 · May 26, 2017 at 10:50 AM
LayerMask.NameToLayer
is also used internally by Unity. As you can see from the stacktrace it's actually called inside LayerMask.GetMask() which in turn got called from your GameSingleton constructor. So you have some code in the constructor of your GameSingleton class that is directly or indirectly using it.
// LayerMask.GetMask()
public static int GetMask(params string[] layerNames)
{
if (layerNames == null)
throw new ArgumentNullException("layerNames");
int num = 0;
for (int i = 0; i < layerNames.Length; i++)
{
string layerName = layerNames[i];
int num2 = LayerMask.NameToLayer(layerName);
if (num2 != -1)
num |= 1 << num2;
}
return num;
}
I remember removing every line of Get$$anonymous$$ask before, probably didn't do the same for NameToLayer that time, after removing Get$$anonymous$$ask/NameToLayer it seems that it is normal again. Thank you! Somehow I forgot how to read lol, maybe because it didn't give me the whole stack trace like normal exceptions and because of my experience in Unity 3 the shader compilor often threw very useless exception info(often wrong that wasted hours of my time) that my brain just chose to ignore it lol.
Your answer
Follow this Question
Related Questions
Object rotation snaps back to 0° 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Enemy Ai is not working as planned 0 Answers
How to Spawn after checking if the clones are destroyed. 1 Answer