从Canvas Scaler(Unity)中检索缩放量

时间:2015-01-06 18:50:16

标签: c# unity3d 2d

我目前正在开发一个健康栏,慢慢消耗你的健康状况。我按照本教程获取了我想要的健康栏:https://www.youtube.com/watch?v=NgftVg3idB4

简而言之,它使用遮罩层和单独的绿色条来指示健康状况。通过向左移动绿色条,它会消失在遮罩层后面,从而显示出越来越少的健康状况。 根据健康状况计算其位置的方法如下: 代码(CSharp):

float maxXValue = healthTransform.position.x;
float minXValue = healthTransform.position.x - healthTransform.rect.width;

private void HandleHealth()
{
    Stats attachedStats = attachedObject.GetComponent<Stats>();

    float currentXValuePlayer = MapValues(attachedStats.currentHealth, 0, attachedStats.maxHealth, minXValue, maxXValue);
    healthTransform.position = new Vector3(currentXValuePlayer, cachedY);
}

private float MapValues(float x, float inMin, float inMax, float outMin, float outMax)
{
    return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}
/*
EXPLANATION:
attachedStats.currentHealth is the current health the player has
attachedStats.maxHealth is the maximum amount of health the player can have
minXValue is the furthest left point the bar is at when health is 0
maxXValue is the furthest right point the bar is at when health is full
*/

这是我用于绘制健康栏的画布的设置。 [​IMG]

麻烦(可能)是因为画布的缩放,healthTransform.rect.width仍然返回健康栏的原始大小,而不是新的缩放大小。那么有没有办法找出Canvas Scaler有多大比例缩放?

3 个答案:

答案 0 :(得分:9)

我在12月份的Unity论坛上回答了同样的问题:

http://forum.unity3d.com/threads/canvasscaler-current-scale.285134/

Unity的答案是: &#34;在缩放画布后,您应该能够从画布上的scaleFactor读取它,因为画布缩放器只是控制此值。 &#34;

但是,无论UI有多小,scaleFactor的值始终为1.0。我不知道为什么会这样,Unity再也没有回应过。有没有其他人有运气能够提取这个价值?

作为一种解决方法,CanvasScaler脚本所使用的对象上的RectTransform的localScale应该反映整个UI的当前比例。

答案 1 :(得分:2)

有一种更简单的方法来处理绿色条的宽度 - 这是使它成为一个&#34;填充&#34;图像类型。这样你根本不需要面具,这简化了一些事情。


使用填充

在Unity 4.6+中创建健康栏

创建一个包含所需图像的画布对象(在本例中为红色背景栏,绿色前景栏和轮廓)。

enter image description here

按此顺序放置时,最低的图像将显示在顶部(见下文)。

enter image description here

结果将是一个如下所示的健康栏:

enter image description here

但是,现在我们需要能够根据生命值的数量来控制绿色条的宽度。为此,我们可以修改&#34; Green Bar&#34;:

的图像组件
  • 将类型更改为&#34;已填充&#34;
  • 将填充方法更改为&#34;水平&#34;
  • 将填充原点更改为&#34; Left&#34;。

enter image description here

现在可以通过修改填充量来控制绿条的宽度。 (您可以使用滑块测试它)

最后,你必须添加一个脚本来设置绿色条的宽度,它在C#中可能如下所示:

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

public class HealthBar : MonoBehaviour {

    public float MaxHealth = 100;
    private float _playerHealth;
    private Image _greenBar

    void Start () {
            _playerHealth = MaxHealth;
            _greenBar = transform.FindChild("GreenBar").GetComponent<Image>();
    }

    void Update () {

            //logic to set _playerHealth goes here

            _greenBar.fillAmount = _playerHealth/MaxHealth;
    }
}

答案 2 :(得分:0)

我今天遇到了这个问题(在提出问题后大约三年),发现通过在scaleFactorStart()的Canvas对象上使用Update(),我能够获得缩放面罩运动的适当因素。但是,Awake()似乎没有可靠地设置该值,这可能会引起一些悲伤。

为了将来参考,您不需要任何形式的解决方法,正如Farmer Joe的回答中所建议的那样。如果有一个错误 - 我怀疑 - 它已被修复。

相关问题