LoopScrollRectBase.cs 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. using UnityEngine.Events;
  2. using UnityEngine.EventSystems;
  3. using System;
  4. using ET;
  5. using YIUIFramework;
  6. namespace UnityEngine.UI
  7. {
  8. [AddComponentMenu("")]
  9. [DisallowMultipleComponent]
  10. [RequireComponent(typeof(RectTransform))]
  11. /// <summary>
  12. /// A component for making a child RectTransform scroll with reuseable content.
  13. /// </summary>
  14. /// <remarks>
  15. /// LoopScrollRect will not do any clipping on its own. Combined with a Mask component, it can be turned into a loop scroll view.
  16. /// </remarks>
  17. public abstract class LoopScrollRectBase : UIBehaviour,
  18. IInitializePotentialDragHandler,
  19. IBeginDragHandler,
  20. IEndDragHandler,
  21. IDragHandler,
  22. IScrollHandler,
  23. ICanvasElement,
  24. ILayoutElement,
  25. ILayoutGroup
  26. {
  27. //==========LoopScrollRect==========
  28. /// <summary>
  29. /// The scroll data source to fill items.
  30. /// </summary>
  31. [HideInInspector]
  32. [NonSerialized]
  33. public IYIUILoopScrollPrefabAsyncSource prefabSource = null;
  34. /// <summary>
  35. /// The scroll's total count for items with id in [0, totalCount]. Negative value like -1 means infinite items.
  36. /// </summary>
  37. [Tooltip("Total count, negative means INFINITE mode")]
  38. public int totalCount;
  39. /// <summary>
  40. /// [Optional] Helper for accurate size so we can achieve better scrolling.
  41. /// </summary>
  42. [HideInInspector]
  43. [NonSerialized]
  44. public LoopScrollSizeHelper sizeHelper = null;
  45. /// <summary>
  46. /// When threshold reached, we prepare new items outside view. This will be expanded to at least 1.5 * itemSize.
  47. /// </summary>
  48. protected float threshold = 0;
  49. /// <summary>
  50. /// Whether we use down-upsize or right-left direction?
  51. /// </summary>
  52. [Tooltip("Reverse direction for dragging")]
  53. public bool reverseDirection = false;
  54. /// <summary>
  55. /// The first item id in LoopScroll.
  56. /// </summary>
  57. protected int itemTypeStart = 0;
  58. /// <summary>
  59. /// The last item id in LoopScroll.
  60. /// </summary>
  61. protected int itemTypeEnd = 0;
  62. protected abstract float GetSize(RectTransform item, bool includeSpacing = true);
  63. protected abstract float GetDimension(Vector2 vector);
  64. protected abstract float GetAbsDimension(Vector2 vector);
  65. protected abstract Vector2 GetVector(float value);
  66. /// <summary>
  67. /// Direction for LoopScroll. This is a bit confusing with m_Horizontal/m_Vertical.
  68. /// </summary>
  69. protected enum LoopScrollRectDirection
  70. {
  71. Vertical,
  72. Horizontal,
  73. }
  74. protected LoopScrollRectDirection direction = LoopScrollRectDirection.Horizontal;
  75. private bool m_ContentSpaceInit = false;
  76. private float m_ContentSpacing = 0;
  77. protected float m_ContentLeftPadding = 0;
  78. protected float m_ContentRightPadding = 0;
  79. protected float m_ContentTopPadding = 0;
  80. protected float m_ContentBottomPadding = 0;
  81. protected GridLayoutGroup m_GridLayout = null;
  82. protected float contentSpacing
  83. {
  84. get
  85. {
  86. if (m_ContentSpaceInit)
  87. {
  88. return m_ContentSpacing;
  89. }
  90. m_ContentSpaceInit = true;
  91. m_ContentSpacing = 0;
  92. if (m_Content != null)
  93. {
  94. HorizontalOrVerticalLayoutGroup layout1 = m_Content.GetComponent<HorizontalOrVerticalLayoutGroup>();
  95. if (layout1 != null)
  96. {
  97. m_ContentSpacing = layout1.spacing;
  98. m_ContentLeftPadding = layout1.padding.left;
  99. m_ContentRightPadding = layout1.padding.right;
  100. m_ContentTopPadding = layout1.padding.top;
  101. m_ContentBottomPadding = layout1.padding.bottom;
  102. }
  103. m_GridLayout = m_Content.GetComponent<GridLayoutGroup>();
  104. if (m_GridLayout != null)
  105. {
  106. m_ContentSpacing = GetAbsDimension(m_GridLayout.spacing);
  107. m_ContentLeftPadding = m_GridLayout.padding.left;
  108. m_ContentRightPadding = m_GridLayout.padding.right;
  109. m_ContentTopPadding = m_GridLayout.padding.top;
  110. m_ContentBottomPadding = m_GridLayout.padding.bottom;
  111. }
  112. }
  113. return m_ContentSpacing;
  114. }
  115. }
  116. private bool m_ContentConstraintCountInit = false;
  117. private int m_ContentConstraintCount = 0;
  118. protected int contentConstraintCount
  119. {
  120. get
  121. {
  122. if (m_ContentConstraintCountInit)
  123. {
  124. return m_ContentConstraintCount;
  125. }
  126. m_ContentConstraintCountInit = true;
  127. m_ContentConstraintCount = 1;
  128. if (m_Content != null)
  129. {
  130. GridLayoutGroup layout2 = m_Content.GetComponent<GridLayoutGroup>();
  131. if (layout2 != null)
  132. {
  133. if (layout2.constraint == GridLayoutGroup.Constraint.Flexible)
  134. {
  135. Debug.LogWarning("[LoopScrollRect] Flexible not supported yet");
  136. }
  137. m_ContentConstraintCount = layout2.constraintCount;
  138. }
  139. }
  140. return m_ContentConstraintCount;
  141. }
  142. }
  143. /// <summary>
  144. /// The first line in scroll. Grid may have multiply items in one line.
  145. /// </summary>
  146. protected int StartLine
  147. {
  148. get
  149. {
  150. return Mathf.CeilToInt((float)(itemTypeStart) / contentConstraintCount);
  151. }
  152. }
  153. /// <summary>
  154. /// Current line count in scroll. Grid may have multiply items in one line.
  155. /// </summary>
  156. protected int CurrentLines
  157. {
  158. get
  159. {
  160. return Mathf.CeilToInt((float)(itemTypeEnd - itemTypeStart) / contentConstraintCount);
  161. }
  162. }
  163. /// <summary>
  164. /// Total line count in scroll. Grid may have multiply items in one line.
  165. /// </summary>
  166. protected int TotalLines
  167. {
  168. get
  169. {
  170. return Mathf.CeilToInt((float)(totalCount) / contentConstraintCount);
  171. }
  172. }
  173. protected virtual async ETTask<(bool, Bounds, Bounds)> UpdateItems(Bounds viewBounds, Bounds contentBounds)
  174. {
  175. await ETTask.CompletedTask;
  176. return (false, viewBounds, contentBounds);
  177. }
  178. //==========LoopScrollRect==========
  179. /// <summary>
  180. /// A setting for which behavior to use when content moves beyond the confines of its container.
  181. /// </summary>
  182. /// <example>
  183. /// <code>
  184. /// using UnityEngine;
  185. /// using System.Collections;
  186. /// using UnityEngine.UI; // Required when Using UI elements.
  187. ///
  188. /// public class ExampleClass : MonoBehaviour
  189. /// {
  190. /// public ScrollRect myScrollRect;
  191. /// public Scrollbar newScrollBar;
  192. ///
  193. /// //Called when a button is pressed
  194. /// public void Example(int option)
  195. /// {
  196. /// if (option == 0)
  197. /// {
  198. /// myScrollRect.movementType = ScrollRect.MovementType.Clamped;
  199. /// }
  200. /// else if (option == 1)
  201. /// {
  202. /// myScrollRect.movementType = ScrollRect.MovementType.Elastic;
  203. /// }
  204. /// else if (option == 2)
  205. /// {
  206. /// myScrollRect.movementType = ScrollRect.MovementType.Unrestricted;
  207. /// }
  208. /// }
  209. /// }
  210. /// </code>
  211. /// </example>
  212. public enum MovementType
  213. {
  214. /// <summary>
  215. /// Unrestricted movement. The content can move forever.
  216. /// </summary>
  217. Unrestricted,
  218. /// <summary>
  219. /// Elastic movement. The content is allowed to temporarily move beyond the container, but is pulled back elastically.
  220. /// </summary>
  221. Elastic,
  222. /// <summary>
  223. /// Clamped movement. The content can not be moved beyond its container.
  224. /// </summary>
  225. Clamped,
  226. }
  227. /// <summary>
  228. /// Enum for which behavior to use for scrollbar visibility.
  229. /// </summary>
  230. public enum ScrollbarVisibility
  231. {
  232. /// <summary>
  233. /// Always show the scrollbar.
  234. /// </summary>
  235. Permanent,
  236. /// <summary>
  237. /// Automatically hide the scrollbar when no scrolling is needed on this axis. The viewport rect will not be changed.
  238. /// </summary>
  239. AutoHide,
  240. /// <summary>
  241. /// Automatically hide the scrollbar when no scrolling is needed on this axis, and expand the viewport rect accordingly.
  242. /// </summary>
  243. /// <remarks>
  244. /// When this setting is used, the scrollbar and the viewport rect become driven, meaning that values in the RectTransform are calculated automatically and can't be manually edited.
  245. /// </remarks>
  246. AutoHideAndExpandViewport,
  247. }
  248. [Serializable]
  249. /// <summary>
  250. /// Event type used by the ScrollRect.
  251. /// </summary>
  252. public class ScrollRectEvent : UnityEvent<Vector2>
  253. {
  254. }
  255. [SerializeField]
  256. protected RectTransform m_Content; //==========LoopScrollRect==========
  257. /// <summary>
  258. /// The content that can be scrolled. It should be a child of the GameObject with ScrollRect on it.
  259. /// </summary>
  260. /// <example>
  261. /// <code>
  262. /// using UnityEngine;
  263. /// using System.Collections;
  264. /// using UnityEngine.UI; // Required when Using UI elements.
  265. ///
  266. /// public class ExampleClass : MonoBehaviour
  267. /// {
  268. /// public ScrollRect myScrollRect;
  269. /// public RectTransform scrollableContent;
  270. ///
  271. /// //Do this when the Save button is selected.
  272. /// public void Start()
  273. /// {
  274. /// // assigns the contect that can be scrolled using the ScrollRect.
  275. /// myScrollRect.content = scrollableContent;
  276. /// }
  277. /// }
  278. /// </code>
  279. /// </example>
  280. public RectTransform content { get { return m_Content; } set { m_Content = value; } }
  281. [SerializeField]
  282. private bool m_Horizontal = true;
  283. /// <summary>
  284. /// Should horizontal scrolling be enabled?
  285. /// </summary>
  286. /// <example>
  287. /// <code>
  288. /// using UnityEngine;
  289. /// using System.Collections;
  290. /// using UnityEngine.UI; // Required when Using UI elements.
  291. ///
  292. /// public class ExampleClass : MonoBehaviour
  293. /// {
  294. /// public ScrollRect myScrollRect;
  295. ///
  296. /// public void Start()
  297. /// {
  298. /// // Is horizontal scrolling enabled?
  299. /// if (myScrollRect.horizontal == true)
  300. /// {
  301. /// Debug.Log("Horizontal Scrolling is Enabled!");
  302. /// }
  303. /// }
  304. /// }
  305. /// </code>
  306. /// </example>
  307. public bool horizontal { get { return m_Horizontal; } set { m_Horizontal = value; } }
  308. [SerializeField]
  309. private bool m_Vertical = true;
  310. /// <summary>
  311. /// Should vertical scrolling be enabled?
  312. /// </summary>
  313. /// <example>
  314. /// <code>
  315. /// using UnityEngine;
  316. /// using System.Collections;
  317. /// using UnityEngine.UI; // Required when Using UI elements.
  318. ///
  319. /// public class ExampleClass : MonoBehaviour
  320. /// {
  321. /// public ScrollRect myScrollRect;
  322. ///
  323. /// public void Start()
  324. /// {
  325. /// // Is Vertical scrolling enabled?
  326. /// if (myScrollRect.vertical == true)
  327. /// {
  328. /// Debug.Log("Vertical Scrolling is Enabled!");
  329. /// }
  330. /// }
  331. /// }
  332. /// </code>
  333. /// </example>
  334. public bool vertical { get { return m_Vertical; } set { m_Vertical = value; } }
  335. [SerializeField]
  336. private MovementType m_MovementType = MovementType.Elastic;
  337. /// <summary>
  338. /// The behavior to use when the content moves beyond the scroll rect.
  339. /// </summary>
  340. public MovementType movementType { get { return m_MovementType; } set { m_MovementType = value; } }
  341. [SerializeField]
  342. private float m_Elasticity = 0.1f;
  343. /// <summary>
  344. /// The amount of elasticity to use when the content moves beyond the scroll rect.
  345. /// </summary>
  346. /// <example>
  347. /// <code>
  348. /// using UnityEngine;
  349. /// using System.Collections;
  350. /// using UnityEngine.UI;
  351. ///
  352. /// public class ExampleClass : MonoBehaviour
  353. /// {
  354. /// public ScrollRect myScrollRect;
  355. ///
  356. /// public void Start()
  357. /// {
  358. /// // assigns a new value to the elasticity of the scroll rect.
  359. /// // The higher the number the longer it takes to snap back.
  360. /// myScrollRect.elasticity = 3.0f;
  361. /// }
  362. /// }
  363. /// </code>
  364. /// </example>
  365. public float elasticity { get { return m_Elasticity; } set { m_Elasticity = value; } }
  366. [SerializeField]
  367. private bool m_Inertia = true;
  368. /// <summary>
  369. /// Should movement inertia be enabled?
  370. /// </summary>
  371. /// <remarks>
  372. /// Inertia means that the scrollrect content will keep scrolling for a while after being dragged. It gradually slows down according to the decelerationRate.
  373. /// </remarks>
  374. public bool inertia { get { return m_Inertia; } set { m_Inertia = value; } }
  375. [SerializeField]
  376. private float m_DecelerationRate = 0.135f; // Only used when inertia is enabled
  377. /// <summary>
  378. /// The rate at which movement slows down.
  379. /// </summary>
  380. /// <remarks>
  381. /// The deceleration rate is the speed reduction per second. A value of 0.5 halves the speed each second. The default is 0.135. The deceleration rate is only used when inertia is enabled.
  382. /// </remarks>
  383. /// <example>
  384. /// <code>
  385. /// using UnityEngine;
  386. /// using System.Collections;
  387. /// using UnityEngine.UI; // Required when Using UI elements.
  388. ///
  389. /// public class ExampleClass : MonoBehaviour
  390. /// {
  391. /// public ScrollRect myScrollRect;
  392. ///
  393. /// public void Start()
  394. /// {
  395. /// // assigns a new value to the decelerationRate of the scroll rect.
  396. /// // The higher the number the longer it takes to decelerate.
  397. /// myScrollRect.decelerationRate = 5.0f;
  398. /// }
  399. /// }
  400. /// </code>
  401. /// </example>
  402. public float decelerationRate { get { return m_DecelerationRate; } set { m_DecelerationRate = value; } }
  403. [SerializeField]
  404. private float m_ScrollSensitivity = 1.0f;
  405. /// <summary>
  406. /// The sensitivity to scroll wheel and track pad scroll events.
  407. /// </summary>
  408. /// <remarks>
  409. /// Higher values indicate higher sensitivity.
  410. /// </remarks>
  411. public float scrollSensitivity { get { return m_ScrollSensitivity; } set { m_ScrollSensitivity = value; } }
  412. [SerializeField]
  413. private RectTransform m_Viewport;
  414. /// <summary>
  415. /// Reference to the viewport RectTransform that is the parent of the content RectTransform.
  416. /// </summary>
  417. public RectTransform viewport
  418. {
  419. get { return m_Viewport; }
  420. set
  421. {
  422. m_Viewport = value;
  423. SetDirtyCaching();
  424. }
  425. }
  426. [SerializeField]
  427. private Scrollbar m_HorizontalScrollbar;
  428. /// <summary>
  429. /// Optional Scrollbar object linked to the horizontal scrolling of the ScrollRect.
  430. /// </summary>
  431. /// <example>
  432. /// <code>
  433. /// using UnityEngine;
  434. /// using System.Collections;
  435. /// using UnityEngine.UI; // Required when Using UI elements.
  436. ///
  437. /// public class ExampleClass : MonoBehaviour
  438. /// {
  439. /// public ScrollRect myScrollRect;
  440. /// public Scrollbar newScrollBar;
  441. ///
  442. /// public void Start()
  443. /// {
  444. /// // Assigns a scroll bar element to the ScrollRect, allowing you to scroll in the horizontal axis.
  445. /// myScrollRect.horizontalScrollbar = newScrollBar;
  446. /// }
  447. /// }
  448. /// </code>
  449. /// </example>
  450. public Scrollbar horizontalScrollbar
  451. {
  452. get
  453. {
  454. return m_HorizontalScrollbar;
  455. }
  456. set
  457. {
  458. if (m_HorizontalScrollbar)
  459. m_HorizontalScrollbar.onValueChanged.RemoveListener(SetHorizontalNormalizedPosition);
  460. m_HorizontalScrollbar = value;
  461. if (m_HorizontalScrollbar)
  462. m_HorizontalScrollbar.onValueChanged.AddListener(SetHorizontalNormalizedPosition);
  463. SetDirtyCaching();
  464. }
  465. }
  466. [SerializeField]
  467. private Scrollbar m_VerticalScrollbar;
  468. /// <summary>
  469. /// Optional Scrollbar object linked to the vertical scrolling of the ScrollRect.
  470. /// </summary>
  471. /// <example>
  472. /// <code>
  473. /// using UnityEngine;
  474. /// using System.Collections;
  475. /// using UnityEngine.UI; // Required when Using UI elements.
  476. ///
  477. /// public class ExampleClass : MonoBehaviour
  478. /// {
  479. /// public ScrollRect myScrollRect;
  480. /// public Scrollbar newScrollBar;
  481. ///
  482. /// public void Start()
  483. /// {
  484. /// // Assigns a scroll bar element to the ScrollRect, allowing you to scroll in the vertical axis.
  485. /// myScrollRect.verticalScrollbar = newScrollBar;
  486. /// }
  487. /// }
  488. /// </code>
  489. /// </example>
  490. public Scrollbar verticalScrollbar
  491. {
  492. get
  493. {
  494. return m_VerticalScrollbar;
  495. }
  496. set
  497. {
  498. if (m_VerticalScrollbar)
  499. m_VerticalScrollbar.onValueChanged.RemoveListener(SetVerticalNormalizedPosition);
  500. m_VerticalScrollbar = value;
  501. if (m_VerticalScrollbar)
  502. m_VerticalScrollbar.onValueChanged.AddListener(SetVerticalNormalizedPosition);
  503. SetDirtyCaching();
  504. }
  505. }
  506. [SerializeField]
  507. private ScrollbarVisibility m_HorizontalScrollbarVisibility;
  508. /// <summary>
  509. /// The mode of visibility for the horizontal scrollbar.
  510. /// </summary>
  511. public ScrollbarVisibility horizontalScrollbarVisibility
  512. {
  513. get { return m_HorizontalScrollbarVisibility; }
  514. set
  515. {
  516. m_HorizontalScrollbarVisibility = value;
  517. SetDirtyCaching();
  518. }
  519. }
  520. [SerializeField]
  521. private ScrollbarVisibility m_VerticalScrollbarVisibility;
  522. /// <summary>
  523. /// The mode of visibility for the vertical scrollbar.
  524. /// </summary>
  525. public ScrollbarVisibility verticalScrollbarVisibility
  526. {
  527. get { return m_VerticalScrollbarVisibility; }
  528. set
  529. {
  530. m_VerticalScrollbarVisibility = value;
  531. SetDirtyCaching();
  532. }
  533. }
  534. [SerializeField]
  535. private float m_HorizontalScrollbarSpacing;
  536. /// <summary>
  537. /// The space between the scrollbar and the viewport.
  538. /// </summary>
  539. public float horizontalScrollbarSpacing
  540. {
  541. get { return m_HorizontalScrollbarSpacing; }
  542. set
  543. {
  544. m_HorizontalScrollbarSpacing = value;
  545. SetDirty();
  546. }
  547. }
  548. [SerializeField]
  549. private float m_VerticalScrollbarSpacing;
  550. /// <summary>
  551. /// The space between the scrollbar and the viewport.
  552. /// </summary>
  553. public float verticalScrollbarSpacing
  554. {
  555. get { return m_VerticalScrollbarSpacing; }
  556. set
  557. {
  558. m_VerticalScrollbarSpacing = value;
  559. SetDirty();
  560. }
  561. }
  562. [SerializeField]
  563. private ScrollRectEvent m_OnValueChanged = new ScrollRectEvent();
  564. /// <summary>
  565. /// Callback executed when the position of the child changes.
  566. /// </summary>
  567. /// <remarks>
  568. /// onValueChanged is used to watch for changes in the ScrollRect object.
  569. /// The onValueChanged call will use the UnityEvent.AddListener API to watch for
  570. /// changes. When changes happen script code provided by the user will be called.
  571. /// The UnityEvent.AddListener API for UI.ScrollRect._onValueChanged takes a Vector2.
  572. ///
  573. /// Note: The editor allows the onValueChanged value to be set up manually.For example the
  574. /// value can be set to run only a runtime. The object and script function to call are also
  575. /// provided here.
  576. ///
  577. /// The onValueChanged variable can be alternatively set-up at runtime.The script example below
  578. /// shows how this can be done.The script is attached to the ScrollRect object.
  579. /// </remarks>
  580. /// <example>
  581. /// <code>
  582. /// using UnityEngine;
  583. /// using UnityEngine.UI;
  584. ///
  585. /// public class ExampleScript : MonoBehaviour
  586. /// {
  587. /// static ScrollRect scrollRect;
  588. ///
  589. /// void Start()
  590. /// {
  591. /// scrollRect = GetComponent<ScrollRect>();
  592. /// scrollRect.onValueChanged.AddListener(ListenerMethod);
  593. /// }
  594. ///
  595. /// public void ListenerMethod(Vector2 value)
  596. /// {
  597. /// Debug.Log("ListenerMethod: " + value);
  598. /// }
  599. /// }
  600. /// </code>
  601. /// </example>
  602. public ScrollRectEvent onValueChanged { get { return m_OnValueChanged; } set { m_OnValueChanged = value; } }
  603. // The offset from handle position to mouse down position
  604. private Vector2 m_PointerStartLocalCursor = Vector2.zero;
  605. protected Vector2 m_ContentStartPosition = Vector2.zero;
  606. private RectTransform m_ViewRect;
  607. protected RectTransform viewRect
  608. {
  609. get
  610. {
  611. if (m_ViewRect == null)
  612. m_ViewRect = m_Viewport;
  613. if (m_ViewRect == null)
  614. m_ViewRect = (RectTransform)transform;
  615. return m_ViewRect;
  616. }
  617. }
  618. protected Bounds m_ContentBounds;
  619. private Bounds m_ViewBounds;
  620. private Vector2 m_Velocity;
  621. /// <summary>
  622. /// The current velocity of the content.
  623. /// </summary>
  624. /// <remarks>
  625. /// The velocity is defined in units per second.
  626. /// </remarks>
  627. public Vector2 velocity { get { return m_Velocity; } set { m_Velocity = value; } }
  628. private bool m_Dragging;
  629. private bool m_Scrolling;
  630. private Vector2 m_PrevPosition = Vector2.zero;
  631. private Bounds m_PrevContentBounds;
  632. private Bounds m_PrevViewBounds;
  633. [NonSerialized]
  634. private bool m_HasRebuiltLayout = false;
  635. private bool m_HSliderExpand;
  636. private bool m_VSliderExpand;
  637. private float m_HSliderHeight;
  638. private float m_VSliderWidth;
  639. [System.NonSerialized]
  640. private RectTransform m_Rect;
  641. private RectTransform rectTransform
  642. {
  643. get
  644. {
  645. if (m_Rect == null)
  646. m_Rect = GetComponent<RectTransform>();
  647. return m_Rect;
  648. }
  649. }
  650. private RectTransform m_HorizontalScrollbarRect;
  651. private RectTransform m_VerticalScrollbarRect;
  652. private DrivenRectTransformTracker m_Tracker;
  653. protected LoopScrollRectBase()
  654. {
  655. }
  656. //==========LoopScrollRect==========
  657. #if UNITY_EDITOR
  658. protected override void Awake()
  659. {
  660. base.Awake();
  661. if (Application.isPlaying)
  662. {
  663. float value = (reverseDirection ^ (direction == LoopScrollRectDirection.Horizontal)) ? 0 : 1;
  664. if (m_Content != null)
  665. {
  666. Debug.Assert(GetAbsDimension(m_Content.pivot) == value, $"{this.gameObject.name} pivot 设置错误 不符合要求 LoopScroll", this);
  667. Debug.Assert(GetAbsDimension(m_Content.anchorMin) == value, $"{this.gameObject.name} anchorMin 设置错误 不符合要求 LoopScroll", this);
  668. Debug.Assert(GetAbsDimension(m_Content.anchorMax) == value, $"{this.gameObject.name} anchorMax 设置错误 不符合要求 LoopScroll", this);
  669. }
  670. //不需要这个断言
  671. /*if (direction == LoopScrollRectDirection.Vertical)
  672. Debug.Assert(m_Vertical && !m_Horizontal, this);
  673. else
  674. Debug.Assert(!m_Vertical && m_Horizontal, this);*/
  675. }
  676. }
  677. #endif
  678. public void ClearCells()
  679. {
  680. if (Application.isPlaying)
  681. {
  682. itemTypeStart = 0;
  683. itemTypeEnd = 0;
  684. totalCount = 0;
  685. for (int i = m_Content.childCount - 1; i >= 0; i--)
  686. {
  687. prefabSource.ReturnObject(m_Content.GetChild(i));
  688. }
  689. }
  690. }
  691. public int GetFirstItem(out float offset)
  692. {
  693. if (direction == LoopScrollRectDirection.Vertical)
  694. offset = m_ViewBounds.max.y - m_ContentBounds.max.y;
  695. else
  696. offset = m_ContentBounds.min.x - m_ViewBounds.min.x;
  697. int idx = 0;
  698. if (itemTypeEnd > itemTypeStart)
  699. {
  700. float size = GetSize(m_Content.GetChild(0) as RectTransform, false);
  701. while (size + offset <= 0 && itemTypeStart + idx + contentConstraintCount < itemTypeEnd)
  702. {
  703. offset += size;
  704. idx += contentConstraintCount;
  705. size = GetSize(m_Content.GetChild(idx) as RectTransform);
  706. }
  707. }
  708. return idx + itemTypeStart;
  709. }
  710. public int GetLastItem(out float offset)
  711. {
  712. if (direction == LoopScrollRectDirection.Vertical)
  713. offset = m_ContentBounds.min.y - m_ViewBounds.min.y;
  714. else
  715. offset = m_ViewBounds.max.x - m_ContentBounds.max.x;
  716. int idx = 0;
  717. if (itemTypeEnd > itemTypeStart)
  718. {
  719. int totalChildCount = m_Content.childCount;
  720. float size = GetSize(m_Content.GetChild(totalChildCount - idx - 1) as RectTransform, false);
  721. while (size + offset <= 0 && itemTypeStart < itemTypeEnd - idx - contentConstraintCount)
  722. {
  723. offset += size;
  724. idx += contentConstraintCount;
  725. size = GetSize(m_Content.GetChild(totalChildCount - idx - 1) as RectTransform);
  726. }
  727. }
  728. offset = -offset;
  729. return itemTypeEnd - idx - 1;
  730. }
  731. public async ETTask ScrollToCell(int index, float speed)
  732. {
  733. if (totalCount >= 0 && (index < 0 || index >= totalCount))
  734. {
  735. Debug.LogErrorFormat("invalid index {0}", index);
  736. return;
  737. }
  738. StopAllCoroutines();
  739. if (speed <= 0)
  740. {
  741. await RefillCells(index);
  742. return;
  743. }
  744. await ScrollToCellCoroutine(index, speed);
  745. }
  746. public async ETTask ScrollToCellWithinTime(int index, float time)
  747. {
  748. if (totalCount >= 0 && (index < 0 || index >= totalCount))
  749. {
  750. Debug.LogErrorFormat("invalid index {0}", index);
  751. return;
  752. }
  753. StopAllCoroutines();
  754. if (time <= 0)
  755. {
  756. await RefillCells(index);
  757. return;
  758. }
  759. float dist = 0;
  760. float offset = 0;
  761. int currentFirst = reverseDirection ? GetLastItem(out offset) : GetFirstItem(out offset);
  762. int TargetLine = (index / contentConstraintCount);
  763. int CurrentLine = (currentFirst / contentConstraintCount);
  764. if (TargetLine == CurrentLine)
  765. {
  766. dist = offset;
  767. }
  768. else
  769. {
  770. if (sizeHelper != null)
  771. {
  772. dist = GetDimension(sizeHelper.GetItemsSize(currentFirst) - sizeHelper.GetItemsSize(index)) +
  773. contentSpacing * (CurrentLine - TargetLine - 1);
  774. dist += offset;
  775. }
  776. else
  777. {
  778. float elementSize = (GetAbsDimension(m_ContentBounds.size) - contentSpacing * (CurrentLines - 1)) / CurrentLines;
  779. dist = elementSize * (CurrentLine - TargetLine) + contentSpacing * (CurrentLine - TargetLine - 1);
  780. dist -= offset;
  781. }
  782. }
  783. await ScrollToCellCoroutine(index, Mathf.Abs(dist) / time);
  784. }
  785. private readonly YIUIInvokeEntity_WaitFrameAsync m_WaitFrameAsync = new();
  786. private async ETTask ScrollToCellCoroutine(int index, float speed)
  787. {
  788. bool needMoving = true;
  789. while (needMoving)
  790. {
  791. await ET.EventSystem.Instance?.YIUIInvokeEntityAsyncSafety<YIUIInvokeEntity_WaitFrameAsync, ETTask>(YIUISingletonHelper.YIUIMgr, m_WaitFrameAsync);
  792. if (!m_Dragging)
  793. {
  794. float move = 0;
  795. if (index < itemTypeStart)
  796. {
  797. move = -Time.deltaTime * speed;
  798. }
  799. else if (index >= itemTypeEnd)
  800. {
  801. move = Time.deltaTime * speed;
  802. }
  803. else
  804. {
  805. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  806. var m_ItemBounds = GetBounds4Item(index);
  807. var offset = 0.0f;
  808. if (direction == LoopScrollRectDirection.Vertical)
  809. offset = reverseDirection ? (m_ViewBounds.min.y - m_ItemBounds.min.y) : (m_ViewBounds.max.y - m_ItemBounds.max.y);
  810. else
  811. offset = reverseDirection ? (m_ItemBounds.max.x - m_ViewBounds.max.x) : (m_ItemBounds.min.x - m_ViewBounds.min.x);
  812. // check if we cannot move on
  813. if (totalCount >= 0)
  814. {
  815. if (offset > 0 && itemTypeEnd == totalCount && !reverseDirection)
  816. {
  817. m_ItemBounds = GetBounds4Item(totalCount - 1);
  818. // reach bottom
  819. if ((direction == LoopScrollRectDirection.Vertical && m_ItemBounds.min.y > m_ViewBounds.min.y) ||
  820. (direction == LoopScrollRectDirection.Horizontal && m_ItemBounds.max.x < m_ViewBounds.max.x))
  821. {
  822. needMoving = false;
  823. break;
  824. }
  825. }
  826. else if (offset < 0 && itemTypeStart == 0 && reverseDirection)
  827. {
  828. m_ItemBounds = GetBounds4Item(0);
  829. if ((direction == LoopScrollRectDirection.Vertical && m_ItemBounds.max.y < m_ViewBounds.max.y) ||
  830. (direction == LoopScrollRectDirection.Horizontal && m_ItemBounds.min.x > m_ViewBounds.min.x))
  831. {
  832. needMoving = false;
  833. break;
  834. }
  835. }
  836. }
  837. float maxMove = Time.deltaTime * speed;
  838. if (Mathf.Abs(offset) < maxMove)
  839. {
  840. needMoving = false;
  841. move = offset;
  842. }
  843. else
  844. move = Mathf.Sign(offset) * maxMove;
  845. }
  846. if (move != 0)
  847. {
  848. Vector2 offset = GetVector(move);
  849. m_Content.anchoredPosition += offset;
  850. m_PrevPosition += offset;
  851. m_ContentStartPosition += offset;
  852. await UpdateBounds(true);
  853. }
  854. }
  855. }
  856. StopMovement();
  857. UpdatePrevData();
  858. }
  859. protected abstract void ProvideData(Transform transform, int index);
  860. /// <summary>
  861. /// Refresh item data
  862. /// </summary>
  863. public async ETTask RefreshCells()
  864. {
  865. if (Application.isPlaying && this.isActiveAndEnabled)
  866. {
  867. itemTypeEnd = itemTypeStart;
  868. // recycle items if we can
  869. for (int i = 0; i < m_Content.childCount; i++)
  870. {
  871. if (itemTypeEnd < totalCount)
  872. {
  873. ProvideData(m_Content.GetChild(i), itemTypeEnd);
  874. itemTypeEnd++;
  875. }
  876. else
  877. {
  878. prefabSource.ReturnObject(m_Content.GetChild(i));
  879. i--;
  880. }
  881. }
  882. await UpdateBounds(true);
  883. UpdateScrollbars(Vector2.zero);
  884. }
  885. }
  886. /// <summary>
  887. /// Refill cells from endItem at the end while clear existing ones
  888. /// </summary>
  889. public async ETTask RefillCellsFromEnd(int endItem = 0, bool alignStart = false)
  890. {
  891. if (!Application.isPlaying)
  892. return;
  893. itemTypeEnd = reverseDirection ? endItem : totalCount - endItem;
  894. itemTypeStart = itemTypeEnd;
  895. if (totalCount >= 0 && itemTypeStart % contentConstraintCount != 0)
  896. {
  897. itemTypeStart = (itemTypeStart / contentConstraintCount) * contentConstraintCount;
  898. }
  899. ReturnToTempPool(!reverseDirection, m_Content.childCount);
  900. float sizeToFill = GetAbsDimension(viewRect.rect.size), sizeFilled = 0;
  901. bool first = true;
  902. // issue 169: fill last line
  903. if (itemTypeStart < itemTypeEnd)
  904. {
  905. itemTypeEnd = itemTypeStart;
  906. float size = reverseDirection ? await NewItemAtStart(!first) : await NewItemAtEnd(!first);
  907. if (size >= 0)
  908. {
  909. first = false;
  910. sizeFilled += size;
  911. }
  912. }
  913. while (sizeToFill > sizeFilled)
  914. {
  915. float size = reverseDirection ? await NewItemAtEnd(!first) : await NewItemAtStart(!first);
  916. if (size < 0)
  917. break;
  918. first = false;
  919. sizeFilled += size;
  920. }
  921. // refill from start in case not full yet
  922. while (sizeToFill > sizeFilled)
  923. {
  924. float size = reverseDirection ? await NewItemAtStart(!first) : await NewItemAtEnd(!first);
  925. if (size < 0)
  926. break;
  927. first = false;
  928. sizeFilled += size;
  929. }
  930. Vector2 pos = m_Content.anchoredPosition;
  931. float dist = alignStart ? 0 : Mathf.Max(0, sizeFilled - sizeToFill);
  932. if (reverseDirection)
  933. dist = -dist;
  934. if (direction == LoopScrollRectDirection.Vertical)
  935. pos.y = dist;
  936. else
  937. pos.x = -dist;
  938. m_Content.anchoredPosition = pos;
  939. m_ContentStartPosition = pos;
  940. ClearTempPool();
  941. // force build bounds here so scrollbar can access newest bounds
  942. LayoutRebuilder.ForceRebuildLayoutImmediate(m_Content);
  943. Canvas.ForceUpdateCanvases();
  944. UpdateBounds();
  945. UpdateScrollbars(Vector2.zero);
  946. StopMovement();
  947. UpdatePrevData();
  948. }
  949. /// <summary>
  950. /// Refill cells with startItem at the beginning while clear existing ones
  951. /// </summary>
  952. /// <param name="startItem">The first item to fill</param>
  953. /// <param name="contentOffset">The first item's offset compared to viewBound</param>
  954. public async ETTask RefillCells(int startItem = 0, float contentOffset = 0)
  955. {
  956. if (!Application.isPlaying)
  957. return;
  958. itemTypeStart = reverseDirection ? totalCount - startItem : startItem;
  959. if (totalCount >= 0 && itemTypeStart % contentConstraintCount != 0)
  960. {
  961. itemTypeStart = (itemTypeStart / contentConstraintCount) * contentConstraintCount;
  962. }
  963. itemTypeEnd = itemTypeStart;
  964. // Don't `Canvas.ForceUpdateCanvases();` here, or it will new/delete cells to change itemTypeStart/End
  965. ReturnToTempPool(reverseDirection, m_Content.childCount);
  966. float sizeToFill = GetAbsDimension(viewRect.rect.size) + Mathf.Abs(contentOffset);
  967. if (sizeToFill <= 0)
  968. {
  969. //Debug.Log($" sizeToFill <= 0 强制刷新一次");
  970. var lastActive = viewRect.gameObject.activeSelf;
  971. if (!lastActive)
  972. {
  973. viewRect.gameObject.SetActive(true);
  974. }
  975. Canvas.ForceUpdateCanvases();
  976. sizeToFill = GetAbsDimension(viewRect.rect.size) + Mathf.Abs(contentOffset);
  977. if (!lastActive)
  978. {
  979. viewRect.gameObject.SetActive(false);
  980. }
  981. if (sizeToFill <= 0)
  982. {
  983. Debug.LogError($"LoopScrollRect获取刷新范围 强制刷新一次后依然 <=0 这样肯定刷新不出Item 请检查 是否设置有问题 {this.gameObject.name}", this);
  984. }
  985. }
  986. float sizeFilled = 0;
  987. // m_ViewBounds may be not ready when RefillCells on Start
  988. float itemSize = 0;
  989. bool first = true;
  990. while (sizeToFill > sizeFilled)
  991. {
  992. float size = reverseDirection ? await NewItemAtStart(!first) : await NewItemAtEnd(!first);
  993. if (size < 0)
  994. break;
  995. first = false;
  996. itemSize = size;
  997. sizeFilled += size;
  998. }
  999. // refill from start in case not full yet
  1000. while (sizeToFill > sizeFilled)
  1001. {
  1002. float size = reverseDirection ? await NewItemAtEnd(!first) : await NewItemAtStart(!first);
  1003. if (size < 0)
  1004. break;
  1005. first = false;
  1006. sizeFilled += size;
  1007. }
  1008. Vector2 pos = m_Content.anchoredPosition;
  1009. if (direction == LoopScrollRectDirection.Vertical)
  1010. pos.y = -contentOffset;
  1011. else
  1012. pos.x = contentOffset;
  1013. m_Content.anchoredPosition = pos;
  1014. m_ContentStartPosition = pos;
  1015. ClearTempPool();
  1016. // force build bounds here so scrollbar can access newest bounds
  1017. LayoutRebuilder.ForceRebuildLayoutImmediate(m_Content);
  1018. Canvas.ForceUpdateCanvases();
  1019. UpdateBounds();
  1020. UpdateScrollbars(Vector2.zero);
  1021. StopMovement();
  1022. UpdatePrevData();
  1023. }
  1024. protected async ETTask<float> NewItemAtStart(bool includeSpacing = true)
  1025. {
  1026. if (totalCount >= 0 && itemTypeStart - contentConstraintCount < 0)
  1027. {
  1028. return -1;
  1029. }
  1030. float size = 0;
  1031. for (int i = 0; i < contentConstraintCount; i++)
  1032. {
  1033. itemTypeStart--;
  1034. var newItem = await GetFromTempPool(itemTypeStart);
  1035. if (newItem != null)
  1036. {
  1037. newItem.SetSiblingIndex(deletedItemTypeStart);
  1038. size = Mathf.Max(GetSize(newItem, includeSpacing), size);
  1039. }
  1040. }
  1041. threshold = Mathf.Max(threshold, size * 1.5f);
  1042. if (size > 0)
  1043. {
  1044. m_HasRebuiltLayout = false;
  1045. if (!reverseDirection)
  1046. {
  1047. Vector2 offset = GetVector(size);
  1048. m_Content.anchoredPosition += offset;
  1049. m_PrevPosition += offset;
  1050. m_ContentStartPosition += offset;
  1051. }
  1052. }
  1053. return size;
  1054. }
  1055. protected float DeleteItemAtStart()
  1056. {
  1057. // special case: when moving or dragging, we cannot simply delete start when we've reached the end
  1058. if ((m_Dragging || m_Velocity != Vector2.zero) && totalCount >= 0 && itemTypeEnd >= totalCount - contentConstraintCount)
  1059. {
  1060. return 0;
  1061. }
  1062. int availableChilds = m_Content.childCount - deletedItemTypeStart - deletedItemTypeEnd;
  1063. Debug.Assert(availableChilds >= 0);
  1064. if (availableChilds == 0)
  1065. {
  1066. return 0;
  1067. }
  1068. float size = 0;
  1069. for (int i = 0; i < contentConstraintCount; i++)
  1070. {
  1071. RectTransform oldItem = m_Content.GetChild(deletedItemTypeStart) as RectTransform;
  1072. size = Mathf.Max(GetSize(oldItem), size);
  1073. ReturnToTempPool(true);
  1074. availableChilds--;
  1075. itemTypeStart++;
  1076. if (availableChilds == 0)
  1077. {
  1078. break;
  1079. }
  1080. }
  1081. if (size > 0)
  1082. {
  1083. m_HasRebuiltLayout = false;
  1084. if (!reverseDirection)
  1085. {
  1086. Vector2 offset = GetVector(size);
  1087. m_Content.anchoredPosition -= offset;
  1088. m_PrevPosition -= offset;
  1089. m_ContentStartPosition -= offset;
  1090. }
  1091. }
  1092. return size;
  1093. }
  1094. protected async ETTask<float> NewItemAtEnd(bool includeSpacing = true)
  1095. {
  1096. if (totalCount >= 0 && itemTypeEnd >= totalCount)
  1097. {
  1098. return -1;
  1099. }
  1100. float size = 0;
  1101. // issue 4: fill lines to end first
  1102. int availableChilds = m_Content.childCount - deletedItemTypeStart - deletedItemTypeEnd;
  1103. int count = contentConstraintCount - (availableChilds % contentConstraintCount);
  1104. for (int i = 0; i < count; i++)
  1105. {
  1106. var newItem = await GetFromTempPool(itemTypeEnd);
  1107. if (newItem != null)
  1108. {
  1109. newItem.SetSiblingIndex(m_Content.childCount - deletedItemTypeEnd - 1);
  1110. size = Mathf.Max(GetSize(newItem, includeSpacing), size);
  1111. itemTypeEnd++;
  1112. if (totalCount >= 0 && itemTypeEnd >= totalCount)
  1113. {
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. threshold = Mathf.Max(threshold, size * 1.5f);
  1119. if (size > 0)
  1120. {
  1121. m_HasRebuiltLayout = false;
  1122. if (reverseDirection)
  1123. {
  1124. Vector2 offset = GetVector(size);
  1125. m_Content.anchoredPosition -= offset;
  1126. m_PrevPosition -= offset;
  1127. m_ContentStartPosition -= offset;
  1128. }
  1129. }
  1130. return size;
  1131. }
  1132. protected float DeleteItemAtEnd()
  1133. {
  1134. if ((m_Dragging || m_Velocity != Vector2.zero) && totalCount >= 0 && itemTypeStart < contentConstraintCount)
  1135. {
  1136. return 0;
  1137. }
  1138. int availableChilds = m_Content.childCount - deletedItemTypeStart - deletedItemTypeEnd;
  1139. Debug.Assert(availableChilds >= 0);
  1140. if (availableChilds == 0)
  1141. {
  1142. return 0;
  1143. }
  1144. float size = 0;
  1145. for (int i = 0; i < contentConstraintCount; i++)
  1146. {
  1147. RectTransform oldItem = m_Content.GetChild(m_Content.childCount - deletedItemTypeEnd - 1) as RectTransform;
  1148. size = Mathf.Max(GetSize(oldItem), size);
  1149. ReturnToTempPool(false);
  1150. availableChilds--;
  1151. itemTypeEnd--;
  1152. if (itemTypeEnd % contentConstraintCount == 0 || availableChilds == 0)
  1153. {
  1154. break; //just delete the whole row
  1155. }
  1156. }
  1157. if (size > 0)
  1158. {
  1159. m_HasRebuiltLayout = false;
  1160. if (reverseDirection)
  1161. {
  1162. Vector2 offset = GetVector(size);
  1163. m_Content.anchoredPosition += offset;
  1164. m_PrevPosition += offset;
  1165. m_ContentStartPosition += offset;
  1166. }
  1167. }
  1168. return size;
  1169. }
  1170. protected int deletedItemTypeStart = 0;
  1171. protected int deletedItemTypeEnd = 0;
  1172. protected abstract ETTask<RectTransform> GetFromTempPool(int itemIdx);
  1173. protected abstract void ReturnToTempPool(bool fromStart, int count = 1);
  1174. protected abstract void ClearTempPool();
  1175. #region Deprecated API
  1176. [Obsolete("SrollToCell(int, float) has been renamed to ScrollToCell(int, float).")]
  1177. public void SrollToCell(int index, float speed)
  1178. {
  1179. ScrollToCell(index, speed).NoContext();
  1180. }
  1181. [Obsolete("SrollToCellWithinTime(int, float) has been renamed to ScrollToCellWithinTime(int, float).")]
  1182. public void SrollToCellWithinTime(int index, float time)
  1183. {
  1184. ScrollToCellWithinTime(index, time).NoContext();
  1185. }
  1186. #endregion
  1187. //==========LoopScrollRect==========
  1188. public virtual void Rebuild(CanvasUpdate executing)
  1189. {
  1190. if (executing == CanvasUpdate.Prelayout)
  1191. {
  1192. UpdateCachedData();
  1193. }
  1194. if (executing == CanvasUpdate.PostLayout)
  1195. {
  1196. UpdateBounds();
  1197. UpdateScrollbars(Vector2.zero);
  1198. UpdatePrevData();
  1199. m_HasRebuiltLayout = true;
  1200. }
  1201. }
  1202. public virtual void LayoutComplete()
  1203. {
  1204. }
  1205. public virtual void GraphicUpdateComplete()
  1206. {
  1207. }
  1208. void UpdateCachedData()
  1209. {
  1210. Transform transform = this.transform;
  1211. m_HorizontalScrollbarRect = m_HorizontalScrollbar == null ? null : m_HorizontalScrollbar.transform as RectTransform;
  1212. m_VerticalScrollbarRect = m_VerticalScrollbar == null ? null : m_VerticalScrollbar.transform as RectTransform;
  1213. // These are true if either the elements are children, or they don't exist at all.
  1214. bool viewIsChild = (viewRect.parent == transform);
  1215. bool hScrollbarIsChild = (!m_HorizontalScrollbarRect || m_HorizontalScrollbarRect.parent == transform);
  1216. bool vScrollbarIsChild = (!m_VerticalScrollbarRect || m_VerticalScrollbarRect.parent == transform);
  1217. bool allAreChildren = (viewIsChild && hScrollbarIsChild && vScrollbarIsChild);
  1218. m_HSliderExpand = allAreChildren && m_HorizontalScrollbarRect &&
  1219. horizontalScrollbarVisibility == ScrollbarVisibility.AutoHideAndExpandViewport;
  1220. m_VSliderExpand = allAreChildren && m_VerticalScrollbarRect &&
  1221. verticalScrollbarVisibility == ScrollbarVisibility.AutoHideAndExpandViewport;
  1222. m_HSliderHeight = (m_HorizontalScrollbarRect == null ? 0 : m_HorizontalScrollbarRect.rect.height);
  1223. m_VSliderWidth = (m_VerticalScrollbarRect == null ? 0 : m_VerticalScrollbarRect.rect.width);
  1224. }
  1225. protected override void OnEnable()
  1226. {
  1227. base.OnEnable();
  1228. if (m_HorizontalScrollbar)
  1229. m_HorizontalScrollbar.onValueChanged.AddListener(SetHorizontalNormalizedPosition);
  1230. if (m_VerticalScrollbar)
  1231. m_VerticalScrollbar.onValueChanged.AddListener(SetVerticalNormalizedPosition);
  1232. CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
  1233. SetDirty();
  1234. }
  1235. protected override void OnDisable()
  1236. {
  1237. CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild(this);
  1238. if (m_HorizontalScrollbar)
  1239. m_HorizontalScrollbar.onValueChanged.RemoveListener(SetHorizontalNormalizedPosition);
  1240. if (m_VerticalScrollbar)
  1241. m_VerticalScrollbar.onValueChanged.RemoveListener(SetVerticalNormalizedPosition);
  1242. m_Dragging = false;
  1243. m_Scrolling = false;
  1244. m_HasRebuiltLayout = false;
  1245. m_Tracker.Clear();
  1246. m_Velocity = Vector2.zero;
  1247. LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
  1248. base.OnDisable();
  1249. }
  1250. /// <summary>
  1251. /// See member in base class.
  1252. /// </summary>
  1253. /// <example>
  1254. /// <code>
  1255. /// using UnityEngine;
  1256. /// using System.Collections;
  1257. /// using UnityEngine.UI; // Required when Using UI elements.
  1258. ///
  1259. /// public class ExampleClass : MonoBehaviour
  1260. /// {
  1261. /// public ScrollRect myScrollRect;
  1262. ///
  1263. /// public void Start()
  1264. /// {
  1265. /// //Checks if the ScrollRect called "myScrollRect" is active.
  1266. /// if (myScrollRect.IsActive())
  1267. /// {
  1268. /// Debug.Log("The Scroll Rect is active!");
  1269. /// }
  1270. /// }
  1271. /// }
  1272. /// </code>
  1273. /// </example>
  1274. public override bool IsActive()
  1275. {
  1276. return base.IsActive() && m_Content != null;
  1277. }
  1278. private void EnsureLayoutHasRebuilt()
  1279. {
  1280. if (!m_HasRebuiltLayout && !CanvasUpdateRegistry.IsRebuildingLayout())
  1281. Canvas.ForceUpdateCanvases();
  1282. }
  1283. /// <summary>
  1284. /// Sets the velocity to zero on both axes so the content stops moving.
  1285. /// </summary>
  1286. public virtual void StopMovement()
  1287. {
  1288. m_Velocity = Vector2.zero;
  1289. }
  1290. public virtual void OnScroll(PointerEventData data)
  1291. {
  1292. if (!IsActive())
  1293. return;
  1294. EnsureLayoutHasRebuilt();
  1295. UpdateBounds();
  1296. Vector2 delta = data.scrollDelta;
  1297. // Down is positive for scroll events, while in UI system up is positive.
  1298. delta.y *= -1;
  1299. if (vertical && !horizontal)
  1300. {
  1301. if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
  1302. delta.y = delta.x;
  1303. delta.x = 0;
  1304. }
  1305. if (horizontal && !vertical)
  1306. {
  1307. if (Mathf.Abs(delta.y) > Mathf.Abs(delta.x))
  1308. delta.x = delta.y;
  1309. delta.y = 0;
  1310. }
  1311. if (data.IsScrolling())
  1312. m_Scrolling = true;
  1313. Vector2 position = m_Content.anchoredPosition;
  1314. position += delta * m_ScrollSensitivity;
  1315. if (m_MovementType == MovementType.Clamped)
  1316. position += CalculateOffset(position - m_Content.anchoredPosition);
  1317. SetContentAnchoredPosition(position);
  1318. UpdateBounds();
  1319. }
  1320. public virtual void OnInitializePotentialDrag(PointerEventData eventData)
  1321. {
  1322. if (eventData.button != PointerEventData.InputButton.Left)
  1323. return;
  1324. m_Velocity = Vector2.zero;
  1325. }
  1326. /// <summary>
  1327. /// Handling for when the content is beging being dragged.
  1328. /// </summary>
  1329. ///<example>
  1330. /// <code>
  1331. /// using UnityEngine;
  1332. /// using System.Collections;
  1333. /// using UnityEngine.EventSystems; // Required when using event data
  1334. ///
  1335. /// public class ExampleClass : MonoBehaviour, IBeginDragHandler // required interface when using the OnBeginDrag method.
  1336. /// {
  1337. /// //Do this when the user starts dragging the element this script is attached to..
  1338. /// public void OnBeginDrag(PointerEventData data)
  1339. /// {
  1340. /// Debug.Log("They started dragging " + this.name);
  1341. /// }
  1342. /// }
  1343. /// </code>
  1344. /// </example>
  1345. public virtual void OnBeginDrag(PointerEventData eventData)
  1346. {
  1347. if (eventData.button != PointerEventData.InputButton.Left)
  1348. return;
  1349. if (!IsActive())
  1350. return;
  1351. UpdateBounds();
  1352. m_PointerStartLocalCursor = Vector2.zero;
  1353. RectTransformUtility.ScreenPointToLocalPointInRectangle(viewRect, eventData.position, eventData.pressEventCamera,
  1354. out m_PointerStartLocalCursor);
  1355. m_ContentStartPosition = m_Content.anchoredPosition;
  1356. m_Dragging = true;
  1357. }
  1358. /// <summary>
  1359. /// Handling for when the content has finished being dragged.
  1360. /// </summary>
  1361. /// <example>
  1362. /// <code>
  1363. /// using UnityEngine;
  1364. /// using System.Collections;
  1365. /// using UnityEngine.EventSystems; // Required when using event data
  1366. ///
  1367. /// public class ExampleClass : MonoBehaviour, IEndDragHandler // required interface when using the OnEndDrag method.
  1368. /// {
  1369. /// //Do this when the user stops dragging this UI Element.
  1370. /// public void OnEndDrag(PointerEventData data)
  1371. /// {
  1372. /// Debug.Log("Stopped dragging " + this.name + "!");
  1373. /// }
  1374. /// }
  1375. /// </code>
  1376. /// </example>
  1377. public virtual void OnEndDrag(PointerEventData eventData)
  1378. {
  1379. if (eventData.button != PointerEventData.InputButton.Left)
  1380. return;
  1381. m_Dragging = false;
  1382. }
  1383. /// <summary>
  1384. /// Handling for when the content is dragged.
  1385. /// </summary>
  1386. /// <example>
  1387. /// <code>
  1388. /// using UnityEngine;
  1389. /// using System.Collections;
  1390. /// using UnityEngine.EventSystems; // Required when using event data
  1391. ///
  1392. /// public class ExampleClass : MonoBehaviour, IDragHandler // required interface when using the OnDrag method.
  1393. /// {
  1394. /// //Do this while the user is dragging this UI Element.
  1395. /// public void OnDrag(PointerEventData data)
  1396. /// {
  1397. /// Debug.Log("Currently dragging " + this.name);
  1398. /// }
  1399. /// }
  1400. /// </code>
  1401. /// </example>
  1402. public virtual void OnDrag(PointerEventData eventData)
  1403. {
  1404. if (!m_Dragging)
  1405. return;
  1406. if (eventData.button != PointerEventData.InputButton.Left)
  1407. return;
  1408. if (!IsActive())
  1409. return;
  1410. Vector2 localCursor;
  1411. if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(viewRect, eventData.position, eventData.pressEventCamera, out localCursor))
  1412. return;
  1413. UpdateBounds();
  1414. ;
  1415. var pointerDelta = localCursor - m_PointerStartLocalCursor;
  1416. Vector2 position = m_ContentStartPosition + pointerDelta;
  1417. // Offset to get content into place in the view.
  1418. Vector2 offset = CalculateOffset(position - m_Content.anchoredPosition);
  1419. position += offset;
  1420. if (m_MovementType == MovementType.Elastic)
  1421. {
  1422. if (offset.x != 0)
  1423. position.x = position.x - RubberDelta(offset.x, m_ViewBounds.size.x);
  1424. if (offset.y != 0)
  1425. position.y = position.y - RubberDelta(offset.y, m_ViewBounds.size.y);
  1426. }
  1427. SetContentAnchoredPosition(position);
  1428. }
  1429. /// <summary>
  1430. /// Sets the anchored position of the content.
  1431. /// </summary>
  1432. protected virtual void SetContentAnchoredPosition(Vector2 position)
  1433. {
  1434. if (!m_Horizontal)
  1435. position.x = m_Content.anchoredPosition.x;
  1436. if (!m_Vertical)
  1437. position.y = m_Content.anchoredPosition.y;
  1438. //==========LoopScrollRect==========
  1439. if ((position - m_Content.anchoredPosition).sqrMagnitude > 0.001f)
  1440. {
  1441. m_Content.anchoredPosition = position;
  1442. UpdateBounds(true).NoContext();
  1443. }
  1444. //==========LoopScrollRect==========
  1445. }
  1446. protected virtual void LateUpdate()
  1447. {
  1448. if (!m_Content)
  1449. return;
  1450. EnsureLayoutHasRebuilt();
  1451. UpdateBounds();
  1452. ;
  1453. float deltaTime = Time.unscaledDeltaTime;
  1454. Vector2 offset = CalculateOffset(Vector2.zero);
  1455. if (!m_Dragging && (offset != Vector2.zero || m_Velocity != Vector2.zero))
  1456. {
  1457. Vector2 position = m_Content.anchoredPosition;
  1458. for (int axis = 0; axis < 2; axis++)
  1459. {
  1460. // Apply spring physics if movement is elastic and content has an offset from the view.
  1461. if (m_MovementType == MovementType.Elastic && offset[axis] != 0)
  1462. {
  1463. float speed = m_Velocity[axis];
  1464. float smoothTime = m_Elasticity;
  1465. if (m_Scrolling)
  1466. smoothTime *= 3.0f;
  1467. position[axis] = Mathf.SmoothDamp(m_Content.anchoredPosition[axis], m_Content.anchoredPosition[axis] + offset[axis],
  1468. ref speed, smoothTime, Mathf.Infinity, deltaTime);
  1469. if (Mathf.Abs(speed) < 1)
  1470. speed = 0;
  1471. m_Velocity[axis] = speed;
  1472. }
  1473. // Else move content according to velocity with deceleration applied.
  1474. else if (m_Inertia)
  1475. {
  1476. m_Velocity[axis] *= Mathf.Pow(m_DecelerationRate, deltaTime);
  1477. if (Mathf.Abs(m_Velocity[axis]) < 1)
  1478. m_Velocity[axis] = 0;
  1479. position[axis] += m_Velocity[axis] * deltaTime;
  1480. }
  1481. // If we have neither elaticity or friction, there shouldn't be any velocity.
  1482. else
  1483. {
  1484. m_Velocity[axis] = 0;
  1485. }
  1486. }
  1487. if (m_MovementType == MovementType.Clamped)
  1488. {
  1489. offset = CalculateOffset(position - m_Content.anchoredPosition);
  1490. position += offset;
  1491. }
  1492. SetContentAnchoredPosition(position);
  1493. }
  1494. if (m_Dragging && m_Inertia)
  1495. {
  1496. Vector3 newVelocity = (m_Content.anchoredPosition - m_PrevPosition) / deltaTime;
  1497. m_Velocity = Vector3.Lerp(m_Velocity, newVelocity, deltaTime * 10);
  1498. }
  1499. if (m_ViewBounds != m_PrevViewBounds || m_ContentBounds != m_PrevContentBounds || m_Content.anchoredPosition != m_PrevPosition)
  1500. {
  1501. UpdateScrollbars(offset);
  1502. #if UNITY_2017_1_OR_NEWER
  1503. UISystemProfilerApi.AddMarker("ScrollRect.value", this);
  1504. #endif
  1505. m_OnValueChanged.Invoke(normalizedPosition);
  1506. UpdatePrevData();
  1507. }
  1508. UpdateScrollbarVisibility();
  1509. m_Scrolling = false;
  1510. }
  1511. /// <summary>
  1512. /// Helper function to update the previous data fields on a ScrollRect. Call this before you change data in the ScrollRect.
  1513. /// </summary>
  1514. protected void UpdatePrevData()
  1515. {
  1516. if (m_Content == null)
  1517. m_PrevPosition = Vector2.zero;
  1518. else
  1519. m_PrevPosition = m_Content.anchoredPosition;
  1520. m_PrevViewBounds = m_ViewBounds;
  1521. m_PrevContentBounds = m_ContentBounds;
  1522. }
  1523. //==========LoopScrollRect==========
  1524. public void GetHorizonalOffsetAndSize(out float totalSize, out float offset)
  1525. {
  1526. if (sizeHelper != null)
  1527. {
  1528. totalSize = sizeHelper.GetItemsSize(TotalLines).x + contentSpacing * (TotalLines - 1);
  1529. offset = m_ContentBounds.min.x - sizeHelper.GetItemsSize(StartLine).x - contentSpacing * StartLine;
  1530. }
  1531. else
  1532. {
  1533. float elementSize = (m_ContentBounds.size.x - contentSpacing * (CurrentLines - 1)) / CurrentLines;
  1534. totalSize = elementSize * TotalLines + contentSpacing * (TotalLines - 1);
  1535. offset = m_ContentBounds.min.x - elementSize * StartLine - contentSpacing * StartLine;
  1536. }
  1537. }
  1538. public void GetVerticalOffsetAndSize(out float totalSize, out float offset)
  1539. {
  1540. if (sizeHelper != null)
  1541. {
  1542. totalSize = sizeHelper.GetItemsSize(TotalLines).y + contentSpacing * (TotalLines - 1);
  1543. offset = m_ContentBounds.max.y + sizeHelper.GetItemsSize(StartLine).y + contentSpacing * StartLine;
  1544. }
  1545. else
  1546. {
  1547. float elementSize = (m_ContentBounds.size.y - contentSpacing * (CurrentLines - 1)) / CurrentLines;
  1548. totalSize = elementSize * TotalLines + contentSpacing * (TotalLines - 1);
  1549. offset = m_ContentBounds.max.y + elementSize * StartLine + contentSpacing * StartLine;
  1550. }
  1551. }
  1552. //==========LoopScrollRect==========
  1553. private void UpdateScrollbars(Vector2 offset)
  1554. {
  1555. if (m_HorizontalScrollbar)
  1556. {
  1557. //==========LoopScrollRect==========
  1558. if (m_ContentBounds.size.x > 0 && totalCount > 0)
  1559. {
  1560. float totalSize, _;
  1561. GetHorizonalOffsetAndSize(out totalSize, out _);
  1562. m_HorizontalScrollbar.size = Mathf.Clamp01((m_ViewBounds.size.x - Mathf.Abs(offset.x)) / totalSize);
  1563. }
  1564. //==========LoopScrollRect==========
  1565. else
  1566. m_HorizontalScrollbar.size = 1;
  1567. m_HorizontalScrollbar.value = horizontalNormalizedPosition;
  1568. }
  1569. if (m_VerticalScrollbar)
  1570. {
  1571. //==========LoopScrollRect==========
  1572. if (m_ContentBounds.size.y > 0 && totalCount > 0)
  1573. {
  1574. float totalSize, _;
  1575. GetVerticalOffsetAndSize(out totalSize, out _);
  1576. m_VerticalScrollbar.size = Mathf.Clamp01((m_ViewBounds.size.y - Mathf.Abs(offset.y)) / totalSize);
  1577. }
  1578. //==========LoopScrollRect==========
  1579. else
  1580. m_VerticalScrollbar.size = 1;
  1581. m_VerticalScrollbar.value = verticalNormalizedPosition;
  1582. }
  1583. }
  1584. /// <summary>
  1585. /// The scroll position as a Vector2 between (0,0) and (1,1) with (0,0) being the lower left corner.
  1586. /// </summary>
  1587. /// <example>
  1588. /// <code>
  1589. /// using UnityEngine;
  1590. /// using System.Collections;
  1591. /// using UnityEngine.UI; // Required when Using UI elements.
  1592. ///
  1593. /// public class ExampleClass : MonoBehaviour
  1594. /// {
  1595. /// public ScrollRect myScrollRect;
  1596. /// public Vector2 myPosition = new Vector2(0.5f, 0.5f);
  1597. ///
  1598. /// public void Start()
  1599. /// {
  1600. /// //Change the current scroll position.
  1601. /// myScrollRect.normalizedPosition = myPosition;
  1602. /// }
  1603. /// }
  1604. /// </code>
  1605. /// </example>
  1606. public Vector2 normalizedPosition
  1607. {
  1608. get
  1609. {
  1610. return new Vector2(horizontalNormalizedPosition, verticalNormalizedPosition);
  1611. }
  1612. set
  1613. {
  1614. SetNormalizedPosition(value.x, 0);
  1615. SetNormalizedPosition(value.y, 1);
  1616. }
  1617. }
  1618. /// <summary>
  1619. /// The horizontal scroll position as a value between 0 and 1, with 0 being at the left.
  1620. /// </summary>
  1621. /// <example>
  1622. /// <code>
  1623. /// using UnityEngine;
  1624. /// using System.Collections;
  1625. /// using UnityEngine.UI; // Required when Using UI elements.
  1626. ///
  1627. /// public class ExampleClass : MonoBehaviour
  1628. /// {
  1629. /// public ScrollRect myScrollRect;
  1630. /// public Scrollbar newScrollBar;
  1631. ///
  1632. /// public void Start()
  1633. /// {
  1634. /// //Change the current horizontal scroll position.
  1635. /// myScrollRect.horizontalNormalizedPosition = 0.5f;
  1636. /// }
  1637. /// }
  1638. /// </code>
  1639. /// </example>
  1640. public float horizontalNormalizedPosition
  1641. {
  1642. get
  1643. {
  1644. UpdateBounds();
  1645. //==========LoopScrollRect==========
  1646. if (totalCount > 0 && itemTypeEnd > itemTypeStart)
  1647. {
  1648. float totalSize, offset;
  1649. GetHorizonalOffsetAndSize(out totalSize, out offset);
  1650. if (totalSize <= m_ViewBounds.size.x)
  1651. return (m_ViewBounds.min.x > offset) ? 1 : 0;
  1652. return (m_ViewBounds.min.x - offset) / (totalSize - m_ViewBounds.size.x);
  1653. }
  1654. else
  1655. return 0.5f;
  1656. //==========LoopScrollRect==========
  1657. }
  1658. set
  1659. {
  1660. SetNormalizedPosition(value, 0);
  1661. }
  1662. }
  1663. /// <summary>
  1664. /// The vertical scroll position as a value between 0 and 1, with 0 being at the bottom.
  1665. /// </summary>
  1666. /// <example>
  1667. /// <code>
  1668. /// using UnityEngine;
  1669. /// using System.Collections;
  1670. /// using UnityEngine.UI; // Required when Using UI elements.
  1671. ///
  1672. /// public class ExampleClass : MonoBehaviour
  1673. /// {
  1674. /// public ScrollRect myScrollRect;
  1675. /// public Scrollbar newScrollBar;
  1676. ///
  1677. /// public void Start()
  1678. /// {
  1679. /// //Change the current vertical scroll position.
  1680. /// myScrollRect.verticalNormalizedPosition = 0.5f;
  1681. /// }
  1682. /// }
  1683. /// </code>
  1684. /// </example>
  1685. public float verticalNormalizedPosition
  1686. {
  1687. get
  1688. {
  1689. UpdateBounds();
  1690. //==========LoopScrollRect==========
  1691. if (totalCount > 0 && itemTypeEnd > itemTypeStart)
  1692. {
  1693. float totalSize, offset;
  1694. GetVerticalOffsetAndSize(out totalSize, out offset);
  1695. if (totalSize <= m_ViewBounds.size.y)
  1696. return (offset > m_ViewBounds.max.y) ? 1 : 0;
  1697. return (offset - m_ViewBounds.max.y) / (totalSize - m_ViewBounds.size.y);
  1698. }
  1699. else
  1700. return 0.5f;
  1701. //==========LoopScrollRect==========
  1702. }
  1703. set
  1704. {
  1705. SetNormalizedPosition(value, 1);
  1706. }
  1707. }
  1708. private void SetHorizontalNormalizedPosition(float value) { SetNormalizedPosition(value, 0); }
  1709. private void SetVerticalNormalizedPosition(float value) { SetNormalizedPosition(value, 1); }
  1710. /// <summary>
  1711. /// >Set the horizontal or vertical scroll position as a value between 0 and 1, with 0 being at the left or at the bottom.
  1712. /// </summary>
  1713. /// <param name="value">The position to set, between 0 and 1.</param>
  1714. /// <param name="axis">The axis to set: 0 for horizontal, 1 for vertical.</param>
  1715. protected virtual void SetNormalizedPosition(float value, int axis)
  1716. {
  1717. //==========LoopScrollRect==========
  1718. if (totalCount <= 0 || itemTypeEnd <= itemTypeStart)
  1719. return;
  1720. //==========LoopScrollRect==========
  1721. EnsureLayoutHasRebuilt();
  1722. UpdateBounds();
  1723. //==========LoopScrollRect==========
  1724. float totalSize, offset;
  1725. float newAnchoredPosition = m_Content.anchoredPosition[axis];
  1726. if (axis == 0)
  1727. {
  1728. GetHorizonalOffsetAndSize(out totalSize, out offset);
  1729. if (totalSize >= m_ViewBounds.size.x)
  1730. {
  1731. newAnchoredPosition += m_ViewBounds.min.x - value * (totalSize - m_ViewBounds.size.x) - offset;
  1732. }
  1733. }
  1734. else
  1735. {
  1736. GetVerticalOffsetAndSize(out totalSize, out offset);
  1737. if (totalSize >= m_ViewBounds.size.y)
  1738. {
  1739. newAnchoredPosition -= offset - value * (totalSize - m_ViewBounds.size.y) - m_ViewBounds.max.y;
  1740. }
  1741. }
  1742. //==========LoopScrollRect==========
  1743. Vector3 anchoredPosition = m_Content.anchoredPosition;
  1744. if (Mathf.Abs(anchoredPosition[axis] - newAnchoredPosition) > 0.01f)
  1745. {
  1746. anchoredPosition[axis] = newAnchoredPosition;
  1747. m_Content.anchoredPosition = anchoredPosition;
  1748. m_Velocity[axis] = 0;
  1749. UpdateBounds(true).NoContext(); //==========LoopScrollRect==========
  1750. }
  1751. }
  1752. private static float RubberDelta(float overStretching, float viewSize)
  1753. {
  1754. return (1 - (1 / ((Mathf.Abs(overStretching) * 0.55f / viewSize) + 1))) * viewSize * Mathf.Sign(overStretching);
  1755. }
  1756. protected override void OnRectTransformDimensionsChange()
  1757. {
  1758. SetDirty();
  1759. }
  1760. private bool hScrollingNeeded
  1761. {
  1762. get
  1763. {
  1764. if (Application.isPlaying)
  1765. return m_ContentBounds.size.x > m_ViewBounds.size.x + 0.01f;
  1766. return true;
  1767. }
  1768. }
  1769. private bool vScrollingNeeded
  1770. {
  1771. get
  1772. {
  1773. if (Application.isPlaying)
  1774. return m_ContentBounds.size.y > m_ViewBounds.size.y + 0.01f;
  1775. return true;
  1776. }
  1777. }
  1778. /// <summary>
  1779. /// Called by the layout system.
  1780. /// </summary>
  1781. public virtual void CalculateLayoutInputHorizontal() { }
  1782. /// <summary>
  1783. /// Called by the layout system.
  1784. /// </summary>
  1785. public virtual void CalculateLayoutInputVertical() { }
  1786. /// <summary>
  1787. /// Called by the layout system.
  1788. /// </summary>
  1789. public virtual float minWidth { get { return -1; } }
  1790. /// <summary>
  1791. /// Called by the layout system.
  1792. /// </summary>
  1793. public virtual float preferredWidth { get { return -1; } }
  1794. /// <summary>
  1795. /// Called by the layout system.
  1796. /// </summary>
  1797. public virtual float flexibleWidth { get { return -1; } }
  1798. /// <summary>
  1799. /// Called by the layout system.
  1800. /// </summary>
  1801. public virtual float minHeight { get { return -1; } }
  1802. /// <summary>
  1803. /// Called by the layout system.
  1804. /// </summary>
  1805. public virtual float preferredHeight { get { return -1; } }
  1806. /// <summary>
  1807. /// Called by the layout system.
  1808. /// </summary>
  1809. public virtual float flexibleHeight { get { return -1; } }
  1810. /// <summary>
  1811. /// Called by the layout system.
  1812. /// </summary>
  1813. public virtual int layoutPriority { get { return -1; } }
  1814. public virtual void SetLayoutHorizontal()
  1815. {
  1816. m_Tracker.Clear();
  1817. if (m_HSliderExpand || m_VSliderExpand)
  1818. {
  1819. m_Tracker.Add(this, viewRect,
  1820. DrivenTransformProperties.Anchors |
  1821. DrivenTransformProperties.SizeDelta |
  1822. DrivenTransformProperties.AnchoredPosition);
  1823. // Make view full size to see if content fits.
  1824. viewRect.anchorMin = Vector2.zero;
  1825. viewRect.anchorMax = Vector2.one;
  1826. viewRect.sizeDelta = Vector2.zero;
  1827. viewRect.anchoredPosition = Vector2.zero;
  1828. // Recalculate content layout with this size to see if it fits when there are no scrollbars.
  1829. LayoutRebuilder.ForceRebuildLayoutImmediate(m_Content);
  1830. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  1831. m_ContentBounds = GetBounds();
  1832. }
  1833. // If it doesn't fit vertically, enable vertical scrollbar and shrink view horizontally to make room for it.
  1834. if (m_VSliderExpand && vScrollingNeeded)
  1835. {
  1836. viewRect.sizeDelta = new Vector2(-(m_VSliderWidth + m_VerticalScrollbarSpacing), viewRect.sizeDelta.y);
  1837. // Recalculate content layout with this size to see if it fits vertically
  1838. // when there is a vertical scrollbar (which may reflowed the content to make it taller).
  1839. LayoutRebuilder.ForceRebuildLayoutImmediate(m_Content);
  1840. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  1841. m_ContentBounds = GetBounds();
  1842. }
  1843. // If it doesn't fit horizontally, enable horizontal scrollbar and shrink view vertically to make room for it.
  1844. if (m_HSliderExpand && hScrollingNeeded)
  1845. {
  1846. viewRect.sizeDelta = new Vector2(viewRect.sizeDelta.x, -(m_HSliderHeight + m_HorizontalScrollbarSpacing));
  1847. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  1848. m_ContentBounds = GetBounds();
  1849. }
  1850. // If the vertical slider didn't kick in the first time, and the horizontal one did,
  1851. // we need to check again if the vertical slider now needs to kick in.
  1852. // If it doesn't fit vertically, enable vertical scrollbar and shrink view horizontally to make room for it.
  1853. if (m_VSliderExpand && vScrollingNeeded && viewRect.sizeDelta.x == 0 && viewRect.sizeDelta.y < 0)
  1854. {
  1855. viewRect.sizeDelta = new Vector2(-(m_VSliderWidth + m_VerticalScrollbarSpacing), viewRect.sizeDelta.y);
  1856. }
  1857. }
  1858. public virtual void SetLayoutVertical()
  1859. {
  1860. UpdateScrollbarLayout();
  1861. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  1862. m_ContentBounds = GetBounds();
  1863. }
  1864. void UpdateScrollbarVisibility()
  1865. {
  1866. UpdateOneScrollbarVisibility(vScrollingNeeded, m_Vertical, m_VerticalScrollbarVisibility, m_VerticalScrollbar);
  1867. UpdateOneScrollbarVisibility(hScrollingNeeded, m_Horizontal, m_HorizontalScrollbarVisibility, m_HorizontalScrollbar);
  1868. }
  1869. private static void UpdateOneScrollbarVisibility(bool xScrollingNeeded,
  1870. bool xAxisEnabled,
  1871. ScrollbarVisibility scrollbarVisibility,
  1872. Scrollbar scrollbar)
  1873. {
  1874. if (scrollbar)
  1875. {
  1876. if (scrollbarVisibility == ScrollbarVisibility.Permanent)
  1877. {
  1878. if (scrollbar.gameObject.activeSelf != xAxisEnabled)
  1879. scrollbar.gameObject.SetActive(xAxisEnabled);
  1880. }
  1881. else
  1882. {
  1883. if (scrollbar.gameObject.activeSelf != xScrollingNeeded)
  1884. scrollbar.gameObject.SetActive(xScrollingNeeded);
  1885. }
  1886. }
  1887. }
  1888. void UpdateScrollbarLayout()
  1889. {
  1890. if (m_VSliderExpand && m_HorizontalScrollbar)
  1891. {
  1892. m_Tracker.Add(this, m_HorizontalScrollbarRect,
  1893. DrivenTransformProperties.AnchorMinX |
  1894. DrivenTransformProperties.AnchorMaxX |
  1895. DrivenTransformProperties.SizeDeltaX |
  1896. DrivenTransformProperties.AnchoredPositionX);
  1897. m_HorizontalScrollbarRect.anchorMin = new Vector2(0, m_HorizontalScrollbarRect.anchorMin.y);
  1898. m_HorizontalScrollbarRect.anchorMax = new Vector2(1, m_HorizontalScrollbarRect.anchorMax.y);
  1899. m_HorizontalScrollbarRect.anchoredPosition = new Vector2(0, m_HorizontalScrollbarRect.anchoredPosition.y);
  1900. if (vScrollingNeeded)
  1901. m_HorizontalScrollbarRect.sizeDelta
  1902. = new Vector2(-(m_VSliderWidth + m_VerticalScrollbarSpacing), m_HorizontalScrollbarRect.sizeDelta.y);
  1903. else
  1904. m_HorizontalScrollbarRect.sizeDelta = new Vector2(0, m_HorizontalScrollbarRect.sizeDelta.y);
  1905. }
  1906. if (m_HSliderExpand && m_VerticalScrollbar)
  1907. {
  1908. m_Tracker.Add(this, m_VerticalScrollbarRect,
  1909. DrivenTransformProperties.AnchorMinY |
  1910. DrivenTransformProperties.AnchorMaxY |
  1911. DrivenTransformProperties.SizeDeltaY |
  1912. DrivenTransformProperties.AnchoredPositionY);
  1913. m_VerticalScrollbarRect.anchorMin = new Vector2(m_VerticalScrollbarRect.anchorMin.x, 0);
  1914. m_VerticalScrollbarRect.anchorMax = new Vector2(m_VerticalScrollbarRect.anchorMax.x, 1);
  1915. m_VerticalScrollbarRect.anchoredPosition = new Vector2(m_VerticalScrollbarRect.anchoredPosition.x, 0);
  1916. if (hScrollingNeeded)
  1917. m_VerticalScrollbarRect.sizeDelta
  1918. = new Vector2(m_VerticalScrollbarRect.sizeDelta.x, -(m_HSliderHeight + m_HorizontalScrollbarSpacing));
  1919. else
  1920. m_VerticalScrollbarRect.sizeDelta = new Vector2(m_VerticalScrollbarRect.sizeDelta.x, 0);
  1921. }
  1922. }
  1923. /// <summary>
  1924. /// Calculate the bounds the ScrollRect should be using.
  1925. /// </summary>
  1926. private async ETTask UpdateBounds(bool updateItems) //==========LoopScrollRect==========
  1927. {
  1928. if (m_Content == null) return;
  1929. using var _ = await ET.EventSystem.Instance.YIUIInvokeEntityAsyncSafety<YIUIInvokeEntity_CoroutineLock, ETTask<Entity>>(YIUISingletonHelper.YIUIMgr, new YIUIInvokeEntity_CoroutineLock { Lock = this.GetHashCode() });
  1930. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  1931. m_ContentBounds = GetBounds();
  1932. // ============LoopScrollRect============
  1933. // Don't do this in Rebuild. Make use of ContentBounds before Adjust here.
  1934. if (Application.isPlaying && updateItems)
  1935. {
  1936. var (result, viewBounds, contentBounds) = await UpdateItems(m_ViewBounds, m_ContentBounds);
  1937. m_ViewBounds = viewBounds;
  1938. m_ContentBounds = contentBounds;
  1939. if (result)
  1940. {
  1941. EnsureLayoutHasRebuilt();
  1942. m_ContentBounds = GetBounds();
  1943. }
  1944. }
  1945. // ============LoopScrollRect============
  1946. Vector3 contentSize = m_ContentBounds.size;
  1947. Vector3 contentPos = m_ContentBounds.center;
  1948. var contentPivot = m_Content.pivot;
  1949. AdjustBounds(ref m_ViewBounds, ref contentPivot, ref contentSize, ref contentPos);
  1950. m_ContentBounds.size = contentSize;
  1951. m_ContentBounds.center = contentPos;
  1952. if (movementType == MovementType.Clamped)
  1953. {
  1954. // Adjust content so that content bounds bottom (right side) is never higher (to the left) than the view bounds bottom (right side).
  1955. // top (left side) is never lower (to the right) than the view bounds top (left side).
  1956. // All this can happen if content has shrunk.
  1957. // This works because content size is at least as big as view size (because of the call to InternalUpdateBounds above).
  1958. Vector2 delta = Vector2.zero;
  1959. if (m_ViewBounds.max.x > m_ContentBounds.max.x)
  1960. {
  1961. delta.x = Math.Min(m_ViewBounds.min.x - m_ContentBounds.min.x, m_ViewBounds.max.x - m_ContentBounds.max.x);
  1962. }
  1963. else if (m_ViewBounds.min.x < m_ContentBounds.min.x)
  1964. {
  1965. delta.x = Math.Max(m_ViewBounds.min.x - m_ContentBounds.min.x, m_ViewBounds.max.x - m_ContentBounds.max.x);
  1966. }
  1967. if (m_ViewBounds.min.y < m_ContentBounds.min.y)
  1968. {
  1969. delta.y = Math.Max(m_ViewBounds.min.y - m_ContentBounds.min.y, m_ViewBounds.max.y - m_ContentBounds.max.y);
  1970. }
  1971. else if (m_ViewBounds.max.y > m_ContentBounds.max.y)
  1972. {
  1973. delta.y = Math.Min(m_ViewBounds.min.y - m_ContentBounds.min.y, m_ViewBounds.max.y - m_ContentBounds.max.y);
  1974. }
  1975. if (delta.sqrMagnitude > float.Epsilon)
  1976. {
  1977. contentPos = m_Content.anchoredPosition + delta;
  1978. if (!m_Horizontal)
  1979. contentPos.x = m_Content.anchoredPosition.x;
  1980. if (!m_Vertical)
  1981. contentPos.y = m_Content.anchoredPosition.y;
  1982. AdjustBounds(ref m_ViewBounds, ref contentPivot, ref contentSize, ref contentPos);
  1983. }
  1984. }
  1985. }
  1986. private void UpdateBounds() //==========LoopScrollRect==========
  1987. {
  1988. m_ViewBounds = new Bounds(viewRect.rect.center, viewRect.rect.size);
  1989. m_ContentBounds = GetBounds();
  1990. if (m_Content == null)
  1991. return;
  1992. // ============LoopScrollRect============
  1993. // Don't do this in Rebuild. Make use of ContentBounds before Adjust here.
  1994. // ============LoopScrollRect============
  1995. Vector3 contentSize = m_ContentBounds.size;
  1996. Vector3 contentPos = m_ContentBounds.center;
  1997. var contentPivot = m_Content.pivot;
  1998. AdjustBounds(ref m_ViewBounds, ref contentPivot, ref contentSize, ref contentPos);
  1999. m_ContentBounds.size = contentSize;
  2000. m_ContentBounds.center = contentPos;
  2001. if (movementType == MovementType.Clamped)
  2002. {
  2003. // Adjust content so that content bounds bottom (right side) is never higher (to the left) than the view bounds bottom (right side).
  2004. // top (left side) is never lower (to the right) than the view bounds top (left side).
  2005. // All this can happen if content has shrunk.
  2006. // This works because content size is at least as big as view size (because of the call to InternalUpdateBounds above).
  2007. Vector2 delta = Vector2.zero;
  2008. if (m_ViewBounds.max.x > m_ContentBounds.max.x)
  2009. {
  2010. delta.x = Math.Min(m_ViewBounds.min.x - m_ContentBounds.min.x, m_ViewBounds.max.x - m_ContentBounds.max.x);
  2011. }
  2012. else if (m_ViewBounds.min.x < m_ContentBounds.min.x)
  2013. {
  2014. delta.x = Math.Max(m_ViewBounds.min.x - m_ContentBounds.min.x, m_ViewBounds.max.x - m_ContentBounds.max.x);
  2015. }
  2016. if (m_ViewBounds.min.y < m_ContentBounds.min.y)
  2017. {
  2018. delta.y = Math.Max(m_ViewBounds.min.y - m_ContentBounds.min.y, m_ViewBounds.max.y - m_ContentBounds.max.y);
  2019. }
  2020. else if (m_ViewBounds.max.y > m_ContentBounds.max.y)
  2021. {
  2022. delta.y = Math.Min(m_ViewBounds.min.y - m_ContentBounds.min.y, m_ViewBounds.max.y - m_ContentBounds.max.y);
  2023. }
  2024. if (delta.sqrMagnitude > float.Epsilon)
  2025. {
  2026. contentPos = m_Content.anchoredPosition + delta;
  2027. if (!m_Horizontal)
  2028. contentPos.x = m_Content.anchoredPosition.x;
  2029. if (!m_Vertical)
  2030. contentPos.y = m_Content.anchoredPosition.y;
  2031. AdjustBounds(ref m_ViewBounds, ref contentPivot, ref contentSize, ref contentPos);
  2032. }
  2033. }
  2034. }
  2035. internal static void AdjustBounds(ref Bounds viewBounds, ref Vector2 contentPivot, ref Vector3 contentSize, ref Vector3 contentPos)
  2036. {
  2037. // Make sure content bounds are at least as large as view by adding padding if not.
  2038. // One might think at first that if the content is smaller than the view, scrolling should be allowed.
  2039. // However, that's not how scroll views normally work.
  2040. // Scrolling is *only* possible when content is *larger* than view.
  2041. // We use the pivot of the content rect to decide in which directions the content bounds should be expanded.
  2042. // E.g. if pivot is at top, bounds are expanded downwards.
  2043. // This also works nicely when ContentSizeFitter is used on the content.
  2044. Vector3 excess = viewBounds.size - contentSize;
  2045. if (excess.x > 0)
  2046. {
  2047. contentPos.x -= excess.x * (contentPivot.x - 0.5f);
  2048. contentSize.x = viewBounds.size.x;
  2049. }
  2050. if (excess.y > 0)
  2051. {
  2052. contentPos.y -= excess.y * (contentPivot.y - 0.5f);
  2053. contentSize.y = viewBounds.size.y;
  2054. }
  2055. }
  2056. private readonly Vector3[] m_Corners = new Vector3[4];
  2057. private Bounds GetBounds()
  2058. {
  2059. if (m_Content == null)
  2060. return new Bounds();
  2061. m_Content.GetWorldCorners(m_Corners);
  2062. var viewWorldToLocalMatrix = viewRect.worldToLocalMatrix;
  2063. return InternalGetBounds(m_Corners, ref viewWorldToLocalMatrix);
  2064. }
  2065. internal static Bounds InternalGetBounds(Vector3[] corners, ref Matrix4x4 viewWorldToLocalMatrix)
  2066. {
  2067. var vMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  2068. var vMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  2069. for (int j = 0; j < 4; j++)
  2070. {
  2071. Vector3 v = viewWorldToLocalMatrix.MultiplyPoint3x4(corners[j]);
  2072. vMin = Vector3.Min(v, vMin);
  2073. vMax = Vector3.Max(v, vMax);
  2074. }
  2075. var bounds = new Bounds(vMin, Vector3.zero);
  2076. bounds.Encapsulate(vMax);
  2077. return bounds;
  2078. }
  2079. //==========LoopScrollRect==========
  2080. private Bounds GetBounds4Item(int index)
  2081. {
  2082. if (m_Content == null)
  2083. return new Bounds();
  2084. int offset = index - itemTypeStart;
  2085. if (offset < 0 || offset >= m_Content.childCount)
  2086. return new Bounds();
  2087. var rt = m_Content.GetChild(offset) as RectTransform;
  2088. if (rt == null)
  2089. return new Bounds();
  2090. rt.GetWorldCorners(m_Corners);
  2091. var viewWorldToLocalMatrix = viewRect.worldToLocalMatrix;
  2092. return InternalGetBounds(m_Corners, ref viewWorldToLocalMatrix);
  2093. }
  2094. //==========LoopScrollRect==========
  2095. private Vector2 CalculateOffset(Vector2 delta)
  2096. {
  2097. //==========LoopScrollRect==========
  2098. if (totalCount < 0 || movementType == MovementType.Unrestricted)
  2099. return delta;
  2100. Bounds contentBound = m_ContentBounds;
  2101. if (m_Horizontal)
  2102. {
  2103. float totalSize, offset;
  2104. GetHorizonalOffsetAndSize(out totalSize, out offset);
  2105. Vector3 center = contentBound.center;
  2106. center.x = offset;
  2107. contentBound.Encapsulate(center);
  2108. center.x = offset + totalSize;
  2109. contentBound.Encapsulate(center);
  2110. }
  2111. if (m_Vertical)
  2112. {
  2113. float totalSize, offset;
  2114. GetVerticalOffsetAndSize(out totalSize, out offset);
  2115. Vector3 center = contentBound.center;
  2116. center.y = offset;
  2117. contentBound.Encapsulate(center);
  2118. center.y = offset - totalSize;
  2119. contentBound.Encapsulate(center);
  2120. }
  2121. //==========LoopScrollRect==========
  2122. return InternalCalculateOffset(ref m_ViewBounds, ref contentBound, m_Horizontal, m_Vertical, m_MovementType, ref delta);
  2123. }
  2124. internal static Vector2 InternalCalculateOffset(ref Bounds viewBounds,
  2125. ref Bounds contentBounds,
  2126. bool horizontal,
  2127. bool vertical,
  2128. MovementType movementType,
  2129. ref Vector2 delta)
  2130. {
  2131. Vector2 offset = Vector2.zero;
  2132. if (movementType == MovementType.Unrestricted)
  2133. return offset;
  2134. Vector2 min = contentBounds.min;
  2135. Vector2 max = contentBounds.max;
  2136. // min/max offset extracted to check if approximately 0 and avoid recalculating layout every frame (case 1010178)
  2137. if (horizontal)
  2138. {
  2139. min.x += delta.x;
  2140. max.x += delta.x;
  2141. float maxOffset = viewBounds.max.x - max.x;
  2142. float minOffset = viewBounds.min.x - min.x;
  2143. if (minOffset < -0.001f)
  2144. offset.x = minOffset;
  2145. else if (maxOffset > 0.001f)
  2146. offset.x = maxOffset;
  2147. }
  2148. if (vertical)
  2149. {
  2150. min.y += delta.y;
  2151. max.y += delta.y;
  2152. float maxOffset = viewBounds.max.y - max.y;
  2153. float minOffset = viewBounds.min.y - min.y;
  2154. if (maxOffset > 0.001f)
  2155. offset.y = maxOffset;
  2156. else if (minOffset < -0.001f)
  2157. offset.y = minOffset;
  2158. }
  2159. return offset;
  2160. }
  2161. /// <summary>
  2162. /// Override to alter or add to the code that keeps the appearance of the scroll rect synced with its data.
  2163. /// </summary>
  2164. protected void SetDirty()
  2165. {
  2166. if (!IsActive())
  2167. return;
  2168. LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
  2169. }
  2170. /// <summary>
  2171. /// Override to alter or add to the code that caches data to avoid repeated heavy operations.
  2172. /// </summary>
  2173. protected void SetDirtyCaching()
  2174. {
  2175. if (!IsActive())
  2176. return;
  2177. CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
  2178. LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
  2179. }
  2180. #if UNITY_EDITOR
  2181. protected override void OnValidate()
  2182. {
  2183. SetDirtyCaching();
  2184. }
  2185. #endif
  2186. }
  2187. }