Как найти canvas в скрипте unity

class in
UnityEngine

/

Inherits from:Behaviour

/

Implemented in:UnityEngine.UIModule

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Your name

Your email

Suggestion*

Cancel

Switch to Manual

Description

Element that can be used for screen rendering.

Elements on a canvas are rendered AFTER Scene rendering, either from an attached camera or using overlay mode.

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

// Create a Canvas that holds a Text GameObject.

public class ExampleClass : MonoBehaviour { void Start() { GameObject myGO; GameObject myText; Canvas myCanvas; Text text; RectTransform rectTransform;

// Canvas myGO = new GameObject(); myGO.name = "TestCanvas"; myGO.AddComponent<Canvas>();

myCanvas = myGO.GetComponent<Canvas>(); myCanvas.renderMode = RenderMode.ScreenSpaceOverlay; myGO.AddComponent<CanvasScaler>(); myGO.AddComponent<GraphicRaycaster>();

// Text myText = new GameObject(); myText.transform.parent = myGO.transform; myText.name = "wibble";

text = myText.AddComponent<Text>(); text.font = (Font)Resources.Load("MyFont"); text.text = "wobble"; text.fontSize = 100;

// Text position rectTransform = text.GetComponent<RectTransform>(); rectTransform.localPosition = new Vector3(0, 0, 0); rectTransform.sizeDelta = new Vector2(400, 200); } }

Properties

additionalShaderChannels Get or set the mask of additional shader channels to be used when creating the Canvas mesh.
cachedSortingLayerValue Cached calculated value based upon SortingLayerID.
isRootCanvas Is this the root Canvas?
normalizedSortingGridSize The normalized grid size that the canvas will split the renderable area into.
overridePixelPerfect Allows for nested canvases to override pixelPerfect settings inherited from parent canvases.
overrideSorting Override the sorting of canvas.
pixelPerfect Force elements in the canvas to be aligned with pixels. Only applies with renderMode is Screen Space.
pixelRect Get the render rect for the Canvas.
planeDistance How far away from the camera is the Canvas generated.
referencePixelsPerUnit The number of pixels per unit that is considered the default.
renderingDisplaySize Returns the canvas display size based on the selected render mode and target display.
renderMode Is the Canvas in World or Overlay mode?
renderOrder The render order in which the canvas is being emitted to the Scene. (Read Only)
rootCanvas Returns the Canvas closest to root, by checking through each parent and returning the last canvas found. If no other canvas is found then the canvas will return itself.
scaleFactor Used to scale the entire canvas, while still making it fit the screen. Only applies with renderMode is Screen Space.
sortingLayerID Unique ID of the Canvas’ sorting layer.
sortingLayerName Name of the Canvas’ sorting layer.
sortingOrder Canvas’ order within a sorting layer.
targetDisplay For Overlay mode, display index on which the UI canvas will appear.
worldCamera Camera used for sizing the Canvas when in Screen Space — Camera. Also used as the Camera that events will be sent through for a World Space Canvas.

Static Methods

Events

Inherited Members

Properties

enabled Enabled Behaviours are Updated, disabled Behaviours are not.
isActiveAndEnabled Reports whether a GameObject and its associated Behaviour is active and enabled.
gameObject The game object this component is attached to. A component is always attached to a game object.
tag The tag of this game object.
transform The Transform attached to this GameObject.
hideFlags Should the object be hidden, saved with the Scene or modifiable by the user?
name The name of the object.

Public Methods

BroadcastMessage Calls the method named methodName on every MonoBehaviour in this game object or any of its children.
CompareTag Checks the GameObject’s tag against the defined tag.
GetComponent Gets a reference to a component of type T on the same GameObject as the component specified.
GetComponentInChildren Gets a reference to a component of type T on the same GameObject as the component specified, or any child of the GameObject.
GetComponentInParent Gets a reference to a component of type T on the same GameObject as the component specified, or any parent of the GameObject.
GetComponents Gets references to all components of type T on the same GameObject as the component specified.
GetComponentsInChildren Gets references to all components of type T on the same GameObject as the component specified, and any child of the GameObject.
GetComponentsInParent Gets references to all components of type T on the same GameObject as the component specified, and any parent of the GameObject.
SendMessage Calls the method named methodName on every MonoBehaviour in this game object.
SendMessageUpwards Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.
TryGetComponent Gets the component of the specified type, if it exists.
GetInstanceID Gets the instance ID of the object.
ToString Returns the name of the object.

Operators

bool Does the object exist?
operator != Compares if two objects refer to a different object.
operator == Compares two object references to see if they refer to the same object.

Unity WebGL can display 3D content because it uses a web standard called WebGL.
I’m sure we all figured that out by the platform build name.
It is basically a web version of an open-spec and mature 3D graphics API called OpenGL. WebGL works by drawing 3D content on to an HTML5 canvas element in the same way OpenGL would draw 3D content on to a native application UI. What happens if you want to mess with the canvas node?

TL;DR

Let’s get to the point for people who don’t need background information or just want the answer immediately! In the Javascript call …

<script>
    var gameInstance = 
        UnityLoader.instantiate(
            "gameInstance", 
            "/blog/content/ProjectName/Build/BuildDir.json", 
            {onProgress: UnityProgress});
</script>

… the gameInstance variable has a Module member. And that Module object has a member called canvas. That’s the canvas DOM object. Do with it what you will.
Since the time of this writing, the sample HTML that Unity generates now calls this variable unityInstance.

var domCanvas = gameInstance.Module.canvas;

Do with that as you would any other Canvas node.

A Light Crash Course on the DOM

The canvas element is an HTML DOM node. The DOM a tree hierarchy that represents the page being viewed. When the site is first downloaded to the browser, it initially exists as the HTML source – but the DOM can be manipulated via JavaScript. Using JavaScript, DOM nodes can be:

