我正在尝试为我的Unity项目创建一个新元素但是我需要统一来将我的整个对象渲染为UI对象如何实现这一点。到目前为止我目前的剧本。
using UnityEditor;
using UnityEngine;
public class OptionSwitch : MonoBehaviour {
[MenuItem ("GameObject/UI/Switch")]
static void Switch(){
GameObject go = new GameObject("switch");
go.transform.parent = Selection.activeTransform;
go.transform.localPosition = Vector3.zero;
}
}
它将是一个选项开关,文本框两侧有一个按钮,表示活动选项。
我做了更多研究并提出了这段代码。
using UnityEditor;
using UnityEngine;
public class OptionSwitch : MonoBehaviour {
[MenuItem ("GameObject/UI/Switch")]
static void Switch(){
if (GameObject.Find ("Canvas") != null) {
// Define Components
GameObject Canvas = GameObject.Find("Canvas");
GameObject Switch = new GameObject("Switch");
GameObject Previous = new GameObject("Previous Button");
GameObject Next = new GameObject("Next Button");
GameObject Text = new GameObject("Textbox");
// Place Switch
Switch.transform.parent = Canvas.transform;
Switch.transform.localPosition = Vector3.zero;
// Place Previous Button
Previous.transform.parent = Switch.transform;
Previous.transform.localPosition = Vector3.zero;
// Place Text Field
Text.transform.parent = Switch.transform;
Text.transform.localPosition = Vector3.zero;
// Place Next Field
Next.transform.parent = Switch.transform;
Next.transform.localPosition = Vector3.zero;
}
}
}
答案 0 :(得分:0)
您必须先找到Canvas
GameObject。 Canvas
GameObject附加了Canvas
个组件。因此,您使用FindObjectOfType
来查找Canvas
组件。然后,您可以将该Canvas
脚本的实例转换为GameObject。您原始代码的修复程序:
[MenuItem("GameObject/UI/Switch")]
static void Switch()
{
//Create new GameObject
GameObject go = new GameObject("switch");
//Find Canvas in the Scene
Canvas canvas = (Canvas)GameObject.FindObjectOfType(typeof(Canvas));
//Get Canvas GameObject
GameObject canvasGameObject = canvas.gameObject;
//Make the new GameObject child of the Canvas
go.transform.parent = canvasGameObject.transform;
go.transform.localPosition = Vector3.zero;
//Change the new GameObject Layer to UI
go.layer = 5; //Or go.layer = canvasGameObject.layer;
//Add Rect Transform to it
go.AddComponent<RectTransform>();
}