The Ultimate Introduction to Scriptable Objects in Unity
Вставка
- Опубліковано 31 лип 2024
- In this video I'll introduce you to ScriptableObjects (SOs), show you what they are, how they work, how to make one, and why you should use them.
ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
sam-yam.itch.io/samyam-full-s...
📥 Get the Source Code 📥
/ 61460588
🤝 Support Me 🤝
Patreon: / samyg
Donate: ko-fi.com/samyam
Try out Machinations for FREE today!!
👉machinations.io/?...
►🔗 Relevant Video Links 🔗
ᐅUnity Forum - ScriptableObject behaviour discussion (how Scriptable Objects work)
forum.unity.com/threads/scrip...
ᐅScriptable Object API Unity Documentation
docs.unity3d.com/ScriptRefere...
I go over the Scriptable Object creation, instantiating them through code dynamically, showing the functions you can call within them, and will mention additional uses with them such as event based messaging and replacing enums. I will be making another video going more in-depth with the event based messaging. Scriptable Objects are scene and play-mode independent assets that live in the project scope and are used to contain data. This makes it great for rapid iteration for both developers and designers and allows for easier testing due to reduced dependencies (can isolate testing features).
Small Fix, in the video I said to put SerializeField and a private setter, but make sure to add the field tag as so
[CreateAssetMenu]
public sealed EnemyData : ScriptableObject
{
[field: SerializeField]
public Int32 MaxHealth { get; private set; } = 100;
}
►⏱️ Timestamps ⏱️
0:00 Intro
0:38 Machinations Sponsorship
1:55 What are Scriptable Objects
3:47 How to make a Scriptable Objects
7:11 Enemy Scriptable Object Example
11:16 Scriptable Objects Overview
11:53 Scriptable Object Functions and Execution Order
14:47 Instantiate Scriptable Object in Code
16:33 Event Based Messaging with Scriptable Objects
17:07 Sidenote - Don't destroy original Scriptable Object
17:21 Replacing Enums with Scriptable Objects
19:11 Outro
💖💖THANK YOU TO ALL MY PATRONS 💖💖
❯❯❯ My Links ❮❮❮
💗 Patreon 💗
/ samyg
💬 Discord Server 💬
/ discord
🐦 Twitter 🐦
/ samyam_utube
📚 Facebook 📚
/ samyam.youtube
🎵 Music 🎵
Ambient Gold
streambeats.com
👍 Like and Subscribe! 👍
🖥️ Computer Setup 🖥️
*As an Amazon Associate I earn from qualifying purchases.
www.amazon.com/shop/samyam
Disclosure: This post may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we have recommended. While clicking these links won't cost you any money, they will help me fund my development projects while recommending great assets!
#madewithunity #gamedev #unity - Наука та технологія
Small Fix, in the video I said to put _SerializeField_ and a _private setter_ - but make sure to add the *field:* tag, like so:
---------
[field: SerializeField] // Notice the field: part. Adding this inside any attribute will make it work with Properties.
// Others you might want to use are [field:Range(min: 0, max: 100)], [field:Tooltip("description")], etc
public int MaxHealth { get; private set; } = 100;
---------
Wait, what?! I suddenly need to refactor my whole game...
I didn't know this one... today you taught me two new things.. you got new sub 😁😁
define NONE? I used IDLE and this aligns with the game logic. After scriptable objects and events, I think the next big issue is the delegate feature. Why don't you make videos about these?
I was on your channel looking for a playslit that included this video but couldnt find one? Did you end up making a playlist or series regarding Scriptable objects as part of another project?
@@Sam4Progress Not really, I do have this intro video though ua-cam.com/video/cy49zMBZvhg/v-deo.html
This is a good video, and I approve of it, but you forgot a very important part of ScriptableObjects: They can run code. Which means you can use them to alter behaviour of stuff. As an example, you can create different ScriptableObjects for different types of AI, and just switch out the "brain" of an enemy to try out different behaviours. I once made a game where we used ScriptableObjects to alter the behaviour of text, so when the player read to a certain point in the text, stuff such as particle effects, screen shakes or sound could play. This is a very powerful tool for your Designers. You should at least mention that it's possible, although all the possibilities would probably require its own video.
That's a good point, I had forgotten to clearly mention it in the video, thanks! I should probably make a separate video on it just because it's such a exhaustive topic after the event based messaging for scriptable objects video 👍
@@samyam That would amazing to see. Would really complement this video as a follow up
This is by far the best scriptable object video I've seen!
Thank you!! :D
The thing I like, is that you mention how important these are when working with designers
So many tutorials forget that game development isn't just about programmers showing off their programming skills but cooperating with non programmers ( designers, artists, etc... ) and making sure they can work autonomously
While I follow and really like your channel, I want to give humble advice. Your tutorials start easy and very understandable, it becomes really hard so quickly. I totally got lost on "Enemy Scriptable Object Example" part.
Your presentation skills are great, and I really want to learn with your content.
All the best!
Thanks for the feedback! I’ll try my best to avoid doing that in the future :)
This is perfect! I needed a new introduction to scriptable objects lately
Samyam, I am Incredibly grateful for your channel's inspiration during tough times. My game is hitting Steam after two years of learning!
I loved this video! this was very comprehensive and got me super excited to try it out!
this is really the best video about SOs, that i found today)
thank you so much, waiting for new tutorials in your style :)
Amazing tutorial. Thank you for taking the time to do this.
i am amazed by how much your channel has evolved. Congrats :)
Thanks Anton! Hope you’ve been well!
Thank you so much for this video! I had a bunch of data in scriptable objects but was struggling to connect them to actual objects in the scene, this was a massive help!
Awesome to hear!
Thanks for actually showing how to create one unlike all the other videos I have watched where it just explains bunch of stuff instead of showing how to create a scriptable object lol
Thanks Samyam, super useful video
An ESSENTIAL Unity tutorial. Thanks again for such an awesome video!
This is such an amazinly done video so clean and useful and to the point
Excellent introduction for this topic. Thanks.
Easily my new favourite unity tutorial channel. The way your videos are organised is freaking perfect. Most other tutorials are jumping all over the place.
Great video as usual! I've been really digging SO's for a while now
Thanks Dan!! 😁
This woman is a hero ❤️🙌🏼 thank you so much for this Sam ❤️
Thank you Rebar! :)
Your code is so clean it shines. Awesome job.
✨ ✨ ✨
bro thanks so much, you actually made soft soft easy to understand
Every time I stumble with your channel I read Saiyaman instead of Samyam so, with this and your useful tips I guess.. 🤔you're kinda my hero 😅
This is fantastic, thanks
Thank you so much for this.
Wonderful tutorial as always!
Thanks!
thanks! helped a lot!
normally i dont give reviews but maam youre amazing like i tried 2 videos on 2020 and one on 2022 but it wont work but i saw yr video today and it worked as being both content creators i respect your hard work and keep it up
Thank you so much I appreciate it!! 😄
What an angel! You save my broken head!
hanks lot Sir.. You helping us..
TNice tutorials was a fantastic beginner's guide, straight to the point, very clear. As a long-ti teacher I can tell you are quite apt at teacNice tutorialng!
great video !
New subscriber ... I really wish I had seen this video a year ago when I was digging into SOs. This was just so much better, clearer, and contains way more info, than all the other videos I watched last year. Such a simple example but the first part of the video explaining how its an asset really made it pop.
Thanks so much glad you enjoyed it! :D
You rock, this is super helpful. Subscribed.
Thank you!
Thank you so much 😊😊😊
great video thanks a lot
Great video! I have a save system with scriptable objects that holds data. So for every object that i want to save, i create a scriptable objects. I watched this video and saw we can create instances of them. So, what my question is that is this going to create instance every time we start playing the game if we use that code in start?
forexample i want to grow tomato, i wrote all scripts required. i just duplicate tomato object in the scene but when i grow 1 of the somato, other also grow at the sametime... so 1 scriptable object will be enough for both of them work independent ?
Fantastic video! Subscribed :)
Thank you!!
Didn’t know they had awake and onEnable. Brilliant video… thank you 😊
Thank you!!
what a great video :D
Thanks!
Good stuff
what if you have functions that you need to save as data. like making a game with active/ passive skills that you can use.
If i store functions how would I execute that from a scriptableObject and apply it to the scene?
How do you access the Scriptable Object data without use of the inspector, purely in code? Like if I wanted to get the Goblin Enemy Scriptable Object's Health integer from inside another script?
I have been using SOs (Scriptable Objects) for all of my projects now (been a year or 2). I use it for the Handling GameManager States such as if the game is starting, running. If the player is dead etc
I am looking forward to Event-Based SOs as I use Unity Events and C# Events (Delegates and static events) but I have never figured it how it works with SOs.
thx nice video
and build tracks from there and leave the rest for a later session. I did both but did the first way initially and it took a day to get through
Great video but I want to clear one thing that scriptable Object are not used for save system, because they don't persist data in build runtime i.e. the game runtime, they persist data only in the editor and any other scene which has reference to that specific scriptable object, if there is no reference to it on other scene the data will lost.
So how actually access that "goblin" parameters? Only main script is accessed in the example.
Nice creative title.
Good video on the basic usage of scriptable objects. One of the biggest things is using them for events. You mention an inventory or save system but I've heard those are actually more complicated than one would think. Do you think it's possible for you to cover those in a future video as well as events?
That's a great idea, perhaps I will once I get through some other videos first!
I'm going to experiment with a localization system with Scriptable Objects. Would be cool to see your take on this!
It might be good to know that Unity has a built-in Localization System. Though I'm not saying you shouldn't make (a better) one, just be aware of it.
_com.unity.localization_
In my case I am trying to make a card game whose card effects are very unique per card. I've taken the approach to make each card a unique scriptable object, meaning each card will have a new scriptable object implementation, and one instance of that scriptable object. Is this a good approach?
what is the color theme used for VSCode?
So ScriptableObject.Destroy(); will destroy /delete the script from the project folder & not just in the hierarchy ?
Great work, Samyam! Love your videos. Keep going! 🙌
Thank you!! 😁
Watching this seemed very basic, and although a really good thing it also has me wondering about the limitations. These would extend to Dictionaries, lists, Indexing, using a NameSpace, and its just how far encapsulation can go.
When you create an instance of a scriptableobject where is it? They obviously don't show up in the hierachy and they don't show up in any folder and they are not attached to any gameobject. So where was it? If you didn't create a scriptableobject with code you'd have to do it through the menu system and then it shows up in your folder so you can edit the values and then drop it onto a gameobject. But running CreateInstance does exactly what?
THIS IS AMAING !! you and the way you explained it and also scriptable objects
Glad to hear!
15:15 what about using this line instead of what you have on line 9 ? This way you'll omit implicit casting that might result in a runtime error, right?
test = ScriptableObject.CreateInstance();
Samyam what theme for VScode do you use?
Godot theme!
Hey would it be a good idea to use scriptable objects for projectiles in my top down shooter game? i'm trying to implement it but having trouble. Ive looked elsewhere and no one uses them as short lived objects. What do you think?
I don't think you'd gain anything by putting meshes on scriptable objects. It won't save any memory since Unity already references duplicate meshes from a shared Mesh pool. Would 100% recommend object pooling though!
I think ScriptableObjects mostly shine from a design perspective since you can use it to make quick adjustments to speed, damage, etc.
Even if you want to describe every bullet in the scene, lets say with a 16 byte string that says "BulletAR", and a 4 byte int to store the damage. You'd only be saving 20 bytes per bullet in your scene. That's only 20KB saved per thousand bullets.
What about just not inheriting from monobehaviour, having data be just classes you serialize into json or xml files, then load and save these data types.
So let's say you have an SO of item, with it's attributes and sub classes for armor, weapons, consumables, etc, each with its own attributes. How then do you access those things like: defense rating or attack rating? Or am I just not getting it?!?
In between minutes 12~14, it seems that person is only thinking about the ones who makes or generates games / apps via Unity, instead of remembering that there are tools makers as well (like persons that extends on default Unity's Editor functionality) - so it is logical that SOs are also friendly for such usage as well. I don't get why the exaggerated [????] writing thing... Like if it necessarily needs to be a bug ?
Then, about execution order, well, after all, it is just a generic file container, so I don't see why they need to forcefully be tied up to any particular execution order by design? Thus, when you do cast* them (their contents), it is not 'so you can access it more easily' but rather, so you can access it. Like, so it can become the adequate data/variable type for your script to correctly handle without producing an error.
Regarding instantiating and memory usage, nothing takes RAM memory until you actually spare 'room' for it (allocate) at execution time. So (in my opinion) stating that because some data structure is residing in an SO will make it not to consume memory can be misleading for the new ones. It does consumes storage memory while at the file (SO) dormant level, the memory needed to store the related file content, plus, if you decide to instantiate many enemies say that makes use of any value store in there you are casting into your own variable and using, then it is using exactly the same memory as any other regular monobehaviour script structure will use. 500 individual enemy health float variables on game screen takes the very same RAM memory if instantiated (allocated) at run time, no matter if from a file's data (SO) or from a script. Allocating for usage is allocating for usage. So I think that the memory conservation can be a misleading subject all-in-all. Unless I'm not getting to understand the point, in case which I do honestly apologize for any related confusion then.
Can you really make a save system system with them? It seems the changes are not persistent if you close and reopen the game in a build, outside of the editor
you can not make save system with them, they only retain value in the editor or any other scene which is reference that specific scriptable if they are no reference for it in the other scene the scriptable object will go back to its previous state.
Your sponsor message scares me to death
Why didn't anyone mention this when I was tackling the binary formatter to just save some simple data🤪 Is there a benefit to storing data that way instead of scriptable objects(like security)
EDIT: I'm dumb XD I didn't realize Scriptable Objects didn't save in the game build
I've always wanted to make soft but every ti I download software to do so, I just look at the 5,000 buttons/settings, cry for a few
Could u make a tutorial of how to get active controller? if is a playstation, xbox or a keyboard?
The PlayerInput component has an event you can subscribe to OnControlsChanged that tells you when a new device is registered, I go over it here 26:40
ua-cam.com/video/Y3WNwl1ObC8/v-deo.html
But a dedicated video is a good idea :)
Hello samya I love your content and your excellent voice I am going to leave my subscription and like, but I have a question, with the new input system you can interact with objects, that is, doors, cabinets, pick up stones or boxes etc, with mobile controls and with the keyboard??
Yes of course! The input system just managed input, it’s up to you to read the input and do what you want with it. Thank you!!
@@samyam awww thank you thank you but I'm new to that system jsjsjsjs 🥺🥺🥺🥺 you couldn't do a tutorial on how to do it please☺️🥺🥺
ua-cam.com/video/m5WsmlEOFiA/v-deo.html
I'm a simple guy..
I see my name, i click
I've been using ScriptableObjects for a while, but I had no idea about those built in functions and their shenanigans. I'ma stay the hell away from those jeez.
Thanks for the video.
Game idea: drink a shot every time you say "scriptable object"!
Jokes apart, very exhaustive explanation. 👏👏
Hahaha that would cause alcohol poisoning. Thanks so much!
Don't you think there are many mistakes in this video, I would say is best to re-record it if it is possible and add the new link into this.
life is life la laa - la la la bruh
Scriptable objects are NOT meant to be used as a save system! You will lose data if you try to use them in a program as a way to save persistent data.
Here is a demonstration video from Code Monkey about this pitfall:
ua-cam.com/video/5a-ztc5gcFw/v-deo.html
I feel like there is gonna be a r/whoosh joke here
the way.
It's like a variable on steroids!
you can set values to enums, so the part of "Replacing enums with scriptable objects" makes no sense. Anyway, it was a great video and very educational, TY
god bless u xdd
This is a good tutorial but the start looked like an ad and made me cringe a bit D:
How the script was written for this video -
____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects. ____ _____ _____ Scriptable objects.
I don’t write scripts 😉
Dave 84
UwU
mac
and sa tNice tutorialng other way around
And how the heck do we learn machinations xD? Joking
great video. Just to add a small opinion. Do away with the random b-roll stuff, it is just distracting and non-informative. Just keep up your graphics instead of flipping back and forth to random b-roll people.
Thanks for the tip! I actually think the B-roll increases audience retention to keep capturing their attention, but I’ll play around with it and see the best results :)
Where is the script that you created with code? After the "how to create a scriptable object" there is nothing of value actually. Those lifecycle methods are not useful. A more useful demo would have been to get data for 100 objects from a database, then create a scriptable object for each to apply to each enemy. You're essentially bringing the scriptable object into existence and destroying it before we even know it even existed.. how is that useful?
Sam you got 18k subs...
Why posting only one video per month then 😐😐😐
Cause I’m a busy person! 😉
The ENUM explanation is so wrong. Who in their right mind uses values in their code when they have ENUMS defined ???????? Sounds like a case of someone not knowing basic programming - NO magic numbers! It is a really good idea to use the Scriptable Objects instead though.
please do not use scriptable objects as a save system, its not persistent when you build the game, if you do use scriptable objects, use json
it would be cool if you pitched your voice down to a male level so it sounded super cool and not god awful annoying. so i have to leave and thumb you down so sorry.
Good video, I didn't know about the OnEnable etc in ScriptableObjects!
I'm confused about the use of ScriptableObjects to replace enums though. My understanding is that you should never hard code in the index, e.g.:
if (attackChoice == 0)
You should use the name of the member, e.g.:
if (attackChoice == AttackType.SWEEP)
So it shouldn't matter if an enum member is deleted. I thought enums are largely used to avoid this specific issue of having to hard code in numbers for a set of options.
And in the situation where you're working with a messy codebase - where whoever wrote the code has been littering indexes as they relate to an enum, rather than the enum itself - and you need to delete something from an enum knowing full well that there are index magic numbers that will break elsewhere in the code, there seems to be a better fix.
Rather than delete an enum option or replace it with NONE, you can just manually set the member after the deleted one back to its expected index, e.g.:
enum AttackType {
SWEEP,
//removed JAB, which was index 1
TEST = 2,
SIDESTEP
}
Now you've removed the unwanted member without affecting any of the existing indexes.
Finally, there shouldn't be a problem with a designer creating a new enum member, unless there are magic number index references (instead of referring to the enum member name).
Please do let me know if I'm missing something here! Great video and I definitely learned something new, just lost on this one point. Subbed :)
This addressed here in the talk samyam linked in the description: ua-cam.com/video/raQ3iHhE_Kk/v-deo.html
Short answer: enums are serialized to their number values.
@@Eddycted Yeah but you can specify the numbers an enum value corresponds to
realy work)