Unity 6.3
0 онлайн 3 гостей 3 в системе
Вход

PlayerLoop

класс в UnityEngine.LowLevel

Выполнено в:UnityEngine.CoreModule

Описание

Предоставляет статические методы для получения и изменения цикла Player в Unity.

Цикл Player представляет собой полный набор обновлений для различных основных систем, которые запускаются на каждой итерации основного цикла исполнения приложения Unity. PlayerLoop класс нельзя инстанцировать: это вспомогательный класс со статическими методами для получения и изменения цикла Player, который представлен как PlayerLoopSystem.

Используйте комбинацию этих методов для настройки цикла проигрывателя. Вы можете использовать PlayerLoop.GetDefaultPlayerLoop для получения цикла Player по умолчанию в качестве PlayerLoopSystem, в соответствии с которыми другие случаи PlayerLoopSystem являются вложенными как PlayerLoopSystem.subSystemList. Вы можете изменить это PlayerLoopSystem или создать свой собственный и предоставить его в качестве параметра для PlayerLoop.SetPlayerLoop заменить цикл проигрывателя по умолчанию на пользовательский. Затем вы можете использовать PlayerLoop.GetCurrentPlayerLoop для получения и внесения дополнительных изменений в текущую петлю Player.

Дополнительные ресурсы: PlayerLoopSystem.

using System.Collections.Generic;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
using UnityEngine;
using System.Text;

// Insert a custom update at a specified point (after an existing update phase) in the Player Loop and print the result.

public class MyCustomUpdate { } // Empty class to use as a type identifier for the custom update

public static class CustomLoop { //Run this method on runtime initialization [RuntimeInitializeOnLoadMethod] private static void AppStart() { // Retrieve the default Player loop system. Get the current loop instead if the default was already modified previously. var defaultLoop = PlayerLoop.GetDefaultPlayerLoop();

// Create a custom update system var myCustomUpdate = new PlayerLoopSystem { subSystemList = null, updateDelegate = CustomUpdate, type = typeof(MyCustomUpdate) }; // Add the custom update system after the PreLateUpdate phase in the Player Loop var loopWithCustomUpdate = InsertSystemAfter<PreLateUpdate>(in defaultLoop, myCustomUpdate); PlayerLoop.SetPlayerLoop(loopWithCustomUpdate);

// Print the current Player loop to verify the custom update was added StringBuilder sb = new(); RecursivePlayerLoopPrint(PlayerLoop.GetCurrentPlayerLoop(), sb, 0); Debug.Log(sb.ToString()); }

private static PlayerLoopSystem InsertSystemAfter<T>(in PlayerLoopSystem loopSystem, PlayerLoopSystem newSystem) where T : struct { // Create a new root PlayerLoopSystem PlayerLoopSystem newPlayerLoop = new() { loopConditionFunction = loopSystem.loopConditionFunction, type = loopSystem.type, updateDelegate = loopSystem.updateDelegate, updateFunction = loopSystem.updateFunction }; // Create a new list to populate with subsystems, including the custom system List<PlayerLoopSystem> newSubSystemList = new();

//Iterate through the subsystems in the existing loop we passed in and add them to the new list if (loopSystem.subSystemList != null) { for (var i = 0; i < loopSystem.subSystemList.Length; i++) { newSubSystemList.Add(loopSystem.subSystemList[i]); // If the previously added subsystem is of the type to add after, add the custom system if (loopSystem.subSystemList[i].type == typeof(T)) { newSubSystemList.Add(newSystem); } } }

newPlayerLoop.subSystemList = newSubSystemList.ToArray(); return newPlayerLoop; }

//Custom update function that will be called in the Player Loop private static void CustomUpdate() { Debug.Log("Custom update running!"); }

private static void RecursivePlayerLoopPrint(PlayerLoopSystem playerLoopSystem, StringBuilder sb, int depth) { if (depth == 0) { sb.AppendLine("ROOT NODE"); } else if (playerLoopSystem.type != null) { for (int i = 0; i < depth; i++) { sb.Append("\t"); } sb.AppendLine(playerLoopSystem.type.Name); } if (playerLoopSystem.subSystemList != null) { depth++; foreach (var s in playerLoopSystem.subSystemList) { RecursivePlayerLoopPrint(s, sb, depth); } depth--; } } }

Статические методы

Метод Описание
GetCurrentPlayerLoopВозвращает систему циклов Player, представляющую текущий порядок обновления всех систем движка в Unity.
GetDefaultPlayerLoopВозвращает систему циклов Player, представляющую порядок обновления по умолчанию всех систем движка в Unity.
SetPlayerLoopУстановить новый пользовательский порядок обновления для всех систем двигателя в Unity.