A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.unity3d.com/Manual/sprite/../sprite/../class-ScriptableObject.html below:

Unity - Manual: ScriptableObject

ScriptableObjectSwitch to Scripting

ScriptableObject is a serializable Unity type derived from UnityEngine.Object. As with MonoBehaviour, you don’t instantiate the ScriptableObject class directly but create your own custom C# classes that derive from it, and then create instances of those custom classes, usually through the Assets menu in the Unity Editor.

All instances of classes derived from ScriptableObject are commonly referred to as ScriptableObjects. Unlike MonoBehaviours, ScriptableObjects are not attached to GameObjectsThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary
as components but exist in the project as assetsAny media or data that can be used in your game or project. An asset may come from a file created outside of Unity, such as a 3D Model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
See in Glossary
, independent of GameObjects. Because ScriptableObjects inherit from UnityEngine.Object, you can drag or pick instances of them into fields in the InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary
.

The main value of a ScriptableObject is as a data store, but they can also define behavior. A common use for ScriptableObjects is as a container for shared data used by multiple objects at runtime, which can reduce a project’s memory usage by avoiding copies of values.

For example, if your project has a prefabAn asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary
that stores unchanging data in attached MonoBehaviour scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary
, then every new instance of the prefab gets its own copy of the data. Instead of duplicating data like this, you can use a ScriptableObject to store the data and then access it by reference from all the prefabs. This means that there is one copy of the data in memory.

The main use cases for ScriptableObjects are:

For a complete reference of every member of the ScriptableObject class, refer to the ScriptableObject script reference.

Create a ScriptableObject

To create a new ScriptableObject script, the quickest way is to use the predefined ScriptableObject script template from the Assets menu in one of the following ways:

This gives you a custom base class that inherits from UnityEngine.ScriptableObject. You can then use the CreateAssetMenu attribute to create instances of this class, each of which becomes an asset in your project.

Example: Instantiate prefabs with a ScriptableObject

The following example uses a ScriptableObject to store data defined at authoring time that is later used to determine where to instantiate prefabs at runtime. First, create the following base ScriptableObject class in your Assets folder:

// Define a base ScriptableObject class called SpawnManagerScriptableObject
using UnityEngine;

// Use the CreateAssetMenu attribute to allow creating instances of this ScriptableObject from the Unity Editor.
[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)]
public class SpawnManagerScriptableObject : ScriptableObject
{
    public string prefabName;

    public int numberOfPrefabsToCreate;
    public Vector3[] spawnPoints;
}

With the previous script in your Assets folder, create an instance of your new ScriptableObject by navigating to Assets > Create > ScriptableObjects > SpawnManagerScriptableObject. Give your new ScriptableObject instance a meaningful name and alter the values. To use these values at runtime, you need to create a new script that references your ScriptableObject, in this case, a SpawnManagerScriptableObject as follows:

using UnityEngine;

public class Spawner : MonoBehaviour
{
    // The GameObject to instantiate.
    public GameObject entityToSpawn;

    // An instance of the ScriptableObject defined above.
    public SpawnManagerScriptableObject spawnManagerValues;

    // This will be appended to the name of the created entities and increment when each is created.
    int instanceNumber = 1;

    void Start()
    {
        SpawnEntities();
    }

    void SpawnEntities()
    {
        int currentSpawnPointIndex = 0;

        for (int i = 0; i < spawnManagerValues.numberOfPrefabsToCreate; i++)
        {
            // Creates an instance of the prefab at the current spawn point.
            GameObject currentEntity = Instantiate(entityToSpawn, spawnManagerValues.spawnPoints[currentSpawnPointIndex], Quaternion.identity);

            // Sets the name of the instantiated entity to be the string defined in the ScriptableObject and then appends it with a unique number. 
            currentEntity.name = spawnManagerValues.prefabName + instanceNumber;

            // Moves to the next spawn point index. If it goes out of range, it wraps back to the start.
            currentSpawnPointIndex = (currentSpawnPointIndex + 1) % spawnManagerValues.spawnPoints.Length;

            instanceNumber++;
        }
    }
}

Note: The script file must have the same name as the class.

Attach the previous script to a GameObject in your SceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary
. Then, in the Inspector, populate the Spawn Manager Values field with the new .asset instance of SpawnManagerScriptableObject that you set up.

Set the Entity To Spawn field to any prefab in your Assets folder, then enter Play mode. The prefab you referenced in the Spawner instantiates using the values you set in the SpawnManagerScriptableObject instance.

If you’re working with ScriptableObject references in the Inspector, you can double click the reference field to open the Inspector for your ScriptableObject. You can also create a custom Inspector for your type to help manage the data that it represents.

Saving changes to ScriptableObject data

In the Unity Editor, you can save data to ScriptableObjects in Edit mode and Play mode. In a standalone Player at runtime, you can only read saved data from the ScriptableObject assets. When you use Editor authoring tools or the Inspector to modify a ScriptableObject asset, Unity automatically writes the data to disk and it persists between Editor sessions.

However, Unity doesn’t automatically save changes to a ScriptableObject made via script in Edit mode. In these cases, you must call EditorUtility.SetDirty on the ScriptableObject to ensure Unity’s serialization system recognizes it as changed and saves the changes to disk. Without this, changes may not persist between Editor sessions.

Suppose you have the following ScriptableObject called GameSettings:

using UnityEngine;

[CreateAssetMenu]
public class GameSettings : ScriptableObject
{
    public int highScore;
}

If you have an Editor script that changes the highScore value, make sure to include a call to EditorUtility.SetDirty in your code as follows:

// Save this as Assets/Editor/GameSettingsEditor.cs
using UnityEditor;
using UnityEngine;

public class GameSettingsEditor : EditorWindow
{
    GameSettings settings;

    [MenuItem("Window/Game Settings Editor")]
    public static void ShowWindow()
    {
        GetWindow<GameSettingsEditor>("Game Settings Editor");
    }

    void OnGUI()
    {
        settings = EditorGUILayout.ObjectField("Settings", settings, typeof(GameSettings), false) as GameSettings;
        if (settings == null) return;

        EditorGUILayout.LabelField("High Score", settings.highScore.ToString());

        if (GUILayout.Button("Increase High Score"))
        {
            settings.highScore += 10;

            // Call SetDirty to ensure the change is saved
            EditorUtility.SetDirty(settings);
            // Optional: AssetDatabase.SaveAssets(); // To save immediately
        }
    }
}

Without the call to SetDirty, the change to highScore appears in memory, but if you close and reopen the Editor the value reverts to its previous value.

Additional resources

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4