Jump to content
  • Advertisement
Sign in to follow this  
  • entries
    4
  • comments
    0
  • views
    590

Create Scriptable Objects with Unity

Sign in to follow this  
Vivek Tank

865 views

Objective

The main objective of this blog post is to give you an idea about ScriptableObject in Unity.

What is Scriptable Object?

What is the difference between ScriptableObject and Monobehaviour class?

What are Pros and Cons of Scriptableobject?

How to use ScriptableObject?

Let’s undertstand all the questions by taking one ride of this blog about ScriptableObject

According to Unity API documentation,

"ScriptableObject is a class you can derive from if you want to create objects that don't need to be attached to game objects."

Confuesed..?

Don’t worry, if you didn’t get it. Here, I will Explain what it means.

As we know, with Unity, everything is an Object.

typesofobject.png.4f16be719604ccb987219d2acb4a79f7.png

Monobehaviours are one of the Objects.

GameObjects: In your scene, you can move around with transform.

ScriptableObject is a kind of Object but, it can only Contain Data.

So, they don’t get involved in the actual game.

I hope you understood the definition of ScriptableObject.

Let's discuss Pros and Cons of ScriptableObject.

Prose of ScriptableObject:

  1. Built into Unity
    • They’re very well maintained by Unity.
    • You can interact with them very easily in Unity inspector.
  2. Can be saved as Assets
    • You can create it as a mini file inside your project.
    • You can update that and save that as per your game requirements.
  3. Can save during runtime
    • If you change something during runtime it will actually remember that.
  4. Internal Solution
    • When you are trying to get the data during run time of the game, you don’t worry about parsing external files which will come into play more.
  5. Large amounts of Data
    • You can save millions of integers inside of a ScriptableObject.
    • So, there’s a lot of space(no size limit function).
  6. Add to Structure as you go
    • As you’re building a scriptable object and create few instances of it and realize ,ohh I need a new setting for ‘moveSpeed’ or whatever additional variable you need you can add, it won’t disrupt your variable.
    • Deleting variable can have a little bit negative impact.

Cons of ScriptableObject:

  1. Requires an editor scripting
    • If you want to make assets out of scripting then you have to know a little bit about it.
  2. Can’t edit outside Unity
    • If you’re working strictly with Unity that’s not really a huge issue.
    • But if you have like team base solution, where you want to send files to someone and have them edit then it won’t work.
  3. Can’t save once deployed
    • Can’t save during runtime,once you’ve built the game meaning that this is not solution for saving a player’s data.This is only for saving game development data.

Let's take one example to understand how to use ScriptableObject in game.

Let me give you one task first.

Suppose, we have 10 level game and at each level the behaviour of enemy will change.

Any Ideas, how you will do this??

Ahh, You might think that make 10 prefab of 10 different enemy and assign it to each level. Right??

Are you sure, it really a good practise?

Actually, the answer is No.

"Because one enemy object may have 4 variable and Update() function with it, and suppose is uses 4 Mb of memory, so 10 level enemy may require 40 Mb of memory amount."

So, here is the solution. Use ScriptableObject to store data of enemy Object.

Let’s, develop our mini game with ScriptableObject.

First, I will create a simple script without using a ScriptableObject. (As per our first thought about creating different prefab of each different enemy and assign it to each level ;) )

Step 1

  • Create an empty GameObject name it Enemy.

Step 2

  • Create C# script and name it EnemyMove

Write following code in EnemyMove.cs

public class EnemyMove : MonoBehaviour {
    #region PUBLIC_VARIABLES
    public string name;
    public int moveSpeed;
    public Color color;
    public string colorName; 
    public SpriteRenderer spriterendere;
    #endregion
    #region PRIVATE_VARIABLES
    private float speed;
    Vector3 newPosition;
    #endregion
    #region UNITY_CALLBACKS
    void Update () {
        ChangeSpeed();
        gameObject.name = name;
        spriterendere.color = color;
        newPosition=transform.position;
        newPosition.y = Mathf.Sin (Time.time) * speed;
        transform.position = newPosition;
    }
    #endregion
    #region PROVATE_METHODS
    private void ChangeSpeed(){
        speed = Mathf.MoveTowards (speed,moveSpeed,Time.deltaTime);
    }
    #endregion
}

Step 3

  • Assign it to empty GameObject(Enemy).
  • EnemyMove script has three public variables.
  • If game has so many enemy GameObject with enemyMove script with it then uses lots of memory.
  • For that as per our solution ScriptableObject, we can make a EnemyData script Instead of storing these variable within EnemyMove script.

Step 4

  • Create C# script name it EnemyData.
  • which inherits ScriptableObject instead of Monobehaviour.

Write the following code in EnemyData.cs.

public class EnemyData : ScriptableObject {
    #region PUBLIC_VERIABLE
    public string name;
    public int moveSpeed;
    public Color color;
    public string colorName; 
    #endregion
}

