【问题标题】:Unity - How to instantiate prefab at slider`s specific valueUnity - 如何以滑块的特定值实例化预制件
【发布时间】:2019-02-04 13:23:50
【问题描述】:

我正在制作一个基于关卡的 2d 游戏,在每个关卡中,分数跟踪栏中都有三个检查点。玩家必须到达最低的关卡才能通关,但到达第二关和第三关会获得奖励。

我坚持使用滑块作为计分条。我的问题是:

有没有办法在 Start 方法中存储 Slider 栏的特定值并在该位置实例化标记预制件?这是一个例子:

  • 第 1 级滑块的最大值为 100。
  • 我想实例化第一个标记,在 y 中有一些填充,在滑块的 50 位置,第二个在 75 位置,第三个在 100 位置。

我目前的逻辑是,我需要以某种方式获得我想要的值并找到他的 Transform,但我无法找到编码这个的方法,我不知道如何获得我想要的位置。

这里有一些图片来说明我正在尝试做的事情:

【问题讨论】:

  • 您好,从您复制的图片中我会说您知道滑块的宽度,因此您知道它是最左点和最右点,因此您可以通过它们计算标记的位置。假设最左边的点是 0,最右边的是 10,你想要一个标记到 50%,一个标记到 75%。所以第一个标记位置将在 (0+10)*50% = 5 ... 等等。希望这个想法有所帮助。

标签: c# unity3d slider instantiation


【解决方案1】:

我会得到滑块的宽度属性,然后除以sliderMax,结果将是滑块上单个百分比的宽度。然后,您可以添加或减去其中的倍数以获得百分比位置。

示例:slider.x=50 slider.width=200;

increment = slider.width/100; //这将产生两个,每百分比给你两个像素。

所以你 50% 的展示位置是:sliderx+(increment*50);

请记住,这都是伪代码,旨在让您了解如何实现您想要的结果

【讨论】:

  • 谢谢!你的回答帮助我做了我想做的事。
【解决方案2】:

我找到了解决办法!

根据我设法做到这一点的见解:

    void SpawnCheckPoint() {
        mySlider.maxValue = gameLevel[currentLevel].maxValue; //Set the slider's Max Value to the max value of the level.
        float sliderMaxValue = mySlider.maxValue;
        float sliderWidth = slider.GetComponent<RectTransform>().sizeDelta.x; //Get the width of the Slider.
        float zeroValue = slider.transform.position.x - (sliderWidth / 2); //Get the leftmost corner of the slider.

        //Loop to Instantiate the 3 checkpoints.
        for (int i = 0; i < gameLevel[currentLevel].values.Length; i++) { 
            float valueToIncrement = (gameLevel[currentLevel].values[i] / sliderMaxValue); //Get the % of the checkpoint based on the max value of the level.
            float newPos = (sliderWidth * valueToIncrement); //New position in screen

            //Instantiate the object as a child of the Slider
            GameObject checkpoint = Instantiate(checkPoint, new Vector3(zeroValue + newPos - xPadding, slider.transform.position.y - yPadding, slider.transform.position.z),
                                            Quaternion.identity, GameObject.FindGameObjectWithTag("Slider").transform);
        }
    }

这可能不是做我想做的最好的方式,但它工作得很好。

感谢所有试图帮助我的人,您的见解非常有用。

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 2016-11-04
    • 2021-10-27
    • 1970-01-01
    • 2014-08-28
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多