我有一个这样的脚本对象
并且在播放模式期间我调整当前健康值
当我存在播放模式时,CurrentHealthValue=80不会返回到40,我知道这是ScriptableObject的工作方式,但我想知道是否有任何方法可以在存在播放模式后自动返回40原始值,而不是在启动新播放模式前手动将值重写为40。
t9aqgxwy1#
你实际上可以通过subscribe来改变你的ScriptableObject类的编辑器的播放模式状态.下面是一个小例子来说明:
subscribe
ScriptableObject
#if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; namespace SomeNameSpace { [CreateAssetMenu(fileName = "TestScriptableObject", menuName = "ScriptableObjects/")] public class TestScriptableObject : ScriptableObject { private const int DefaultHealth = 120; public int Health = 60; private void OnEnable() { #if UNITY_EDITOR // Subscribe for the "event" EditorApplication.playModeStateChanged += LogPlayModeState; #endif } private void OnDisable() { #if UNITY_EDITOR // Don't forget to unsubscribe EditorApplication.playModeStateChanged -= LogPlayModeState; #endif } #if UNITY_EDITOR private void LogPlayModeState(PlayModeStateChange state) { if (state == PlayModeStateChange.ExitingPlayMode) { // Reset / Set the default health value Health = DefaultHealth; } } #endif } }
u91tlkcl2#
在这种情况下,我使用EditorJsonUtility将初始对象的副本保存为JSON,然后在完成后覆盖目标对象。在这种情况下,代码类似于:
EditorJsonUtility
using UnityEngine; #if UNITY_EDITOR // makes intent clear. using UnityEditor; #endif [CreateAssetMenu ( fileName = "TestScriptableObject", menuName = "TestScriptableObject", order = 1 )] public class TestScriptableObject : ScriptableObject { public int Field1; public float Field2; public Vector2 Field3; #if UNITY_EDITOR [SerializeField] private bool _revert; private string _initialJson = string.Empty; #endif private void OnEnable ( ) { #if UNITY_EDITOR EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; EditorApplication.playModeStateChanged += OnPlayModeStateChanged; #endif } #if UNITY_EDITOR private void OnPlayModeStateChanged ( PlayModeStateChange obj ) { switch ( obj ) { case PlayModeStateChange.EnteredPlayMode: _initialJson = EditorJsonUtility.ToJson ( this ); break; case PlayModeStateChange.ExitingPlayMode: EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; if ( _revert ) EditorJsonUtility.FromJsonOverwrite ( _initialJson, this ); break; } } #endif }
2条答案
按热度按时间t9aqgxwy1#
你实际上可以通过
subscribe
来改变你的ScriptableObject
类的编辑器的播放模式状态.下面是一个小例子来说明:u91tlkcl2#
在这种情况下,我使用
EditorJsonUtility
将初始对象的副本保存为JSON,然后在完成后覆盖目标对象。在这种情况下,代码类似于: