这是一个简单的手卡框架,以unity的horizontal layout group组件为基础。
把Child Force Expand Width取消勾选后子对象将会根据间距来排列。但是不会自动设置不超出父级的大小范围。因此我写一个脚本来根据子级对象的数量修改间距。
首先是限制手卡数量。手卡间距为x,手卡满时间距为xmin,随着手卡数量的增多,间距逐渐减小,同时手卡总宽度在增大,手卡总宽度设置为y,最大宽度为ymax。这个公式各位就见仁见智了,我用最简单的方法来实现。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HandShow : MonoBehaviour
{
HorizontalLayoutGroup Hor;
List<int> Hands = new();
int length;
int interval;// 手卡间隔
public int max_length;
// Start is called before the first frame update
void Start()
{
Hor = gameObject.GetComponent<HorizontalLayoutGroup>();
Hor.spacing=interval;
length = Hands.Count;
}
// Update is called once per frame
void Update()
{
length=Hands.Count;
//根据手卡数量更改间隔
interval=-50-length;
Hor.spacing = interval;
}
void AddCard(int num)
{
if (length >= max_length)
{
Debug.Log("手卡满了");
return;
}
Hands.Add(num);
}
}