gpt4 book ai didi

c# - 通过脚本更改 UI 按钮的颜色

转载 作者:行者123 更新时间:2023-11-30 23:23:01 29 4
gpt4 key购买 nike

我正在尝试使用这行代码更改 UI 按钮上的颜色。

prev.GetComponent<Button>().colors.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);

但是我收到了这个错误

Assets/_Scripts/OptionSwitch.cs(28,53): error CS1612: Cannot modify a value type return value of `UnityEngine.UI.Selectable.colors'. Consider storing the value in a temporary variable

我试过在调用它们之前将按钮和颜色都存储为变量,但它不会更改错误代码。

编辑:

using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Sprites;

public class OptionSwitch : MonoBehaviour {

ColorBlock colorBlock = new ColorBlock();
colorBlock.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);

[MenuItem ("GameObject/UI/Switch")]
static void Switch(){

if (GameObject.FindObjectOfType (typeof(Canvas)) != null) {

Canvas canvas = (Canvas)GameObject.FindObjectOfType (typeof(Canvas));

// Define Previous Button
GameObject prev = new GameObject ("Previous", typeof(Button));
prev.layer = 5;
prev.AddComponent<Image> ();
prev.transform.parent = canvas.transform;

prev.GetComponent<Image> ().sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UISprite.psd");
prev.GetComponent<Button>().colors = buttonColors;

// Define Previous Button Image
GameObject previm = new GameObject("Previous Image", typeof(RawImage));
previm.layer = 5;
previm.transform.parent = prev.transform;

} else {

// Create Canvas
GameObject canvas = new GameObject("Canvas", typeof(Canvas));
canvas.AddComponent<CanvasScaler> ();
canvas.AddComponent<GraphicRaycaster> ();
canvas.layer = 5;
canvas.GetComponent<Canvas> ().renderMode = RenderMode.ScreenSpaceOverlay;
canvas.transform.localPosition = Vector3.zero;

// Create Event System
GameObject eventsystem = new GameObject("EventSystem", typeof(EventSystem));
eventsystem.AddComponent<StandaloneInputModule>();
eventsystem.AddComponent<TouchInputModule>();

}

}

}

最佳答案

您必须更改 colors不是 normalColor . GetComponent<Button>().colors返回 ColorBlock .

因此,创建 ColorBlock 的新实例.修改normalColor来自那个ColorBlock然后分配ColorBlockGetComponent<Button>().colors .

完整示例:

ColorBlock colorBlock = new ColorBlock();
colorBlock.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);

prev.GetComponent<Button>().colors = colorBlock;

这将覆盖您的其他颜色设置。为了保护它们,创建你的 ColorBlock来自 prev.GetComponent<Button>().colors;

ColorBlock colorBlock = prev.GetComponent<Button>().colors;
colorBlock.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);

prev.GetComponent<Button>().colors = colorBlock;

您还可以修改以下颜色属性:

colorBlock.pressedColor = new Color(1f, 0.0f, 0.0f, 1.0f);
colorBlock.highlightedColor = new Color(0f, 1f, 0.0f, 1.0f);
colorBlock.disabledColor = new Color(0f, 0f, 1, 1.0f);

关于c# - 通过脚本更改 UI 按钮的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38546130/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com