unity Domain Reload & scene Reload 静态变量重置

关闭 Domain Reload 选项后,c#的静态变量在下次运行时不会怎么重置,需要手动添加重置代码。使用下面的属性设置重置变量函数。

using UnityEngine;

public class StaticCounterExampleFixed : MonoBehaviour
{
    static int counter = 0;

//此属性
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
    static void Init()
    {
            Debug.Log("Counter reset.");
            counter = 0;   
    }

    // Update is called once per frame
    void Update()
    {
            if (Input.GetButtonDown("Jump"))
            {
                counter++;
                Debug.Log("Counter: " + counter);
            }
    }
}

Asset Import Order

If you are scripting using the AssetDatabase class, it’s important to understand how the order of Unity’s import processes can affect your scripts, otherwise you may get unexpected results. The order is as follows:

  1. Import Script Assets (.cs, .dll, .asmdef files)
  2. Compilation
  3. Domain reload
  4. InitializeOnLoad callback
  5. Import all other assets

Unity - Manual: Details of disabling Domain and Scene Reload

Unity - Manual: Special folder names

你可能感兴趣的:(unity,游戏引擎)