从 Canvas Scaler (Unity) 检索缩放量 [英] Retrieving the amount of scaling from the Canvas Scaler (Unity)

查看:21
本文介绍了从 Canvas Scaler (Unity) 检索缩放量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究一个健康条,它会慢慢消耗你的健康值.我按照本教程获得了我想要的健康栏:

Unity 的回答是:在画布缩放后,您应该能够从画布上的 scaleFactor 读取它,因为画布缩放器只是控制这个值."

但是,无论 UI 变得多小,scaleFactor 的值始终为 1.0.我不知道这是为什么,Unity 再也没有回应.有没有其他人有幸提取过这个值?

作为一种变通方法,您有 CanvasScaler 脚本的对象上的 RectTransform 的 localScale 应反映整个 UI 的当前比例.

I am currently working on a healthbar which slowly drains the less health you have. I followed this tutorial to get the healthbars I wanted: https://www.youtube.com/watch?v=NgftVg3idB4

In short, it uses a mask layer and a seperate green bar to indicate the amount of health. By moving the green bar to the left, it disappears behind the mask layer and thus shows less and less health. The method to calculate its position based on the amount of health is here: Code (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
*/

This is the setting I use for the canvas the healthbar is drawn on.

The trouble is(probably) that because of the scaling the canvas does, healthTransform.rect.width still returns the original size of the healthbar and not the new, scaled size. So is there a way to find out how much the Canvas Scaler has scaled things?

解决方案

I asked the same question back in December on the Unity forums:

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

The answer from Unity was: "After the canvas has been scaled you should be able to just read it back from the scaleFactor on the canvas as the canvas scaler just controls this value. "

But, no matter how small the UI gets, the value of scaleFactor is always 1.0. I don't know why this is, and Unity never responded again. Has anyone else had any luck being able to extract this value?

As a workaround, The RectTransform's localScale on the object you have CanvasScaler script on should reflect the current scale of the entire UI.

这篇关于从 Canvas Scaler (Unity) 检索缩放量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