我正在尝试使用此代码行更改UI按钮上的颜色。通过脚本更改UI按钮的颜色
prev.GetComponent<Button>().colors.normalColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);
,但我收到此错误
资产/ _Scripts/OptionSwitch.cs(28,53):错误CS1612:不能修改UnityEngine.UI.Selectable的'值类型返回值.colors'。考虑将该值存储在一个临时变量中
我试图在调用它们之前存储按钮和颜色作为变量,但它不会更改错误代码。
编辑:
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>();
}
}
}
遇到错误资产/ _Scripts/OptionSwitch.cs(10,28):错误CS1519:意外符号'=”在类,结构或接口成员声明和资产/ _Scripts/OptionSwitch.cs( 10,43):错误CS1519:类,结构或接口成员声明中的意外符号'0', – Jdoonan
哪行代码?我上面发布的代码在我身边工作得很好。你做错了什么。我建议你创建一个新的脚本来确保你有这个权利。如果可能,请直接复制答案中的代码。 – Programmer
我直接拷贝它的第10行,是否有一个非标准的命名空间用于定义色块? – Jdoonan