  • New nodes can be added or destroyed.
  • Nodes can be shown or hidden.
  • Nodes can be moved.
  • Nodes can have their styles manipulated.

So to recap:

  • A Unity WebGL app exists as a JavaScript program
  • The app is able to render 3D content in the browser by using the WebGL API
  • The WebGL API operates on a canvas node.
  • a canvas node is an HTML tag.

Where is it in the HTML Source?

So, where is it? How can I do stuff with it? Well, let’s look at a common snippet of HTML/Javascript I used to embed content into WordPress. You’ll notice plenty of div elements, but where’s the canvas element?

<script src="/blog/content/WebHalt/TemplateData/UnityProgress.js"></script>
<script src="/blog/content/WebHalt/Build/UnityLoader.js"></script>
<script>var gameInstance= UnityLoader.instantiate("gameInstance", "/blog/content/WebHalt/Build/WebHalt.json", {onProgress: UnityProgress});</script>
<div class="webgl-content">
   <div id="gameInstance" style="width: 960px; height: 600px">
</div>

Well, the canvas doesn’t exist until the UnityLoader.instantiate() is called. When it’s called, it will find the DOM element that has the same id as the first parameter passed in (i.e. gameInstance). So the canvas doesn’t exist in the HTML source file, only the parent container where it will eventually be created into.

In this post where I don’t instance the app until a placeholder image is clicked, here’s what the DOM hierarchy looks like before and after the app is instanced.

Examples

Some examples of what can be done with access to the canvas. Really you can do anything with the canvas that you could do with any DOM node – so this is in no way comprehensive. Do you ever need to do any of these things or anything else with the canvas? Unless you’re trying to do something exotic that requires the right WebGL app and browser/DOM integration, the chances are that you don’t. But for more exotic Unity WebGL applications, now you’ll know.

Demo

Some explanations of them and a few other things below the demo.

Fullscreen

There’s nothing special you have to do with the canvas to fullscreen the app. This is because the app is built with a handy function you can call. It’s even in the sample HTML that Unity generates for you when you build a WebGL app.

gameInstance.SetFullscreen(true);

Restoring the app from the fullscreen status can be done by either calling the same function with a false parameter or by pressing the escape key.

Unloading The App

For Unity 2018, this article used to say that WebGL apps could not be unloaded after they’re created. Any attempt to delete them would spam errors indefinitely.

In Unity 2019 the canvas can now be deleted without issues.

// Delete the Canvas DOM object hosting the game.
gameInstance.Module.canvas.remove();

You will probably be left with a black box afterward, that will be the parent div (id=”gameInstance”).
This will be the same black box if you tested the reparenting demo above.

Hide and Show the Canvas

Hiding the canvas in Unity 2018 runs into the same issue as simply destroying the application. In Unity 2019 there are no issues. Simply change the hidden member for the Canvas or a parent node to true. And obviously, set it to false to make it visible again.

// Functions callbacks for the Show/Hide Container and Show/Hide Canvas buttons

function WebGLDemo_WebGLContentMinimize()
{
    // Disable the starting container div (that's been id-ed as webglcontainer)
     var cont = document.getElementById("webglcontainer");
     cont.hidden = true;
}

function WebGLDemo_WebGLContentRestore()
{
     var cont = document.getElementById("webglcontainer");
     cont.hidden = false;
}

function WebGLDemo_Hide()
{
     gameInstance.Module.canvas.hidden = true;
}

function WebGLDemo_Show()
{
     gameInstance.Module.canvas.hidden = false;
}

Modify Event Handlers

If you’re familiar with JavaScript, you know you can add event handlers to DOM objects to call callbacks on different events, such as when the mouse cursor moves over it, or when a key is pressed when the object is in focus, etc. Any handlers you add in JavaScript to the canvas shouldn’t interrupt the game’s ability to continue polling its own events.

// Functions callbacks for the Add/Rem Click buttons
// After clicking these buttons, make sure the click inside the app the test it.

function WebGLDemo_AddClick()
{
     gameInstance.Module.canvas.onclick = function(){alert("Canvas clicked on!");};
}

function WebGLDemo_RemClick()
{
     gameInstance.Module.canvas.onclick = null;
}

Resizing the Canvas

The canvas can be resized. Setting the width and the height seems to be interlinked, where modifying one (the width or the height) modifies the other to maintain the aspect ratio. Thus, I only have to modify one component of the size (in this example, the width).

// Functions callbacks for the Resize Small/Normal Click buttons

function WebGLDemo_MakeSmall()
{
     gameInstance.Module.canvas.style.width = "600px";
}

function WebGLDemo_MakeNormal()
{
     gameInstance.Module.canvas.style.width = "960px";
}

The parent container still maintains its size—something you have to address.

Reparenting the Canvas

Simple enough, reparent the canvas with the usual DOM node reparenting function.

// Functions callbacks for the (Re)/Reparent Click buttons

function WebGLDemo_Reparent()
{
	var newcont = document.getElementById("otherparent");
	newcont.appendChild(gameInstance.Module.canvas);
}

function WebGLDemo_Rereparent()
{
	var newcont = document.getElementById("gameInstance");
	newcont.appendChild(gameInstance.Module.canvas);
}

Restyling the Canvas

The DOM node style can be changed like anything else. Just keep in mind that because your app rendering is taking up the interior of the canvas, you won’t be able to see those effects. But, things that are visible outside the object’s bounds (such as drop shadows) are visible.

// Functions callbacks for the shadow restyling buttons

function WebGLDemo_StyleShadow()
{
     gameInstance.Module.canvas.style.boxShadow = "10px 10px 8px 10px #888888"
}

function WebGLDemo_StyleNoShadow()
{
     gameInstance.Module.canvas.style.boxShadow = "";
}

In Conclusion

I might have gotten a little gratuitous with the number of examples, but you get the idea!

Information on the sample WebGL app can be found here.
Built with Unity 2018.3.8f1
Authored and tested in Chrome.
– Stay strong, code on. William Leu

Explore more articles here.
Explore more articles about Unity WebGL here.

Как указать родительским Canvas из скрипта?

Прошу проконсультировать (три дня рыскания по инету ни к чему не привели).
Имеем Canvas на котором кучу всего набросано.
Имеем функцию создающую из префаба новый объект.
Проблема в том, что данный объект создаётся за пределами Canvas и указать в качестве родительского Canvas (чтобы объект был виден на экране) не получается.
Как это можно осуществить?

Создаётся такой строкой:

Используется csharp

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

