当前位置:网站首页>Usage Summary of scriptable object in unity
Usage Summary of scriptable object in unity
2022-07-05 22:28:00 【M.JH】
Scriptable Object
One . What is? Scriptable Object?
A resource file used to store data , Like JSON、XML、 Storage files such as text files , Can be used to store data . But here he doesn't need to read the file again at the beginning , like JSON At the beginning of the game , We need to load JSON The data in the file , We need to read this file , Then assign values to objects . He can use the data directly . Because it is a resource file , So it has the characteristics of resource files .
Two .Scriptable Object What can you do with it ?
1. replace enum
Enum The shortcomings of : The code must be changed , Inconvenient to delete or modify , No more data can be stored
Usage is as follows
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName ="TabSO",menuName ="ScriptableObject/NewTab",order = 1 )]
public class TabSO : ScriptableObject
{
// It can contain more data , Information
}
When we need a new logo , Create and name a SO that will do
public class PlayerSo : MonoBehaviour
{
[SerializeField] TabSO myType;
[SerializeField] TabSO t1;
[SerializeField] TabSO t2;
// Start is called before the first frame update
void Start()
{
if (t1 == myType)
{
Debug.Log("Fire");
}
if (t2 == myType)
{
Debug.Log("Go");
}
}
}

2. As a data container
reason : Friendly to designers , Yes Git friendly , Can be monitored elsewhere , Convenient for packing and transportation
Data monitoring : example . Player's HP And UI Blood bar pass Scriptable Object decoupling
The configuration file : example . Basic attributes of player enemies
3. Extended editor
If the default content is not enough to meet our requirements , You can customize the extension
example : We created a SO, It carries AudioClip, We plan to click play on the editor
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Scriptable Object/NewAudioSO",order =1)]
public class AudioSO : ScriptableObject
{
public AudioClip[] clips;
[Range(0f, 1f)] public float minVolume;
[Range(0f, 1f)] public float maxVolume;
[Range(-2f, 2f)] public float minPitch;
[Range(-2f, 2f)] public float maxPitch;
public void Play(AudioSource source)
{
if (clips.Length <= 0)
return;
source.clip = clips[Random.Range(0,clips.Length)];
source.volume = Random.Range(minVolume, maxVolume);
source.pitch = Random.Range(minPitch, maxPitch);
source.Play();
}
}
We need to create a script , For this ScriptObject service
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
[CustomEditor(typeof(AudioSO))] // Declare which class you are serving
public class AudioSOEditor : Editor
{
// The goal of the service
private AudioSO _target;
private AudioSource _previewAudioSource;
private void OnEnable()
{
_target = target as AudioSO;
// Create a hidden AudioSource
_previewAudioSource = EditorUtility.CreateGameObjectWithHideFlags(
"AudioPreview",HideFlags.HideAndDontSave,typeof(AudioSource)).GetComponent<AudioSource>();
}
// because _previewAudioSource yes HideAndDontSave, So in OnDisable It must be destroyed
private void OnDisable()
{
DestroyImmediate(_previewAudioSource);
}
//OnInspectorGUI Create a button to play it
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
// Add a button on the original basis
if(GUILayout.Button("PreviewAudio"))
{
_target.Play(_previewAudioSource);
}
}
}
Now let's click on the newly created PreviewAudio Press the button to play the sound of firing
4. hold ScriptObject Use it as an event
First of all, we need a bridge ScriptObject
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[CreateAssetMenu(menuName ="EventsSO/Event Channel")]
public class EventSO : ScriptableObject
{
public UnityAction action;
public void Raise()
{
action?.Invoke();
}
}
The sender and receiver of the event have one EventSO Field , Store new SO
The receiver of the event is SO Internal action Add event
public class Test : MonoBehaviour
{
[SerializeField] EventSO eso;
void print()
{
Debug.Log("Button Clicked ");
}
private void Start()
{
eso.action += print;
}
private void OnDisable()
{
eso.action -= print;
}
}
// The sender of the event
public class NewButtonScript : MonoBehaviour
{
Button b;
[SerializeField] EventSO eso;
// Start is called before the first frame update
void Start()
{
b = this.GetComponent<Button>();
if (b == null)
Debug.LogError(" Not found Button");
b.onClick.AddListener(bOnclick);
}
private void OnDisable()
{
b.onClick.RemoveAllListeners();
}
void bOnclick()
{
eso.Raise();
}
}
5.RuntimeSet
example : When there is n An enemy , After one of them died , Other enemies need to do something ( For example, rush to the place of death )
The original way : Create a singleton class , Contains a List Field , Register all enemies , When an enemy dies , Delete it and traverse List All enemies in call behavior functions
ScriptObject practice : Create a SO, It contains a List Field , Add functionality , Delete function , And traverse all enemies to call behavioral function , In this way, we don't need to create a singleton and load the script into the scene .
[CreateAssetMenu(fileName = "RuntimeSetSo",menuName = "ScriptableObjects/RuntimeSetSo",order = 1)]
public class RuntimeSetSo:ScriptableObject
{
public List<Enemy> _ListEnemys = new List<Enemy>();
public Add(Enemy enemy)
{
if(!_ListEnemys.Contains(enemy))
_ListEnemys.Add(enemy);
}
public Remove(Enemy enemy)
{
if(_ListEnemys.Contains(enemy))
_ListEnemys.Remove(enemy);
}
//---- Traverse all enemies except the dead enemy , And perform a certain behavior
public void OnEnemyDie(Enemy enemy,Vector3 location)
{
Remove(enemy);
foreach(var _enemy in _ListEnemys)
{
_enemy.GotoLocation(location);
}
}
}
public class Enemy:MonoBehaviour
{
[SerializeField] private RuntimeSetSo runtimeSetSo;
private void Start()
{
if(runtimeSetSo!=null)
{
runtimeSetSo.Add(this);
}
}
private void Update()
{
if(this.Die())
{
runtimeSetSo.OnEnemyDie(this,this.transform.position);
}
}
}
边栏推荐
- 如何開發引入小程序插件
- The code generator has deoptimised the styling of xx/typescript.js as it exceeds the max of 500kb
- Technology cloud report won the special contribution award for the 10th anniversary of 2013-2022 of the "cloud Ding Award" of the global cloud computing conference
- Solutions for unexplained downtime of MySQL services
- 點到直線的距離直線的交點及夾角
- 70. Climbing Stairs. Sol
- [error record] file search strategy in groovy project (src/main/groovy/script.groovy needs to be used in the main function | groovy script directly uses the relative path of code)
- Form artifact
- Win11运行cmd提示“请求的操作需要提升”的解决方法
- 元宇宙中的三大“派系”
猜你喜欢

