I have a monobehaviour script. I attempt to add it to a gamobject and I get this dialogue
Can’t add script component ‘MyScript’ because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
The usual issue is that the filename and classname do not match or there are compiler errors. This is not the case. I’ve diagnosed the issue as being related to the namespace. For whatever reason if the class is inside a namespace unity will not be able to find it.
I’ve tried renaming the namespace but that did not work. It seems to be just namespaces in general. This issue seems to be with just this class as well. I just finished a big refactor of my project and other monobehaviours attached to gameobjects are working fine.
Any clue as to why this is happening? How exactly does unity find classes?
The issue was that I had a static using in my class file. For whatever reason a MonoBehaviour can’t be attached to a GameObject if it has a static using.
I was trying to reference an enum from a static class. To shorten the syntax I just put a static using at the top. But that’s a no no apparently.
So instead of this at the top:
using static YourNamespace.Constants;
You can do this whenever you want to talk about your enum:
YourNamespace.Constants.YourEnum
I’ll leave this up in case someone else runs into this if das coo
I’ve had the same problem but with no static. but did have many classes in the same file.
Possibly unity cannot find the correct class, maybe associated with being inside namespaces.
solution was to separate mono classes out into separate files. so there is only one class that definitely matches the filename… no ambiguities.
Note:- once broken… it stayed broken until deleting the project files in the root (above assets/) and the library folder, and re-importing everything.