        public Transform LeftLine;

        void Start() {

                for (int y = 2; y < 2; y++) {
                        for (int x = 2; x < 2; x++) { 
                                GameObject childObject = Instantiate(LeftLine, new Vector3(x, y, 0), Quaternion.identity) as GameObject;
                        }
                }
        }

       
        // Update is called once per frame
        void Update () {

       
        }
}

Выглядит это так:
Изображение

Но если во время исполнения перетащить созданный объект (LeftLine) в Canvas то его становится видно.

Что я делаю не так и как правильно нужно добавлять на существующий Canvas новые элементы?

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01

Re: Как указать родительским Canvas из скрипта?

Сообщение BornFoRdeatH 07 сен 2015, 17:26

Не бойся, если ты один, бойся, если ты ноль.

BornFoRdeatH
Адепт
 
Сообщения: 2377
Зарегистрирован: 22 окт 2011, 23:41
Откуда: Украина
Skype: bornfordeath

Re: Как указать родительским Canvas из скрипта?

Сообщение юnity 07 сен 2015, 18:39

BornFoRdeatH купи себе ios :))

Give exact coordinates of the decision of the problems

Аватара пользователя
юnity
UNITрон
 
Сообщения: 290
Зарегистрирован: 21 июл 2015, 18:30

Re: Как указать родительским Canvas из скрипта?

