Reputation: 2308
in my projects I often have multiple things I want to instantiate while playing, which are very similar and just differ in e.g. the sprite of the image-component.
My question is, whether it is better to
a) create many prefabs which are mostly the same and just differ in the image component vs.
b) create one prefab and Resources.Load() the needed sprite and set it to the image component of the instance of the prefab, or maybe even
c) create public references for the needed sprites and combine the "one prefab" approach but don't do Resources.Load().
For me, this is mostly interesting concerning image-components, but it would also be nice to know for other cases. Is there a clear answer to which option is better, or does it depend on the component and has maybe the one option better performance, while the other one saves more space?
Cheers.
Upvotes: 2
Views: 745
Reputation: 2970
Typically I think the best way to do this is to create a single prefab and then give it a public component or a script that can receive messages and change a private component to control the aspect you want to change. In the instance you describe, where you just want to change the image component, you can change that component when you instantiate the prefab.
The question becomes a design problem: would you rather change the property (in this case the image components) from the script that instantiated the game object from the prefab after you've instantiated it? Or send a message to a script on the prefab, which would then, reacting to that message, set its properties accordingly?
You can see a fairly thorough and diverse discussion of instantiation here.
I think the consensus is generally that you do not want to addComponent
on tons of prefabs to "specialize" them and you do not want to instantiate tons of prefabs all at once (in one frame) unless it's in start()
. Other than that, my suggestion would be to have a single prefab, give it a script that lets you set the proprties you want to set, and proceed accordingly.
Upvotes: 1