我正在嘗試使用此代碼行更改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