当前位置:网站首页>【Unity3D】嵌套使用Layout Group制作拥有动态子物体高度的Scroll View
【Unity3D】嵌套使用Layout Group制作拥有动态子物体高度的Scroll View
2022-07-02 06:36:00 【趁着头发多我想做游戏】
注1:本解决方案参考 StackOverFlow
注2:本解决方案只使用UGUI自带的组件,不造轮子
注3:下文使用UGUI自带的Scroll View组件,由于Scroll View和Content都是Unity自带的命名,因此不再赘述其具体的功能
需求
搭建聊天界面或者其他需要根据子物体具体高度(宽度同理)动态改变的界面
想要的效果

遇到的问题
由于通常的做法是ScrollView组件下的Content挂载某个(Grid/Horizontal/Vertical)LayoutGroup,然后通过调节LayoutGroup上的属性来控制子物体的宽高,这样的做法会导致每一个子物体都有相同的宽高,而无法根据子物体的具体高度(比如想根据子物体的Text上的文字数量来自动调整整个子物体的高度,从而调整整个ScrollView的高度)
解决方案
ScrollView 下的 Content 挂载 ContentSizeFitter (Vertical Fit = Preferred Size) 和 Vertical Layout Group(Child Controls Size Width / Height = true),ContentSizeFitter主要作用是根据子物体的宽高来调节Content的宽高,Child Controls Size是让子物体能够自己控制自己的宽高,注意这里不要选择Child Force Expand ,否则子物体的宽高又不能控制了。
聊天界面一般由头像和对话框组成,那么我们就可以通过在根节点添加Horizontal Layout Group(因为头像和对话框一般是横向布局的),然后对话框添加Vertical Layout Group来控制自身纵向的高度。
此时你会发现头像的RectTransform宽高都不能设置了,因为你在子物体的根节点使用了Horizontal Layout Group控制了头像和对话框的布局。
想设置其宽高也很简单,只要在头像上挂载 Layout Element ,然后调节Min Width/Min Height 和 Preferred Width/Preferred Height即可。
一个小技巧
现在的聊天界面填充方向是从上往下的(即 Pivot = (0.5,1)),若想从下往上,则需要调节父物体的Pivot = (0.5,0),原理不明,还请各位老师赐教

最终效果

原文来自 CSDN博主 【趁着头发多我想做游戏】https://blog.csdn.net/weixin_37658157/article/details/104558947 转载请注明出处
边栏推荐
猜你喜欢

Kinect DK obtains color RGB images in cv:: mat format (used in openpose)

Skywalking理论与实践

【虚幻】自动门蓝图笔记

2837xd code generation module learning (3) -- IIC, ECAN, SCI, watchdog, ECAP modules

Blender海洋制作

What wires are suitable for wiring on bread board?

Matlab generates DSP program -- official routine learning (6)

Blender多鏡頭(多機比特)切換

C language programming problems

ICLR 2022: how does AI recognize "things I haven't seen"?
随机推荐
C language strawberry
Alibaba cloud SMS service
Tee command usage example
ue虛幻引擎程序化植物生成器設置——如何快速生成大片森林
Share a blog (water blog)
Matlab代码生成之SIL/PIL测试
【leetcode】33. Search rotation sort array
Career planning and development
Error reporting on the first day of work (error reporting when Nessus installs WinPcap)
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
Database -- acid of transaction -- introduction / explanation
The primary market project galaxy will conduct public offering on coinlist on February 17
A model can do two things: image annotation and image reading Q & A. VQA accuracy is close to human level | demo can be played
【虚幻】过场动画笔记
ICLR 2022: how does AI recognize "things I haven't seen"?
【虚幻】武器插槽:拾取武器
Project practice, redis cluster technology learning (12)
Matlab generates DSP program -- official routine learning (6)
MySQL transaction
UE5——AI追逐(蓝图、行为树)