UI 中的堆叠效果和通电 |统一 C#

问题描述

我怎么能做到这一点,例如,如果只有一个东西会移动到第一个位置,我想你知道我的意思......那么我怎么能做到这一点?1

我想过使用数组,但我不明白如何。

这是我目前的代码,它只是显示和隐藏但不移动它们,所以只有一个间隙。

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class UI : MonoBehavIoUr
{
    public Text myText;
    public GameObject Player;
    public GameObject SugarIcon;
    public GameObject DashIcon;
    public GameObject JumpIcon;
    public GameObject ShieldIcon;
    private string dashreadystring;
    private string doublejumpstring;
    private string triplejumpstring;
    private string shieldbuffstring;
    private int iconamount = 0;
    
    void Start()
    {
        GameObject Player = GameObject.Find("Player");
    }

    void Update()
    {
        PlayerScript PlayerScript = Player.GetComponent<PlayerScript>();
        bool dashready = PlayerScript.canDash;
        float sugarbuff = PlayerScript.sugarbuffactive;
        int airJumpCount = PlayerScript.airJumpCount;
        int airJumpCountMax = PlayerScript.airJumpCountMax;
        bool canDoubleJump = PlayerScript.canDoubleJump;
        bool shieldon = PlayerScript.shieldon;
        float score = Player.transform.position.x;

        // If Dash is ready,show icon,if not,hide it.
        if (dashready == true)
        {
            DashIcon.GetComponent<Renderer>().enabled = true;
        }
        else
        {
            DashIcon.GetComponent<Renderer>().enabled = false;
        }

        // If Sugarbuff is active,hide it.
        if (sugarbuff == 1.5)
        {
            SugarIcon.GetComponent<Renderer>().enabled = true;
        }
        else
        {
            SugarIcon.GetComponent<Renderer>().enabled = false;
        }

        // If can jump,if ((airJumpCount < airJumpCountMax) | ((canDoubleJump) && (sugarbuff == 1.5f)))
        {
            JumpIcon.GetComponent<Renderer>().enabled = true;
        }
        else
        {
            JumpIcon.GetComponent<Renderer>().enabled = false;
        }
        if (shieldon)
        {
            ShieldIcon.GetComponent<Renderer>().enabled = true;
        }
        else
        {
            ShieldIcon.GetComponent<Renderer>().enabled = false;
        }
    }
}

我怎么能做到这一点?谢谢。

解决方法

如果您的图标是使用 Horizo​​ntalLayoutGroup 组件的父容器的子项,它将自动水平排列您的图标(使用 VerticalLayoutGroup 或 GridLayoutGroup 以不同的模式自动对齐)。

然后,如果您禁用图标的游戏对象,它们将消失。 Horizo​​ntalLayoutGroup 将按照我认为你想要的方式重新排列剩余的图标。当您重新启用图标时,它会重新插入到水平布局中。

注意事项:

  1. 您当前正在禁用游戏对象上的渲染器组件。这确实使对象不可见,但它仍然存在并占用空间。相反,禁用图标本身的游戏对象 (SugarIcon.enabled = false)。希望 Icon 对象只是图像,上面没有脚本/逻辑,但如果是这样,您需要将其解耦。

  2. 看起来您每帧都多次使用 GetComponent() 调用。不要这样做——GetComponent() 调用有相当大的开销。相反,在初始化管理器时调用一次,然后缓存结果。这将节省大量的处理工作。

// 调用 GetComponent() 并缓存一次引用(当您初始化对象时)。

Renderer sugarIconRenderer = SugarIcon.GetComponent<Renderer>();

// 在需要时每帧调用缓存的引用。

sugarIconRenderer.enabled = false;