Сообщение BornFoRdeatH 07 сен 2015, 18:47

Спасибо, но меня мало интересуют продукты маркетинга.

Не бойся, если ты один, бойся, если ты ноль.

BornFoRdeatH
Адепт
 
Сообщения: 2377
Зарегистрирован: 22 окт 2011, 23:41
Откуда: Украина
Skype: bornfordeath

Re: Как указать родительским Canvas из скрипта?

Сообщение GAVsi 07 сен 2015, 20:28

BornFoRdeatH писал(а):http://docs.unity3d.com/ScriptReference/Transform.SetParent.html

Уж как только не изголялся — не получается.
Canvas же вроде как не объект.

Используется csharp

public class Test : MonoBehaviour {

        public Transform LeftLine; // объект LeftLine
        public Transform canvas; // Canvas

        void Start() {

                for (int y = 2; y < 2; y++) {
                        for (int x = 2; x < 2; x++) { 
                                GameObject childObject = Instantiate(LeftLine, new Vector3(x, y, 0), Quaternion.identity)  as GameObject;

                                childObject.transform.SetParent(canvas, false);  // строка ошибки
                        }
                }
        }
}

получаем ошибку при выполнении:

NullReferenceException: Object reference not set to an instance of an object
Test.Start () (at Assets/Image/Test.cs:16)

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01

Re: Как указать родительским Canvas из скрипта?

Сообщение BornFoRdeatH 07 сен 2015, 20:34

В инспекторе присвойте канвас либо другой го в который нужно запарентить.

Не бойся, если ты один, бойся, если ты ноль.

BornFoRdeatH
Адепт
 
Сообщения: 2377
Зарегистрирован: 22 окт 2011, 23:41
Откуда: Украина
Skype: bornfordeath

Re: Как указать родительским Canvas из скрипта?

Сообщение samana 07 сен 2015, 20:39

Почему бы просто не найти то, что нужно, там где это нужно (в Start методе)

Используется csharp

GameObject canvas =GameObject.Find(«Canvas»);
мойНовыйОбъект.setParent(canvas.transform);
 

Аватара пользователя
samana
Адепт
 
Сообщения: 4738
Зарегистрирован: 21 фев 2015, 13:00
Откуда: Днепропетровск

Re: Как указать родительским Canvas из скрипта?

Сообщение GAVsi 07 сен 2015, 21:04

samana писал(а):Почему бы просто не найти то, что нужно, там где это нужно (в Start методе)

Пробовал — ошибка та же.

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01

Re: Как указать родительским Canvas из скрипта?

Сообщение seaman 07 сен 2015, 21:40

Можно спросить.
Почему многие делают трансформ?

Используется csharp

public Transform LeftLine;

