当前位置:网站首页>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);
}
}
}
边栏推荐
- U盘的文件无法删除文件怎么办?Win11无法删除U盘文件解决教程
- boundary IoU 的计算方式
- Solutions for unexplained downtime of MySQL services
- 如何快速体验OneOS
- GWT module may need to be (RE) compiled reduce - GWT module may need to be (RE) compiled reduce
- 344. Reverse String. Sol
- FBO and RBO disappeared in webgpu
- Analysis of the problem that the cookie value in PHP contains a plus sign (+) and becomes a space
- Binary tree (II) -- code implementation of heap
- Alternating merging strings of leetcode simple questions
猜你喜欢
Metaverse ape received $3.5 million in seed round financing from negentropy capital
opencv 判断点在多边形内外
A substring with a length of three and different characters in the leetcode simple question
Cobaltstrike builds an intranet tunnel
谷歌地图案例
[groovy] groovy dynamic language features (automatic type inference of function arguments in groovy | precautions for function dynamic parameters)
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
如何快速体验OneOS
Concurrency control of performance tuning methodology
Metaverse ape ape community was invited to attend the 2022 Guangdong Hong Kong Macao Great Bay metauniverse and Web3.0 theme summit to share the evolution of ape community civilization from technology
随机推荐
Nacos 的安装与服务的注册
数据泄露怎么办?'华生·K'7招消灭安全威胁
Binary tree (III) -- heap sort optimization, top k problem
What changes has Web3 brought to the Internet?
QT creator 7-cmake update
database mirroring
MySQL服务莫名宕机的解决方案
元宇宙中的三大“派系”
[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)
Sub total of Pico development
Text组件新增内容通过tag_config设置前景色、背景色
The difference between MVVM and MVC
Common interview questions of redis factory
Some tutorials install the database on ubantu so as not to occupy computer memory?
Solutions for unexplained downtime of MySQL services
Request preview display of binary data and Base64 format data
Golang writes the opening chapter of selenium framework
344. Reverse String. Sol
科技云报道荣膺全球云计算大会“云鼎奖”2013-2022十周年特别贡献奖
Matlab draws a cute fat doll