Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Question Qustion about scriptable objects

Discussion in 'Scripting' started by miccalisto, Mar 19, 2023.

  1. miccalisto

    miccalisto

    Joined:
    Feb 20, 2018
    Posts:
    28
    If I have a scriptable object and some instances of gameobjects with a script use this scriptable object, then does this mean whenever one changes value in scriptable object it changes the value in all the classes that use this object?

    For example I have a scriptable object called PlayerResources and there are some variables like wood.
    Then I have a player instance that have an attribute PlayerResources resources. Some methoed do stuff like "add wood to the player", so resources.wood += 10. But when this function is invoked, it changes the wood property in all the Player instances, right?
    If so, even after watching a few tutorials, I still don't see how scriptableobjects are really usefull except a few hardcoded constant field properties.
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    4,023
    The main use of scriptable objects is immutable bags of data. They're great for this, especially when you need many instances of the same 'thing' with varying data.

    However, yes, as you've noticed multiple references to the same asset mean any changes to said scriptable object are seen by everything.

    However don't see this as a downside, it's just a property of their behaviour you can take advantage of. I have my cases where I use this behaviour to 'transmit' data across scenes.

    If it doesn't work in your situation, you just need a different solution. Just use a little imagination.
     
    Bunny83 likes this.
  3. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    907
    You can also duplicate scriptable objects with Instantiate, like you can any prefab or game object. This way you can e.g. create template scriptable object assets and then instantiate and modify them. You do need to be careful about not modifying the original asset or forgetting to instantiate before applying some changes. Sometimes, keeping the "template" scriptable object unchanged and copying/storing the changes in a regular class or component might make more sense.
     
    Bunny83 likes this.