- Home /
Assagning prefab with component to component
Hi,
While adding Prefabs to public variables in editor I've became confused.
Let me describe: On the scene I have GameObject Manager which has public variable of type MyComponentScript.
I have created prefab MyComponentScriptPrefab which consists of Transfrom , BoxCollider, MyComponentScript components. This prefab is placed in Resources folder.
Now, why I'm allowed to drag & drop this prefab MyComponentScriptPrefab into public variable field MyComponentScript ? (MyComponentScriptPrefab is GameObject type, not MyComponentScript).
If I try something similar in code, e.g.
MyComponentScript script = Resources.Load("MyComponentScriptPrefab") as MyComponentScript;
I'm getting NullReference error (however this mimics above behavior in editor).
The working code is:
MyComponentScript script = (Resources.Load("MyComponentScriptPrefab") as GameObject).GetComponent<MyComponentScript>();
I don't understand, why editor allows assigning prefabs (GameObjects) to other (MonoBehavior derivative) types.
Your answer
![](https://koobas.hobune.stream/wayback/20220612075250im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
can I update prefab Assets with new 3D files without resetting their components? 2 Answers
How to add components to all spawned prefabs ? 0 Answers
Animated character FBX workflow question 1 Answer
how do I assign a prefab's child to another prefab's script's public variable? 1 Answer
can you access a script in a prefab and change its value 1 Answer