Понятно, что они неразрывно связаны, но какого… трансформ, а не GameObject?

Попробуйте так:

Используется csharp

Transform tr= Instantiate(LeftLine, new Vector3(x, y, 0), Quaternion.identity)  as Transform;
GameObject childObject = tr.gameObject;
childObject.transform.SetParent(canvas, false);

Или проще, если childObject сам не нужен:

Используется csharp

Transform tr= Instantiate(LeftLine, new Vector3(x, y, 0), Quaternion.identity)  as Transform;
tr.SetParent(canvas, false);

seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Как указать родительским Canvas из скрипта?

Сообщение GAVsi 07 сен 2015, 22:17

К сожалению ни первый, ни второй вариант не сработали… :(

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01

Re: Как указать родительским Canvas из скрипта?

Сообщение seaman 07 сен 2015, 22:26

Ну так дебажте. Смотрите что у Вас null

Используется csharp

Transform tr= Instantiate(LeftLine, new Vector3(x, y, 0), Quaternion.identity)  as Transform;
Debug.Log(«TRANSFORM-« + tr);
GameObject childObject = tr.gameObject;
Debug.Log(«CANVAS-« + canvas);
childObject.transform.SetParent(canvas, false);

seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Как указать родительским Canvas из скрипта?

Сообщение GAVsi 07 сен 2015, 22:50

в этой строке ошибка:

Используется csharp

GameObject childObject = tr.gameObject;

NullReferenceException: Object reference not set to an instance of an object

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01

Re: Как указать родительским Canvas из скрипта?

Сообщение seaman 07 сен 2015, 23:31

Вы читаете что написано?
Если ошибка тут, то Debug.Log(«TRANSFORM-» + tr); должен выдать null. Если он выдает null, значит Instantiate(LeftLine, new Vector3(x, y, 0), Quaternion.identity) дает не Transform.
Что на самом деле в public Transform LeftLine;?

seaman
Адепт
 
Сообщения: 8352
Зарегистрирован: 24 янв 2011, 12:32
Откуда: Самара

Re: Как указать родительским Canvas из скрипта?

Сообщение GAVsi 08 сен 2015, 06:50

LeftLine — это префаб из Image и текстовых полей.

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01

Re: Как указать родительским Canvas из скрипта?

Сообщение GAVsi 08 сен 2015, 07:52

Спасибо. Заработало. (Утро вечера мудреней.)
Закинул заного объекты, перекомпилил и.. заработало.

Используется csharp

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

        public GameObject LeftLine; // Prefab
        public GameObject canvas; // Canvas

        void Start() {

                //Debug.Log(«LeftLine-» + LeftLine);
                //Debug.Log(«canvas-» + canvas);
                for (int y = 2; y < 2; y++) {
                        for (int x = 2; x < 2; x++) {

                                GameObject childObject = Instantiate(LeftLine, new Vector3(x*150, y*50, 0), Quaternion.identity)  as GameObject;
                                //Debug.Log(«childObject-» + childObject);
                                childObject.transform.SetParent(canvas.transform, false);
                        }
                }
        }

        // Update is called once per frame
        void Update () {

       
        }
}

Теперь бы разобраться как якорь сменить и от нового спозиционировать?

GAVsi
UNец
 
Сообщения: 10
Зарегистрирован: 07 сен 2015, 17:01


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 18



I have a scene with two cubes, and canvas. One cube falls onto another. Canvas appearing must be triggered by collision. It’s does not working. Where’s the problem?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class EverythingInside : MonoBehaviour
{

public Canvas GUICanvas;
void Start()
{
}
void OnGUI()
{
    GUICanvas.gameObject.SetActive(true);
}
void OnCollisionEnter(Collision col)
{
    if (col.gameObject.tag == "FallingCube")
    {
        OnGUI();
    }
}
void Update()
{
}

}

Filburt's user avatar

Filburt

17.5k12 gold badges64 silver badges113 bronze badges

asked Jun 3, 2016 at 15:01

Andrii's user avatar

3

Put the code below inside your EverythingInside script. Make sure Collider and Rigidbody are attached to both cubes. Also make sure to drag your Canvas from the Editor to the GUICanvas slot.

