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

Create Scriptable Objects with Unity

Sign in to follow this  
Vivek Tank

741 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 Sergey-Kh
      I'm taking my first steps in programming with Direct3D. I have a very basic pipeline setup, and all I want to get from it is an antialiased smooth image. But I get this:

      First, I can't get rid of stair effect though I have 4x MSAA enabled already in my pipeline (DXGI_SAMPLE_DESC::Count is 4 and Quality is 0): 

      And second, I get this noisy texturing though I have mipmaps generated and LINEAR filtering set in the sampler state.

      Am I missing something or doing wrong? I would appreciate any advice on that.
      Here is my code:
      1) Renderer class:
      2) Vertex shader:
      3) Pixel shader:
      Thank you in advance!
    • By NeoRetro
      Hi -
      I'm a game designer, artist, and game content creator who's been working in the industry on/off for many years.  My work has been primarily on PC and mobile puzzle and action games (Here's an oooold article:  https://www.gamasutra.com/view/feature/130053/breaking_down_breakout_system_and_.php)
       
      I've decided to develop one of my prototypes into a game.  Closest description would be a mashup of Mario Brothers, Mount Your Friends and Cut the Rope.  Single or local multiplayer.  Unity 2D.   
       
      When I began this project in my spare time a few years ago, it was a series of paper and visual prototypes and there were many unknowns.  Since then I've been lucky enough to have pitched the design to a university game incubator in 2017 and have it accepted and developed as a capstone project through Fall/Spring semesters (won best-project award).  This has reduced the unknowns dramatically.  I've also refined and evolved the theme and art style.  Thus my decision to proceed with developing the prototype into a game. 
       
      I've done level scripting in Lua and Objective C, but I don't really have the coding chops to proceed on my own.  Thus I'm looking for an experienced developer with numerous games and prototypes under their belt (bonus points for "2D physics-thing" prototypes and games).  Ideally several years of Unity C# work.  Ideally based in the U.S. since I'm on the east coast. 
       
      This would be a variable amount of revenue share based on contribution (anything from: 4-16 hours per week for a ~12 month duration).  If you're local, there's the possibility of other types of compensation as well (free meals, computer test equipment, etc).  I estimate project completion Sep-Dec 2019. 
       
      I'll provide A TON of specifics for serious inquiries in the form of a brief screenshare walkthrough and short design pitchbook.
      Start would be in early September.
       
      ***Please message me on gamedev.net***
      ***Please include the usual details required to determine qualifications/experience***
      ***Please be over 18***
       
      THANKS FOR READING!
    • By MoreLion
      3D Artists And Unity Programmers For Doom Like Shooter
      Game:ROGUE
      Studio:Rebound Entertainment
      Current Team:3
      Payment:Rev-Share Or Kickstarter
      Programming Requirements:
      - Must Know And Have Experience With Unity And Know C#
      - Must Be Able To Spend 5 To 12 hours a week on the project
      - Must Be Older Than 15
      3D Artist Requirements:
      - Be Able To Model, Animate, Create 3D Monsters And Characters Or Rig (Must Have at least one of these)
      - Must Be Able To Spend 5 To 12 hours a week on the project
      - Must Be Older Than 15
      Project Description:
      You are on the ESL (The Elementary Space Lab). You wake not knowing what has happened, you soon learn that a experimental AI Has gone rogue and created beasts and monsters to kill anything in its path. Now, you know what your mission is.
      If You Are Interested DM Me on discord at thathuman44#4207 or email me at oneriot3@gmail.com
    • By jb-dev
      This is a picture of a yet to be completed bank. The idea is to generate simple geometries to fill the space between the floor and the ceiling. It's done like that because I can set the wall height of the generated level on the fly, so I need something generic and flexible.
    • By Lucas Strain
      Hey there im looking to make a good 2d dark storied game with unity.
      Im looking for:
      Programmers
      Artists
      Recruiters
      Story Writers
      If you are interested contact me at heartachegamers@gmail.com
×

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!