Class instance vs Prefab instance

Hello all,

First off, Happy Friday! :smile:

I’m wondering about the differences between creating a C# script and adding it to a prefab, then instancing the prefab or creating a public class that the object instantiates when it loads? I understand an instantiated class will create new data, but all the methods would be referenced.

Is this basically the same case when instancing a prefab with an object that has script as a component? It seems either would work fine from a functionality standpoint, so this is probably more of a memory question. Also can anyone recommend a good way to check on memory usage like this?

Thanks for any input,
-d

The main difference between a script component instantiated along with a prefab and one that is constructed at runtime is that the component derives from MonoBehaviour. This means that it gets its Start, Update and other functions called when appropriate. Also, its properties will be visible and adjustable in the inspector. If you don’t need these features, it probably won’t make much difference which of the two approaches you use. I guess that an object constructed from the script can go out of use in cases where an instantiated prefab can’t, so you may sometimes get better memory performance. However, this is most likely to occur when you are creating objects at a rapid rate. For example, it would be better to keep an array of constructed objects rather than instantiate lots of prefabs purely for their scripts.

Thanks andeeee, that really helps and clears up a lot of questions.

Is there ever any benefit to creating a class without making it a MonoBehavior class? I realize it wouldn’t have access to Awake(), Start(), ect.

cheers,
-d

Classes have all sorts of uses, and it is often handy to define your own classes and create objects from them at runtime. MonoBehaviour classes from scripts are designed to be added directly to GameObjects as components. If you need an object that is active in the scene somehow (eg, getting regular updates, responding to collisions, etc) then a MonoBehaviour script is the way to go. For most other uses (data structures, etc) a non-MonoBehaviour class is much easier to use.

Excellent!

Thanks again sir,
-d