Step 5

  • Change the code inside ‘EnemyMove’,which was previously created.
  • Create One public variable ‘data’ which is the reference of ‘EnemyData’.
  • Remove the public which is already in ‘EnemyData’

Change according to following code.

    public class EnemyMove : MonoBehaviour {
        #region PUBLIC_VARIABLES
        public EnemyData data;
        public SpriteRenderer spriterendere;
        #endregion
        #region PRIVATE_VARIABLES
        private float speed;
        Vector3 newPosition;
        #endregion
        #region UNITY_CALLBACKS
        void Update () {
            ChangeSpeed();
            gameObject.name = name;
            spriterendere.color = data.color;
            newPosition=transform.position;
            newPosition.y = Mathf.Sin (Time.time) * speed;
            transform.position = newPosition;
        }
        #endregion
        #region PROVATE_METHODS
        private void ChangeSpeed(){
            speed=Mathf.MoveTowards (speed,data.moveSpeed,Time.deltaTime);
        }
        #endregion
    }

Now you can see that inside the Inspector for Enemy GameObject on ‘Data’ variable will appear,

Any idea..what you suppose assign over here??

enemymove-inspectorwindow.png

Follow me...

Step 1

  • Add one line in EnemyData.cs as follow
[CreateAssetMenu(fileName="EnemyData" ,menuName="Enemy Data")]
public class EnemyData : ScriptableObject {
      #region PUBLIC_VERIABLE
      public string name;
      public int moveSpeed;
      public Color color;
      public string colorName; 
      #endregion
}

Step 2

  • Create one folder Game data and do following

assetsenemydata-menuitem.png

Step 3

  • Name it as you like.
  • Now, you can see all the variable inside the EnemyData in inspector window, you can change values of variable here.

enemy data inspector window

Step 4

  • Assign this into ‘EnemyMove’ script

assign enemy data to enemymove inspector window

I am sure you got all the answers now.

Conclusion

  • ScriptableObject are really good for the fact that they can break your data into more sizeable chunks.
  • So that you’re not eating up a lot of memory.
  • ScriptableObject is only for development purpose.
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By jb-dev
      This is a picture of a regular room. 
      Each rooms has a chance to have props with a certain layout.
      If a rock is spawn the player can try to break it by exploding it. These can spawn common collectibles like money and such...
      There are many different type of layout possible, including a totally random one.
      The generator simply picks a shape, an anchor position and the type of prop to be generated.
      The process itself is simply a 2D boolean array. We simply draw on that array like we would in a bitmap using traditional image manipulation algorithms.
      Once the array is set, then we simply add a given prop for each true cell of the array 
      We then finally remove every props that are either outside its room or obstructing an entry/exit point.
      Right now, only two types of props can be generated, although the algorithm itself is kinda flexible.
    • By Jreal
      How could I animate a model that has been created from high-fidelity scans with blend shape-based facial rigs?
      Should I find a set of Unity|Unreal plug-ins and packages (middleware, libraries, tools, etc...) that separately do speech synthesis, lip sync, cheek movement, eye rolling, etc...?
      I know this is a broad question, but I would appreciate some pointers to help me understand how I can create verbal & non-verbal behaviors in such a model when I open it in Unity|Unreal in order to create a primitive virtual human.
    • By marcus12
      Hello,

      Glad to share that our mobile game: Solbot Energy Rush available on Android and iOS platform got accepted into:

      Indie Prize Showcase at Casual Connect Asia 2018 to be held in November-12 to 14.

      As indies it's a big encouragement for us!
       
      Playstore: https://play.google.com/store/apps/details?id=com.freakoutgames.chromaflyer

      iTunes : https://itunes.apple.com/us/app/solbot-energy-rush/id1368418939?ls=1&mt=8
                                                                                   
    • By jb-dev
      This is a nicer version of the spa room, plants included!
    • By 999PING
      I'm very often facing one small problem when trying to learn some new stuff - hard to choose what to learn next.
      Even if the problem seems to be small it has a very huge impact on the final result I think. And because Game Programming offers so much to learn, I'm always feeling that I'm missing something important and wasting my time learning something not important or unneeded. Or usually, I'm afraid to focus on something specific and huge for a long time, because I think that I'll spend all my time on that particular filed and will not be able to solve another problem.
       
      So I've tried to fit all my thoughts in this questions.
      1) Are you trying to cover all the aspects of Game Programming? Or you trying to focus on some specific aspects like physics, animations, or networking etc.
      2) What is your way to find a new theory or whatever else for your learning process? (Manuals, Courses, Books, Documentation? etc.)
      3) When you trying to learn while practicing, are you search for learning because of a problem that appears, or because you wants to try new things? How do you choose this new thing? And finally, Which of this two approaches was the best for you if any?
       
      Not actually in the scope of the topic, but I'm also very interested to hear your thoughts on this.
      What is Game Programming for you? How would you describe what should Game Programmer able to solve?
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!