public Canvas GUICanvas;

void Start()
{

}

void OnCollisionEnter(Collision col)
{
    if (col.gameObject.CompareTag("FallingCube"))
    {
        GUICanvas.gameObject.SetActive(true);
    }
}

void Update()
{

}

Unity Physics tutorials.

Unity UI Tutorials.

Unity Scripting Tutorials.

answered Jun 3, 2016 at 15:42

Programmer's user avatar

ProgrammerProgrammer

121k22 gold badges234 silver badges324 bronze badges

5

Your problem is that OnGUI() as a function is called once every frame in Unity, regardless of whether or not you call it manually. Also, OnGUI is reserved for doing things like rendering simple buttons and text directly to the screen, it doesn’t perform any actual logic.

All you have to do to make this work is just replace where you’ve called OnGui() with GUICanvas.gameObject.SetActive(true)
and get rid of the other functions.

using UnityEngine;
using UnityEngine.UI;

public class EverythingInside : MonoBehaviour
{
    public Canvas GUICanvas;

    void OnCollisionEnter(Collision col)
    {
        if (col.tag == "FallingCube")
        {
            GUICanvas.gameObject.SetActive(true);
        }
    }
}

That right there is literally all you need to make it work. Bear in mind that if you change it later on to be a trigger instead of two colliding cubes you will need to replave OnCollisionEnter with OnTriggerEnter.

answered Jun 3, 2016 at 16:20

DisturbedNeo's user avatar

DisturbedNeoDisturbedNeo

7132 gold badges5 silver badges19 bronze badges

1

Пользовательские интерфейсы являются важным аспектом многих игр и приложений, предоставляя игрокам возможность взаимодействовать с игровым миром и получать доступ к важной информации. В Unity компонент Canvas — это мощный инструмент для создания пользовательских интерфейсов и управления ими. В этой статье мы рассмотрим компонент Canvas в Unity и то, как его можно использовать для разработки привлекательных и интерактивных пользовательских интерфейсов.

Компонент Canvas в Unity — это контейнер для элементов пользовательского интерфейса, таких как кнопки, текст, изображения и панели. Он предоставляет разработчикам возможность создавать элементы пользовательского интерфейса и размещать их на экране таким образом, чтобы это имело смысл для их конкретной игры или приложения. Компонент Canvas — это, по сути, двухмерное пространство, в котором можно размещать элементы пользовательского интерфейса, изменять их размер и манипулировать ими.

Как работает Canvas?

Компонент Canvas в Unity работает, определяя 2D-пространство на экране, в котором могут быть размещены элементы пользовательского интерфейса. Он создается как объект на сцене и предоставляет разработчикам возможность размещать элементы пользовательского интерфейса на экране таким образом, чтобы это имело смысл для их конкретной игры или приложения.

Чтобы создать Canvas в Unity, вам просто нужно создать новый игровой объект и добавить к нему компонент Canvas. Затем вы можете создавать элементы пользовательского интерфейса и прикреплять их к нему, используя компонент Rect Transform для управления их положением, размером и поворотом.

Использование

Компонент Canvas в Unity предоставляет множество инструментов и функций, упрощающих создание привлекательных и интерактивных пользовательских интерфейсов. Например, вы можете использовать компонент Canvas Scaler для управления размером элементов пользовательского интерфейса в зависимости от размера и разрешения экрана или компонент Graphic Raycaster для определения, когда игрок взаимодействует с элементами пользовательского интерфейса с помощью мыши или сенсорного ввода.

В дополнение к своим встроенным функциям компонент Canvas в Unity также хорошо интегрируется с другими компонентами пользовательского интерфейса, такими как компонент Text и компонент Image. Используя эти компоненты вместе, разработчики могут создавать сложные элементы пользовательского интерфейса, такие как диалоговые окна, индикаторы выполнения и индикаторы работоспособности.

Вот пример скрипта для создания элемента пользовательского интерфейса с помощью компонента Canvas в Unity:

using UnityEngine;
using UnityEngine.UI;

public class UIScript : MonoBehaviour
{
    public Canvas canvas;
    public Text textElement;

