【发布时间】:2022-12-11 07:43:19
【问题描述】:
我是 unity 和 C# 的新手,我对如何保存当前 scrollrect 位置有疑问。 示例:我正在滚动视图,然后移动到另一个场景,然后返回到上一个场景,但是滚动显示的是我移动场景之前的前一个位置,而不是将滚动重置为默认值。
【问题讨论】:
标签: c# unity3d scrollrect
我是 unity 和 C# 的新手,我对如何保存当前 scrollrect 位置有疑问。 示例:我正在滚动视图,然后移动到另一个场景,然后返回到上一个场景,但是滚动显示的是我移动场景之前的前一个位置,而不是将滚动重置为默认值。
【问题讨论】:
标签: c# unity3d scrollrect
可惜你想做的没有现成的,得自己做
当滚动到滚动底部时,你必须保存通过 PlayerPrefs 发送给 DemoCall 的 id,然后当你转到另一个场景并再次返回所选场景时,从它停止的地方调用滚动信息,即你保存的id
编辑
添加Recyclable-Scroll-Rect后,就可以使用这段代码了
using System.Collections.Generic;
using UnityEngine;
using PolyAndCode.UI;
using System.Collections;
public struct ContactTsnif
{
public string id;
}
public class Objx
{
public string id;
}
public class RecyclTsnif : MonoBehaviour, IRecyclableScrollRectDataSource
{
[SerializeField]
RecyclableScrollRect _recycHat;
public GameObject RecyScrHat;
[SerializeField]
public int _dataLenHat;
public int beginning;
private List<ContactTsnif> _contactList = new List<ContactTsnif>();
public List<string> id = new List<string>();
void Start()
{
beginning = PlayerPrefebs.GetInt("Start", 5)// start with 5
GetHat();
}
public void GetHat()
{
_dataLenHat = 0;
_recycHat.DataSource = this;
InitDataHat();
RecyScrHat.GetComponent<RecyclableScrollRect>().Initialize();
}
public void InitDataHat()
{
if (_contactList != null) _contactList.Clear();
for (int i = beginning; i < _dataLenHat;)
{
ContactTsnif obj = new ContactTsnif();
obj.id = id[i];
i++;
_contactList.Add(obj);
}
}
#region DATA-SOURCE
public int GetItemCount()
{
return _contactList.Count;
}
public void SetCell(ICell cell, int index)
{
var item1 = cell as DemoTsnif;
item1.ConfigureCellSor(_contactList[index], index);
}
#endregion
}
演示
using UnityEngine;
using System;
using System.Collections;
public class DemoTsnif : MonoBehaviour, ICell
{
private ContactTsnif _ContactInfo;
private int _cellIndex;
public int id;
public void GetData()
{
}
public void ConfigureCellSor(ContactTsnif contactInfo,int cellIndex)
{
_cellIndex = cellIndex;
_ContactInfo = contactInfo;
id = contactInfo.id;
GetData();
}
}
【讨论】:
你试过读/写 normalizedPosition 吗?
你基本上需要做两件事: 您需要将此脚本附加到包含 ScrollRect 的 GameObject 以保持位置:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems; // Required when using event data
using UnityEngine.UI;
public class DragNotify : MonoBehaviour, IEndDragHandler // required interface when using the OnEndDrag method.
{
//Do this when the user stops dragging this UI Element.
public void OnEndDrag(PointerEventData data)
{
PlayerPrefs.SetFloat("scrollX", this.GetComponent<ScrollRect>().normalizedPosition.x);
}
}
您还需要在初始化 ScrollRect 并应用所需内容后应用 normalizedPosition:
this.transform.Find("Scroll View").GetComponent<ScrollRect>().normalizedPosition = new Vector2(PlayerPrefs.GetFloat("scrollX"), 0F);
【讨论】: