赞
踩
Canvas(画布)是Unity UGUI系统中的一个重要组件,用于在屏幕上绘制UI元素。它是UI元素的容器,可以包含各种UI元素,如按钮、文本、图像等。Canvas组件提供了一种方便的方式来管理和渲染UI元素。
Canvas组件通过渲染器将UI元素绘制到屏幕上。它使用层级结构来管理UI元素的显示顺序,可以通过设置UI元素的层级来控制它们的显示顺序。Canvas组件还可以设置渲染模式,包括屏幕空间、世界空间和摄像机空间等。
using UnityEngine; using UnityEngine.UI; public class CanvasExample : MonoBehaviour { void Start() { // 创建一个屏幕空间的Canvas GameObject canvasObject = new GameObject("Canvas"); Canvas canvas = canvasObject.AddComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; // 创建一个UI元素 GameObject textObject = new GameObject("Text"); textObject.transform.SetParent(canvas.transform); Text text = textObject.AddComponent<Text>(); text.text = "Hello World!"; } }
操作步骤:
using UnityEngine; using UnityEngine.UI; public class CanvasExample : MonoBehaviour { void Start() { // 创建一个世界空间的Canvas GameObject canvasObject = new GameObject("Canvas"); Canvas canvas = canvasObject.AddComponent<Canvas>(); canvas.renderMode = RenderMode.WorldSpace; // 创建一个UI元素 GameObject textObject = new GameObject("Text"); textObject.transform.SetParent(canvas.transform); Text text = textObject.AddComponent<Text>(); text.text = "Hello World!"; } }
操作步骤:
using UnityEngine; using UnityEngine.UI; public class CanvasExample : MonoBehaviour { void Start() { // 创建一个屏幕空间的Canvas GameObject canvasObject = new GameObject("Canvas"); Canvas canvas = canvasObject.AddComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; // 创建两个UI元素 GameObject textObject1 = new GameObject("Text1"); textObject1.transform.SetParent(canvas.transform); Text text1 = textObject1.AddComponent<Text>(); text1.text = "Text 1"; text1.canvas.sortingLayerName = "UI"; text1.canvas.sortingOrder = 1; GameObject textObject2 = new GameObject("Text2"); textObject2.transform.SetParent(canvas.transform); Text text2 = textObject2.AddComponent<Text>(); text2.text = "Text 2"; text2.canvas.sortingLayerName = "UI"; text2.canvas.sortingOrder = 2; } }
操作步骤:
using UnityEngine; using UnityEngine.UI; public class CanvasExample : MonoBehaviour { void Start() { // 创建一个屏幕空间的Canvas GameObject canvasObject = new GameObject("Canvas"); Canvas canvas = canvasObject.AddComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.pixelPerfect = true; // 创建一个UI元素 GameObject textObject = new GameObject("Text"); textObject.transform.SetParent(canvas.transform); Text text = textObject.AddComponent<Text>(); text.text = "Hello World!"; } }
操作步骤:
using UnityEngine; using UnityEngine.UI; public class CanvasExample : MonoBehaviour { void Start() { // 创建一个屏幕空间的Canvas GameObject canvasObject = new GameObject("Canvas"); Canvas canvas = canvasObject.AddComponent<Canvas>(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.referencePixelsPerUnit = 100; // 创建一个UI元素 GameObject textObject = new GameObject("Text"); textObject.transform.SetParent(canvas.transform); Text text = textObject.AddComponent<Text>(); text.text = "Hello World!"; } }
操作步骤:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。