We use scriptable objects pretty much in the way you dont see them useful. We have a in-game tutorial each step in the tutorial is a scriptable object. A tutorial is just a collection of scriptable objects executed in sequence. Whats nice is that you can reuse teh same configured .asset multiple times.
This seems like perfect place to ask a noobish (ScriptableObject behavior related) question;
Why should I use ScriptableObject.CreateInstance, instead of Instantiate?
I’ve seen some examples here and there talking about this, but I’ve also seen people use Instantiate as well. Seems like both create exactly the same end result. If I have something like this:
public SO someSO; // ScriptableObject Asset ref, that only has two fields, int and float
public SO so1; // For testing
public SO so2; // For testing
void Start ()
{
so1 = Instantiate(someSO);
Debug.Log("so1: " + so1.ToString() + " intValue: " + so1.intValue + " floatValue: " + so1.floatValue);
// Result:
// so1: soAsset(Clone) (SO) intValue: 2 floatValue: 3
so2 = ScriptableObject.CreateInstance<SO>();
Debug.Log("so2: " + so2.ToString() + " intValue: " + so2.intValue + " floatValue: " + so2.floatValue);
// Result:
// so2: (SO) intValue: 2 floatValue: 3
}
If I run this, the end result is nearly the same, only name of the version created by CreateInstance will be missing the part “soAsset(Clone)”. I can double click both in inspector to see what they contain, and they both look just the same. Only with different instanceIDs.
Edit (I can at least answer partially to my question):
If I got this right, it seems like Instantiate “clones” the Created asset, as it is. If I change the values (2 and 3) from the asset to 1 and 2, the result will be like below. Instantiate takes values from Asset, whereas CreateInstance takes the values from script file:
// so1: soAsset(Clone) (SO) intValue: 1 floatValue: 3
// so2: (SO) intValue: 2 floatValue: 3
But I have to say, I haven’t found any threads or sources to mention this, or how this exactly works.
You can do the same thing with a prefab. Both are just assets that can be loaded and then instantiated (copied). Prefabs are a bit different in that MonoBehaviour is involved. Depends on what you want.
Each step really dont have a relationship to a transform
Here is an example,
A step that displays a popup message.
A tutorial are a collection of these
Offcourse it could have been made without scriptable objects, but I liked the approach
@zombiegorilla - I did read that page, but I guess it didn’t sink in to my head then… ![]()
I guess I should have underlined that I haven’t found anything that explains this clearly and thoroughly… it’s not newbie friendly or very easy to understand. When you already understand the system, the words probably make sense, but not in my bonehead… All I got from this page are cryptic sentences like these:
"CreateInstance - Creates an instance of a scriptable object. "
“Instantiate - Clones the object original and returns the clone.”
The "Clones the object original" for Instantiate doesn’t really sound too clear. They are calling the actual Asset file a “object original” and this actually means that this creates an exact copy of the existing ScriptableObject Asset file, along with it’s inspector / however assigned values (not the ones defined in script file). Just wondering why they have to be so terse. But anyway, IMHO there are several such vague definitions in Unity docs that I find hard to understand clearly without experimentation, meaning I’m guessing… until I’ve figured the meaning by trial and error.
It does state clearly that one is an instance and one returns a clone of the object. I’m not sure how it could be clearer.
The api documentation isn’t an introduction to programming, it’s a description of what the api does. If therms used are unclear, there are introductory tutorials in the learn section as well as some great resources on the web.
ScriptableObject.CreateInstance is a bit outdated since they added the CreateAssetMenu attribute which took away alot of the boilerplate code
https://docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html
It can still be used to batch create stuff etc
I do not know but it is weird for me as I use scriptableobjects for anything.
I know it is awesome that I create FloatVariable, IntVariable, IntArray, etc and assign the scriptableobjects to several mono classes.
In “PlayerHealth” example, I have already used it, created it and assign it to PlayerHealthUI class, etc but it is weird that there is only one field in a class (scriptableobject), share data to other mono classes.
Have you seen this approach in other frameworks and environments?
I would really like to consider scriptableObjects like initializers and immutable. If other classes like Healthbar want to access current health, they can do using the mediator mono class or events like ValueChangedEventHandler.
I know it decreases modularity but …
ScriptableObjects create dependency hiddenly. Sometimes, they can be seen like controllers in MVC patterns.
public class Player:MonoBehaviour{
[SerializeField]
private IntVariable _maxHealth;
private int _currentHealth;
void Awake(){
_currentHealth=_maxHealth.Value;
}
}
Sure. Ultimately, it’s just an object instance. The only difference is that you can assign a reference to it at design time.
Yes it encapsulates values in references.
I meant you see classes with only one field in other places?!
Is it normal to use classes with one field?
Sure, if that perfectly represents its single responsibility, then yes. In some frameworks I’ve even seen classes that have no fields whatsoever, used sort of like tags.
I see it like css. One approach is to create css blocks with one properties like background-color or color or font and combine the classes to reach a special class in tag html.
Some developers do not like this approach but others like.
So you agree to modulate in the lowest level for example FloatVariable maxHealth (immutable) or currentHealth(muttable)?
If I faced situations that I need a field (mutable or immutable) in two or more mono scripts, it will be appropriate to use scriptableObjects for the field?
As long as it keeps your code concise, readable, maintainable, and reliable, I think that would be fine.
I use scriptable objects as much as possible to act as a sort of global variable to avoid using singletons every where, I’m able to change the variables value from anywhere leaving my event system free to just call methods when needed without needing to pass variables.
This topic is an interesting read but Oh god please don’t tell me I’ve done it wrong again. I’ve already revised my project twice now, last time was to remove singletons lol.
Edit: maybe time to make a seperate thread again for me to ensure I’m on track
One of my coworkers created a tool for that. You can do the same thing yourself - you just have to find them with the general Find methods and show them somewhere.
An important thing to note is what happens if you create an SO, assign it to a MonoBehaviour in a scene, and don’t save the SO as an asset. When you save the scene, that SO gets appended to the scene file. So you can have SO’s that just live in a scene, if that’s somehow useful.
Unity also seems to do a perfect job of “garbage collecting” the appended SO’s, so if no MonoBehaviours are referencing them anymore, they get automatically deleted when you save the scene. AFAIK, none of this
is documented.
We use SO for a bunch of runtime data. For example, all of the npc’s in our game is defined in an SO. Methods to modify them are placed in the same file.
The way this works is that we define all of our NPC’s as ScriptableObject assets in the assets folder. At builds, those are written to a save file (ie. the state of a save file , and then copies are instantiated from the save file. We could have done this with an xml/json/whatever instead, but using SO’s for this have some nice advantages:
- Serialization is already solved
- It’s easy to create editors for the data
- We can reuse the editors for the runtime data, so it’s not that much work to create debug views of the game
There’s a big downside here, in that we had to make some special tooling for some kinds of data referencing other kinds of data. Both npcs and locations are Scriptableobjects like this, and both are fetched from the save file. This meant that we had to create special wrapper-types for fields, that allow designers to drag-and-drop assets like usual, but use IDs for serialization of the assets so the clones can be picked up on deserialization from a save file. It might sound bad, but the alternative is creating a completely from-scratch toolset around eg. xml, or doing some kind of creative leap where all SOs contain all of their data in a container that’s cloned on startup.
Fascinating discussion. Keeping your SOs immutable avoids a lot of problems, but I am not sure it is utterly necessary. What seems to happen is that Unity uses reflection to extract state and remembers it. Interestingly, for each SO you have created, a call to that SO’s class’s constructor occurs when you enter play mode, so I have to guess that Unity does not keep instances alive between exits and subsequent re-entries to play mode. However, it does restore the prior state it memorized for each instance. That includes state that changed during the last time your entered, then left, play mode.
This leads to the somewhat odd behavior that, when you first create an SO, if its constructor initializes a private field, that initial value is retained for the lifetime of that SO, even if you modify its constructor to set the same field to another value. So, if you have private int x in your SO class, and your SO’s constructor includes x = 3, when you create the SO, x will be given the value 3. But Unity remembers that value from then on, so that if you change your constructor and replace x = 3 with x = 2, new instances of that SO will show x = 2, but instances you created before that change continue to show x = 3. This would make sense if the instances were kept around after the first time you create them, but that’s not what appears to be happening. For whatever reason, Unity creates a full set of instances of all your SOs every time it enters play mode, restoring the state it extracted after it created them the first time. This leads to some inconsistent persistence. For example, multicast delegates do not appear to retain their subscribers across multiple entries to play mode. I am guessing that Unity either can’t, or just doesn’t, extract those lists, so they can’t be retained (and, therefore, can’t be restored).
Ryan Hipple’s video emphasizes the elimination of singletons by use of SOs. His example code shows how to avoid persistent state being a problem by using OnEnable and OnDisable handlers in his Monobehaviour objects, such that whatever sorts of mutation he applies when play mode is entered, all of that is undone when play mode is exited. It would be nice to do that with OnEnable and OnDisable handlers in the SOs themselves, but Unity appears to call these somewhat erratically and in no predictable order across SOs. (I can’t consistently duplicate it, but Unity does call OnDisable for SOs that have never had OnEnable called.)
I think I would be willing to use a very lean singleton to call all of my SOs in a given resource folder and, say, tell them to restore themselves to their initial state, then follow that with a call to all of those SOs to do whatever communication among each other is required to prepare for game-play. In a sense, Unity’s run-time engine is such a singleton, sending OnEnable and OnDisable messages when it deems it appropriate to do so. Having a singleton of one’s own do something similar, particularly if that singleton is immutable, does not seem all that awful, and it does allow for mutable SOs which can maintain all sorts of changing state independent of any GameObject.
I sometimes use scriptableObjects instead of singletons. Also, scriptableObjects are like controllers in MVC patterns.
You can remove controllers and instead use scriptableObjects.
Finally I utilize it for configure settings and read only data.
Before, I applied scriptableObjects only for immutable data but I knew it is so useful and increases maintainability, if I use it for mutable data as well.
scriptableObjects are very helpful. If you do not use scriptableObjects, you sometimes need to create many same prefabs(same meshRenderer, scripts, etc) with different values. It is awful.
Also, you can create one scriptableObject and use it in several prefabs and monobehaviours.
I tend to see them more as models in the MVC pattern. Controllers were really just part of the Smalltalk language. They pretty much don’t exist in the current MVC pattern, which is more of a Document-Observer pattern, I think.
that whole roundtrip is called serialization btw
in unity land at least [it can cross native/managed boundary that way]
did you by chance have [SerializeField] attribute on that private field ?
EDIT: Oh, and btw scriptable objects are special in that changes from play mode in the editor are persistent - as opposed to ‘normal’ MonoBehaviours where changes from play mode are not transferred when stopping it (i.e. are restored back (via serialization system))

