简体   繁体   English

尽管 Selectable 已禁用,但 Unity UI 图像不会改变颜色

[英]Unity UI image doesn't change color although Selectable disabled

I am instantiating a UI image prefab in Unity and sets its color, but it doesn't work.我正在 Unity 中实例化一个 UI 图像预制件并设置它的颜色,但它不起作用。

This is my code:这是我的代码:

public class Test
{
    public ImageInitializer pImage;

    private void Start()
    {
        var temp = Instantiate(pImage, GameObject.FindObjectOfType<Canvas>().transform);
        temp.Selectable = false;
        temp.Color = Color.red;
    }
}

public class ImageInitializer : MonoBehaviour
{
    public Image image;
    public Selectable selectable;

    public bool Selectable
    {
        set => selectable.enabled = value;
    }

    public Color Color
    {
        set => image.color = value;
    }
}

And the prefab is just a simple UI button with the ImageInitializer script on it.预制件只是一个简单的 UI 按钮,上面有 ImageInitializer 脚本。

But it doesn't set the color.但它没有设置颜色。 in fact, the image component's color is set, but it is still using the selectable's normal color.其实图片组件的颜色已经设置好了,但是还是使用了selectable的正常颜色。 If I turn it on and off in the editor everything is working.如果我在编辑器中打开和关闭它,一切正常。

Do you know why it doesn't update the image¿你知道为什么它不更新图像吗?

=== EDIT === ===编辑===

So far I tried LayoutRebuilder.ForceRebuildLayoutImmediate(temp.transform as RectTransform) and temp.image.SetAllDirty() and a coroutine that disables the Selectable , wait one frame and sets the color.到目前为止,我尝试了LayoutRebuilder.ForceRebuildLayoutImmediate(temp.transform as RectTransform)temp.image.SetAllDirty()以及禁用Selectable的协程,等待一帧并设置颜色。

Nothing worked...没有任何效果...

I think you want to make a custom image class which is selectable, make a custom class which has an image you can manipulate which is also a child of 'Selectable'.我认为您想制作一个可选的自定义图像 class,制作一个自定义 class 具有您可以操作的图像,它也是“可选”的子图像。 Right now you have a random selectable not attached to anything/doing anything.现在你有一个随机选择不附加到任何东西/做任何事情。 You can make the code your own but something like this:您可以制作自己的代码,但如下所示:

public class ImageInitializer : Selectable
    {
    public Image image;

    //use enabled = true or enabled = false;

    public Color Color
    {
        set => image.color = value;
    }
}

Then you can implement methods like 'OnPointerEnter' 'OnPointerExit' 'OnPointerDown'... etc然后你可以实现像'OnPointerEnter''OnPointerExit''OnPointerDown'...等方法

Which version of unity editor are u using?您使用的是哪个版本的统一编辑器?

I guess its just an issue with not rebuilding.我想这只是不重建的问题。

public ImageInitializer pImage;
private void Start()
{
    var temp = Instantiate(pImage, GameObject.FindObjectOfType<Canvas>().transform);
    temp.Selectable = false;
    temp.Color = Color.red;
    LayoutRebuilder.ForceRebuildLayoutImmediate(temp.GetComponent<RectTransform>());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM