- Home /
Cannot drag and assign other class to prefab
Hi, I am new to Unity, so it might be a newbie question, but I could not find the answer on the web.
I have a prefab in my game, ready to collide with the main game object. What I'm trying to do here is that, I have a HUDLayer including the scores, and I have assigned the HUDClass in the prefab script so I could update the scores in the HUD
public HUDClass hud;
With this, in the inspector, it shows that there's an option to drag and drop the gameObject/script of the HUDClass as a reference to the prefab. But it doesn't allow me to do that, why is that?
Is there any way to do this?
Thank you.
Answer by OperationDogBird · Jul 09, 2012 at 07:51 AM
The reason, as i believe, is because the class has not been created yet...mono behavior classes are created(Instantiated) in editor for purposes of drag/drop..etc. Editor and Runtime are 2 completely different realms, and it wouldnt make sense to make a runtime class available in the editor unless there is a reason..thus: extends MonoBehaviour
this should clear up your problems:
1)Class should be instantiated: var myClass=new MyClass();
2)Class should be same: 'name' == 'script name' : var myClass:MyClass=new MyClass();
Thank you for the reply. I understand the problem now. When I try your instruction to instantiate the class in C#, it works, but a warning shows up saying "You are trying to create a $$anonymous$$onoBehaviour using the 'new' keyword. This is not allowed." Why is this?
And I don't quite understand the 2nd bullet point about "the class should be the same". How should it be in C#?
Thanks again.
If it'S a monobehaviour you can't create an instance with new. You just drag your script onto a gameobject to create an instance. This instance (or the gameobject itself) can be dragged onto such a variable to assign the instance reference to the variable.
Second, the script name only have to match the class name when the class is derived from $$anonymous$$onoBehaviour ot ScriptableObject (I talk about runtime classes, the same rule is valid for editor classes like EditorWindow ...).
Again, you can't assign a class to a reference variable. A "class" is like a blueprint. With it you can create actual instances of that class. In case of Components ($$anonymous$$onoBehaviour) you have to attach it to a gameobject, either by drag&drop or via AddComponent
Your answer
Follow this Question
Related Questions
Variable not Assigned 1 Answer
Assign Transform from Hierarchy to Prefab script 1 Answer
Accessing a game object from a script? 1 Answer
making prefabs at runtime? 2 Answers
How to apply a texture to a prefab? 2 Answers