- Home /
Make all instances inherit the same value from parent and make static
Basically I'm trying to create a prefab that has a script with certain variables that I give it, the only thing I'm unhappy with is that when I place the prefab into the world it obviously carries the variables down onto the instance. For example if I made an item prefab and I called it 'Rock' it would mean that every instance of that prefab would have it's own variable called 'Rock' which is kind of a waste of memory.
What I'm trying to do is along the lines of a static variable but obviously if I did use a static variable that means I'd have to create a new class for each item or a new variable for each item.
Answer by UnityCoach · Jan 23, 2017 at 10:51 PM
You can use a ScriptableObject. One of the particularities of Scriptable Object is that you only reference them.
So, every "static yet derivable" properties can be part of a Scriptable Object that you reference in your Prefab/ScriptInstance.
Then all you need is to create as many ScriptableObject instances as you need variations.
I +1 this. You can create a ScriptableObject called RockData which can be instantiated as an asset in the project folder via the [CreateAsset$$anonymous$$enu] attribute. It can store things like strings, bools, lists, references to other assets in the project and so on. Then each prefab has a $$anonymous$$onoBehaviour with specific or shared logic in them and they all reference the RockData instance that lives in the project. That way, they all share the same memory and only need a single, very small pointer to the asset. Next, when you need to have variations, you just need to create multiple instances in the project or you can associate instances with scene objects, as well. You can still share data between multiple scene objects when referencing either an SO asset or an instance within a $$anonymous$$onoBehaviour in the scene.
Your answer

Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
Inheritance best solution to handle *many* instances of a class with unique values? 1 Answer
How to set different classes at runtime 2 Answers
Having problem with constructor 3 Answers
Inherited member variables not set to base value c# 1 Answer