我对Unity ScrollRect/ScrollView优化/性能的了解



ScrollView的性能是一个真正的拖累(明白吗?(,尤其是在移动平台上。我经常发现自己的帧速率低于15帧,这让用户体验感到震撼和乏味。经过大量的研究和测试,我编制了一份清单,以大幅提高性能。我现在至少可以获得30帧/秒,大部分CPU时间分配给WaitForTargetFPS

我希望这能帮助任何在这方面遇到麻烦的人。优化解决方案很难找到。请随意使用和修改我的任何代码。

ONE: .GetComponent<>((调用效率低下,尤其是在编辑器之外。避免在任何类型的Update((方法中使用这些。

TWO: OnValueChanged((在拖动ScrollView的每一帧时调用。因此,它在某种意义上等同于Update((,因此应避免使用.GetComponent<>((调用。

THREE:每当画布上的任何元素发生更改时,整个Canvas都必须重新生成其批。这种操作可能非常昂贵。因此,建议将UI元素拆分为至少两个画布,一个用于很少或从未更改的元素,另一个用于经常更改的元素。

每当ScrollView滚动时,其所在的整个画布都会变脏。因此,建议您将每个ScrollView都放在一个单独的画布上。

Unity Canvas重建说明:https://unity3d.com/learn/tutorials/topics/best-practices/fill-rate-canvases-and-input?playlist=30089

FOUR: EventSystem.Update((处理场景中的输入检测,使用光线投射在层次结构中进行过滤,以找到接受此输入的组件。因此,这些计算仅在与场景交互时进行,例如滚动ScrollView时。从图形和文本中删除不必要的RaycastTarget属性将缩短处理时间。这可能不会有太大的区别,但如果你不够小心,对象可能会使输入处理时间增加。

FIVE:使用任何类型的遮罩组件,即使是RectMask2DScrollView中的所有对象都会被批处理和渲染。如果ScrollView中有很多元素,建议您使用某种池化解决方案。应用商店里有很多这样的应用。

Unity Pooling解释:https://unity3d.com/learn/tutorials/topics/best-practices/optimizing-ui-controls

但是,如果您的项目与此不兼容,需要持久元素,我建议您隐藏屏幕外的对象以减少性能开销Transform.SetParent((GameObject.SetActive((都是资源密集型方法,而是将CanvasGroup组件附加到每个元素,并调整alpha值以实现相同的效果。

这里有一个静态脚本,用于检测对象是否可见,并相应地设置alpha:

using UnityEngine;
using UnityEngine.UI;
public class ScrollHider : MonoBehaviour {
static public float contentTop;
static public float contentBottom;

static public bool HideObject(GameObject givenObject, CanvasGroup canvasGroup, float givenPosition, float givenHeight) {
if ((Mathf.Abs(givenPosition) + givenHeight > contentTop && Mathf.Abs(givenPosition) + givenHeight < contentBottom) || (Mathf.Abs(givenPosition) > contentTop && Mathf.Abs(givenPosition) < contentBottom)) {
if (canvasGroup.alpha != 1) {
canvasGroup.alpha = 1;
}
return true;
} else {
if (canvasGroup.alpha != 0) {
canvasGroup.alpha = 0;
}
return false;
}
}
static public void Setup(Scroll givenScroll) {
contentTop = (1 - givenScroll.verticalNormalizedPosition) * (givenScroll.content.rect.height - givenScroll.viewport.rect.height);
contentBottom = contentTop + givenScroll.viewport.rect.height;
}
}

SIX:Unity内置的ScrollRect组件允许广泛的模块化功能。然而,就性能而言,它可能明显比你自己写的慢。这里有一个Scroll脚本,它实现了相同的目的,但只支持Unity的ScrollRect的垂直、夹紧和惯性特性。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class Scroll : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler, IScrollHandler {
private Camera mainCamera;
private RectTransform canvasRect;
public RectTransform viewport;
public RectTransform content;
private Rect viewportOld;
private Rect contentOld;
private List<Vector2> dragCoordinates = new List<Vector2>();
private List<float> offsets = new List<float>();
private int offsetsAveraged = 4;
private float offset;
private float velocity = 0;
private bool changesMade = false;
public float decelration = 0.135f;
public float scrollSensitivity;
public OnValueChanged onValueChanged;

[System.Serializable]
public class OnValueChanged : UnityEvent { }
[HideInInspector]
public float verticalNormalizedPosition
{
get
{
float sizeDelta = CaculateDeltaSize();
if (sizeDelta == 0) {
return 0;
} else {
return 1 - content.transform.localPosition.y / sizeDelta;
}
}
set
{
float o_verticalNormalizedPosition = verticalNormalizedPosition;
float m_verticalNormalizedPosition = Mathf.Max(0, Mathf.Min(1, value));
float maxY = CaculateDeltaSize();
content.transform.localPosition = new Vector3(content.transform.localPosition.x, Mathf.Max(0, (1 - m_verticalNormalizedPosition) * maxY), content.transform.localPosition.z);
float n_verticalNormalizedPosition = verticalNormalizedPosition;
if (o_verticalNormalizedPosition != n_verticalNormalizedPosition) {
onValueChanged.Invoke();
}
}
}
private float CaculateDeltaSize() {
return Mathf.Max(0, content.rect.height - viewport.rect.height); ;
}

private void Awake() {
mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
canvasRect = transform.root.GetComponent<RectTransform>();
}
private Vector2 ConvertEventDataDrag(PointerEventData eventData) {
return new Vector2(eventData.position.x / mainCamera.pixelWidth * canvasRect.rect.width, eventData.position.y / mainCamera.pixelHeight * canvasRect.rect.height);
}
private Vector2 ConvertEventDataScroll(PointerEventData eventData) {
return new Vector2(eventData.scrollDelta.x / mainCamera.pixelWidth * canvasRect.rect.width, eventData.scrollDelta.y / mainCamera.pixelHeight * canvasRect.rect.height) * scrollSensitivity;
}
public void OnPointerDown(PointerEventData eventData) {
velocity = 0;
dragCoordinates.Clear();
offsets.Clear();
dragCoordinates.Add(ConvertEventDataDrag(eventData));
}
public void OnScroll(PointerEventData eventData) {
UpdateOffsetsScroll(ConvertEventDataScroll(eventData));
OffsetContent(offsets[offsets.Count - 1]);
}
public void OnDrag(PointerEventData eventData) {
dragCoordinates.Add(ConvertEventDataDrag(eventData));
UpdateOffsetsDrag();
OffsetContent(offsets[offsets.Count - 1]);
}
public void OnPointerUp(PointerEventData eventData) {
dragCoordinates.Add(ConvertEventDataDrag(eventData));
UpdateOffsetsDrag();
OffsetContent(offsets[offsets.Count - 1]);
float totalOffsets = 0;
foreach (float offset in offsets) {
totalOffsets += offset;
}
velocity = totalOffsets / offsetsAveraged;
dragCoordinates.Clear();
offsets.Clear();
}
private void OffsetContent(float givenOffset) {
float newY = Mathf.Max(0, Mathf.Min(CaculateDeltaSize(), content.transform.localPosition.y + givenOffset));
if (content.transform.localPosition.y != newY) {
content.transform.localPosition = new Vector3(content.transform.localPosition.x, newY, content.transform.localPosition.z);
}
onValueChanged.Invoke();
}
private void UpdateOffsetsDrag() {
offsets.Add(dragCoordinates[dragCoordinates.Count - 1].y - dragCoordinates[dragCoordinates.Count - 2].y);
if (offsets.Count > offsetsAveraged) {
offsets.RemoveAt(0);
}
}
private void UpdateOffsetsScroll(Vector2 givenScrollDelta) {
offsets.Add(givenScrollDelta.y);
if (offsets.Count > offsetsAveraged) {
offsets.RemoveAt(0);
}
}
private void LateUpdate() {
if (viewport.rect != viewportOld) {
changesMade = true;
viewportOld = new Rect(viewport.rect);
}
if (content.rect != contentOld) {
changesMade = true;
contentOld = new Rect(content.rect);
}
if (velocity != 0) {
changesMade = true;
velocity = (velocity / Mathf.Abs(velocity)) * Mathf.FloorToInt(Mathf.Abs(velocity) * (1 - decelration));
offset = velocity;
}
if (changesMade) {
OffsetContent(offset);
changesMade = false;
offset = 0;
}
}
}

一篇不错的文章解释了默认的targetFrameRate可能是scrollView不平滑滚动行为的原因。这可以通过以下方式解决:

Application.targetFrameRate = 60; // or whatever you wish. 60 turned out enough for us

当然,只有解决了性能问题(正如Phedg1很好地解释的那样(,此设置才有效。

相关内容

  • 没有找到相关文章

最新更新