Oracle hint understanding

ESP32 hosted

实战:fabric 用户证书吊销操作流程

Nanjing: full use of electronic contracts for commercial housing sales

Storage optimization of performance tuning methodology

Livelocks and deadlocks of concurrency control

Win11 runs CMD to prompt the solution of "the requested operation needs to be promoted"

元宇宙中的三大“派系”

How can Bluetooth in notebook computer be used to connect headphones

Win11缺少dll文件怎么办?Win11系统找不到dll文件修复方法
随机推荐
Wonderful review of the digital Expo | highlight scientific research strength, and Zhongchuang computing power won the digital influence enterprise award
Talking about MySQL index
Distributed resource management and task scheduling framework yarn
The difference between MVVM and MVC
Comment développer un plug - in d'applet
数据泄露怎么办?'华生·K'7招消灭安全威胁
Win11 runs CMD to prompt the solution of "the requested operation needs to be promoted"
Nanjing: full use of electronic contracts for commercial housing sales
解决thinkphp启动时“No input file specified”的问题
Kubernetes Administrator certification (CKA) exam notes (IV)
IIC bus realizes client device
如何开发引入小程序插件
Storage optimization of performance tuning methodology
[agc009e] eternal average - conclusion, DP
Nacos 的安装与服务的注册
The statistics of leetcode simple question is the public string that has appeared once
从 1.5 开始搭建一个微服务框架——日志追踪 traceId
Learning of mall permission module
All expansion and collapse of a-tree
Oracle hint understanding









