无法通过脚本更改游戏对象颜色? [英] Can't change GameObject color via script?

查看:38
本文介绍了无法通过脚本更改游戏对象颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于 UI 的画布,图像与画布大小相同.Imagergba0,0,0,0 ,使其不可见(因为 a 是0).我想让图像从脚本中淡入黑色.这是我正在使用的代码:

I have a canvas for UI, with an image the same size of the canvas. The Image has an rgba of 0,0,0,0 , making it invisible (because the a is 0). I want to have the image fade into black from a script. Here is the code I am using:

public class NavigationC : MonoBehaviour {
    public Image screen;
    float fadeTime = 3f;
    Color colorToFadeTo;

    void StartGame()
    {
        colorToFadeTo = new Color(0f, 0f, 0f, 255f);
        screen.CrossFadeColor(colorToFadeTo, fadeTime, true, true);
    }
}

现在,这在执行时不会做任何事情.但是,当我统一手动更改图像的 a 值以使图像可见时,我可以看到脚本更改了图像的颜色.所以脚本确实有效,它只是不可见,因为 a 值没有被脚本改变.那么如何让图像从不可见变为黑色?

Now, this doesn't do anything when executed. But when I change the image's a value manually in unity so that the image becomes visible, I can see the script changing the image's color. So the script does work, it just isn't visible because the a value is not being changed by the script. So how can I make the image fade from invisible to black?

推荐答案

这是你的问题:

新颜色(0f, 0f, 0f, **255f**);

Color 构造函数参数采用从 0f1f 的值,但您将 0f 传递给 255f 范围值.

The Color constructor parameter takes values from 0f to 1f but you are passing 0f to 255f range value to it.

应该是:

colorToFadeTo = new Color(0f, 0f, 0f, 1f);

如果你想使用0255的范围,那么你必须除以255.

If you want to use the 0 to 255 range then you must divide it by 255.

colorToFadeTo = new Color(0f, 0f, 0f, 255f/255f);

<小时>

此外,还有 Color32可以取 0255 之间的值.您可以使用它,然后将其变回颜色.


Also, there is Color32 which can take values between 0 and 255. You can use that then covert it back to color.

Color32 color32 = new Color32(0f, 0f, 0f, 255f));
Color color = color32;

这篇关于无法通过脚本更改游戏对象颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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