Hi!
I have a reference to a GameObject, which I defined by draging a prefab to the reference in Unity.
Now I want to access a component from the prefab. Is it possible without instantiating it?
If not, what other solutions do I have?
Thanks !
Hi!
I have a reference to a GameObject, which I defined by draging a prefab to the reference in Unity.
Now I want to access a component from the prefab. Is it possible without instantiating it?
If not, what other solutions do I have?
Thanks !
A way to do this is by creating an itemhandler class that deals with that. You can do that by creating an empty game object that holds those scripts and you refer to this itemhandler when you need to access a prefab script. Your prefabs themselves would then only include references to that itemhandler, even when they are instantiated.
You can call GetComponent on prefab references just fine. The components won’t have had their awake/start/whatever methods called on them, but they do have all their data.
Note that if you change the component, that will change the file on disk in editor, and do strange things in builds, so you should not do that unless you really know what you’re doing.
Is this the case at runtime as well or just in the editor?
For the GetComponent part, yes.
For doing things like AddComponent, yes, but with a big caveat; the changes won’t persist. So if you close the game, or even unload the prefab while the game is running by losing all references to it, it’ll get reloaded as it was.
It’ll also be super annoying to deal with since the prefab will be changed on disk all the time.