    void Start()
    {
        canvas = GetComponent<Canvas>();
        textElement = GetComponentInChildren<Text>();

        textElement.text = "Hello, World!";
    }
}

Этот сценарий создает компонент Canvas и компонент Text и устанавливает текст компонента Text в значение «Hello, World!». В этом примере компонент Canvas и компонент Text получаются с помощью методов GetComponent.

Вот пример сценария для создания элемента пользовательского интерфейса с компонентами Canvas Controller, Canvas Scaler, Graphic Raycaster и Image в Unity:

using UnityEngine;
using UnityEngine.UI;

public class UIScript : MonoBehaviour
{
    public Canvas canvas;
    public CanvasScaler canvasScaler;
    public GraphicRaycaster graphicRaycaster;
    public Image imageElement;

    void Start()
    {
        canvas = GetComponent<Canvas>();
        canvasScaler = GetComponent<CanvasScaler>();
        graphicRaycaster = GetComponent<GraphicRaycaster>();
        imageElement = GetComponentInChildren<Image>();

        canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        canvasScaler.referenceResolution = new Vector2(1920, 1080);
        canvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
        canvasScaler.matchWidthOrHeight = 1.0f;

        imageElement.sprite = Resources.Load<Sprite>("Sprites/UIImage");
    }
}

В этом примере сценарий начинается с получения ссылки на компоненты Canvas, Canvas Scaler, Graphic Raycaster и Image с помощью методов GetComponent() и GetComponentInChildren().

Затем сценарий задает свойства компонента Canvas Scaler для масштабирования элементов пользовательского интерфейса в зависимости от размера и разрешения экрана. Для свойства uiScaleMode установлено значение ScaleWithScreenSize, чтобы обеспечить масштабирование элементов пользовательского интерфейса в соответствии с размером экрана, для свойства referenceResolution установлено значение 1920 x 1080, чтобы указать эталонное разрешение, а для свойства screenMatchMode установлено значение MatchWidthOrHeight, чтобы соответствовать ширине или высоте экрана. экран. Для свойства matchWidthOrHeight установлено значение 1,0f, чтобы гарантировать сохранение пропорций элементов пользовательского интерфейса.

Наконец, скрипт устанавливает спрайт компонента Image в изображение, хранящееся в папке Resources, с помощью метода Resources.Load().

Используя компонент Canvas в Unity, разработчики получают мощный инструмент для создания пользовательских интерфейсов и управления ими. Независимо от того, создаете ли вы простые элементы пользовательского интерфейса или сложные интерфейсы, компонент Canvas обеспечивает гибкий и интуитивно понятный способ размещения элементов пользовательского интерфейса на экране и позволяет оживить вашу игру или приложение.

Доступные свойства

Свойство Описание
Render Mode The way the UI is rendered to the screen or as an object in 3D space (see below). The options are Screen Space — OverlayScreen Space — Camera and World Space.
Pixel Perfect (Screen Space modes only) Should the UI be rendered without antialiasing for precision?
Render Camera (Screen Space — Camera mode only) The camera to which the UI should be rendered (see below).
Plane Distance (Screen Space — Camera mode only) The distance at which the UI plane should be placed in front of the camera.
Event Camera (World Space mode only) The camera that will be used to process UI events.
Receives Events Are UI events processed by this Canvas?
[UNITY 5] UI Элементы для создания интерфейса (Canvas,text,image и т.д)[UNITY 5] UI Элементы для создания интерфейса (Canvas,text,image и т.д)

Заключение

В заключение отметим, что компонент Canvas в Unity — важный инструмент для разработчиков игр и приложений, стремящихся создавать привлекательные и интерактивные пользовательские интерфейсы. Он обеспечивает простой и интуитивно понятный способ размещения элементов пользовательского интерфейса на экране и хорошо интегрируется с другими компонентами пользовательского интерфейса, что упрощает создание сложных интерфейсов.

Понравилась статья? Поделить с друзьями:
  • Как найти все вклады в сбербанке
  • Как составить задачи для реферата
  • Как найти провода в получении
  • Проблема как найти друга
  • Памятка как правильно составить резюме