Как сделать фон в unity
Перейти к содержимому

Как сделать фон в unity

Set background images

UI Builder doesn’t have a dedicated “image” element. To create an image, do the following:

  1. Import background image into your project.
  2. Create a regular visual element in UI (User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
    See in Glossary Builder.
  3. Set the element’s background image to the imported image.

When you set the background image, you must select a supported background image types:

  • Textures An image used when rendering a GameObject, Sprite, or UI element. Textures are often applied to the surface of a mesh to give it visual detail. More info
    See in Glossary
  • Sprites A 2D graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development. More info
    See in Glossary
  • Render textures A special type of Texture that is created and updated at runtime. To use them, first create a new Render Texture and designate one of your Cameras to render into it. Then you can use the Render Texture in a Material just like a regular Texture. More info
    See in Glossary
  • SVG Vector images

Note: To use a SVG image as a background for a visual element, you must install a package. To do so, in the Package Manager window, install the package com.unity.vectorgraphics from git URL.

Image import settings

After you have imported an image to your project, for the most intuitive results, Unity recommends you to apply certain import settings for Textures, Sprites, and Vector images before you use them as a background for a visual element in the UI Builder.

Texture

The recommended import settings for a Texture image that you use as a background for a visual element:

Property: Value:
Texture Type Default
Non-Power of 2 None
Compression A method of storing data that reduces the amount of storage space it requires. See Texture Compression, Animation Compression, Audio Compression, Build Compression.
See in Glossary
None
Alpha Is Transparency true
Texture Type Editor GUI and Legacy GUI
Non-Power of 2 None
Compression None
Alpha Is Transparency true
Texture Type Sprite (2D and UI)
Compression None
Alpha Is Transparency true
Sprite Mode Single
Mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary Type
Tight

Sprites

The recommended import settings for a Sprite image that you use as a background for a visual element:

Property: Value:
Texture Type Sprite (2D and UI)
Compression None
Alpha Is Transparency true
Sprite Mode Multiple if file contains multiple sprites, Single otherwise
Mesh Type Tight

Vector images

The recommended import settings for a SVG Vector image that you use as a background for a visual element:

Property: Value:
Generated Asset Type UI Toolkit Vector Image
Tessellation Settings Basic
Target Resolution Lowest value that produces satisfactory results

Tip:

  • You can apply default presets to Assets by folder to automatically set your desired import settings.
  • All image types are subject to dynamic atlasing if they’re not already in an atlas. (An image is in an atlas if imported as a Sprite with Sprite Mode set to Multiple, or if you have manually added it to a Sprite Atlas A texture that is composed of several smaller textures. Also referred to as a texture atlas, image sprite, sprite sheet or packed texture. More info
    See in Glossary asset.) You can configure dynamic atlasing in a Panel Settings asset.

9-Slice images with UI Toolkit

Generally, you can only 9-slice a regular 2D Sprite. With UI Toolkit however, you can also 9-slice Texture, Render Texture, and SVG Vector images.

To 9-slice an image:

  • For a Sprite image, use Sprite Editor or USS.
  • For other types of images, use USS.

To 9-slice a selected image using USS:

  1. Open UI Builder .
  2. In the Background section in the Inspector A Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
    See in Glossary , specify the Left, Right, Top, and Bottom slice values.

You can also specify the slice values directly in USS, UXML, or C# files for the following properties:

Какие есть способы добавить фоновую картинку в 2Д игре в юнити

Так как я новичок, мне дали тестовое задание, есть игра в которой некоторые обьекты генерируются вне canvas — a, но отображаются в игре и при этом они находятся выше камеры по иерархий, ниже картинка. Но добавленный мной бэкграунд не отображается. Подскажите возможности добавить бэкграун.

введите сюда описание изображения

Добавьте отдельную камеру на сцену, которая будет рисовать только бэкграунд. Но при этом, если у вас есть еще камеры на сцене, настройте их так, чтобы они перерисовывали ваш бэкграунд, а именно посмотрите в сторону настроек Culling Mask и Background

А также настройте ваш Canvas , чтобы он рисовался в режиме либо Screen Space — Camera либо World Space

Adding and displaying a background

Pixelnest StudioPixelnest 18 nov. 2013

Using the empty project we created in the previous part, we will now learn how to add a background and some fancy clouds.

Adding a background

Your first background will be static. We will use the following image:

TGPA background

(Right click to save the image)

Import the image in the “sprites” folder. Simply copy the file in it, or drag and drop it from the explorer.

Do not worry about the import settings for now.

In Unity, create a new Sprite game object in the scene.

New sprite

What is a sprite?

In general, we call “sprite” a 2D image displayed in a video game. Here, it’s a Unity specific object made for 2D games.

Add the texture to the sprite

We will now select the actual sprite to display. Make sure that “New Sprite” is selected and look at the inspector. Set the Sprite property to the “background” image:

Select a sprite

(You have to click on the small round icon at the right of the input box to show the “Select Sprite” inspector)

You can see that some other sprites are there. Those are the default images used by uGUI (the Unity UI system).

“My sprite doesn’t show up in the dialog?”: first, make sure you are in the “Assets” tab of the “Select Sprite” dialog.

Some readers have reported that, in their project, this dialog was empty. The reason is that for some Unity installations, even with a fresh new 2D project, images are imported as “Texture” and not “Sprite”.

To fix this, you need to select the image in the “Project” pane, and in the “Inspector”, change the “Texture Type” property to “Sprite”:

Sprite mode

We don’t know why everybody doesn’t seem to have the same behavior.

Well, we have set a simple sprite displaying a cloudy sky background. You can think it was a bit complicated just for that. In fact, we could have dragged the sprite from the “Project” tab directly right into the “Scene”.

Let’s reorganize the scene.

In the “Hierarchy” pane, select the New Sprite . Rename it in Background1 or something you will easily remember.

Then move the object to where it belongs: Level -> Background . Change its position to (0, 0, 0) .

Background is set

A quick exercise: duplicate the background and place it at (20, 0, 0) . It should fit perfectly with the first part.

Tip: you can duplicate an objet with the cmd + D (OS X) or ctrl + D (Windows) shortcuts.

Background2 in place

Sprite layers

The next statement will seem pretty obvious, but it has some consequences: we are displaying a 2D world.

This means that all images are at the same depth, ie. 0 . And you (as well as the graphics engine) don’t really know who’s going to be displayed first.

Sprite layers allow us to tell Unity what is in the front and what is in the back.

In Unity, we can change the “Z” of our elements, and this will allow us to have layers. This is actually what we were doing in this tutorial before the Unity 5 update.

But we thought that it was a good idea to use Sprite Layers.

On your “Sprite Renderer” component, you have a field named… “Sprite Layer”, currently set to Default .

If you click on it, a short list will show:

Sorting layer list

Let’s add some layers to fit our needs (use the “+” button):

Sorting layer add

Apply the Background layer to our background sprite:

Set sorting layer

Tip: the settings “Order in Layer” is a way to limit sub-layers. Sprites with lower numbers are rendered before sprites with greater numbers.

Note: the “Default” layer cannot be removed, because this is the layer used by 3D elements. You can have 3D objects in your 2D game. Particles are considered as 3D objects by Unity, so they will be rendered on this layer.

Adding background elements

Also known as props. These elements aren’t used to improve the gameplay but to visually enhance the scene.

Here are some simple flying platform sprites:

Platform sprites

(Right click to save the image)

As you can see, we got two platforms in one file. This is a good way to learn how to crop sprites with the Unity tools.

Getting two sprites from one image

  1. Import the image in your “sprites” folder
  2. Select the “platforms” sprite and go to the inspector
  3. Change “Sprite Mode” to “Multiple”
  4. Click on “Sprite Editor”

Multiple sprites

In the new window (“Sprite Editor”), you can draw rectangles around each platform to slice the texture into smaller parts:

Sprite Editor

Call the platforms “platform1” and “platform2”.

Tip: the top-left button “Slice” allows you to quickly and automatically make this tedious task.

Unity will find the objects inside the image and will slice them automatically. You can specify the default pivot point, or set a minimum size for a slice. For a simple image without artifacts, it’s really efficient. However, if you use this tool, be careful and check the result to be sure to get what you want.

Now, under the image file, you should see the two sprites separately:

Sprite Editor result

Adding them to the scene

We will proceed like for the background sprite: create a new Sprite and select the “platform1” sprite (or drag them one by one from the “Project” to the “Scene” tab). Repeat for “platform2”.

Set their “Sprite Layer” to “Platforms”.

Place them in the Middleground object.

Two shiny new platforms

And… it’s working! I’m still amazed how simple it is now (to be honest, it was a bit tricky without the 2D tools, involving quad and image tiling).

Prefabs

Save those platforms as prefabs. Just drag’n’drop them inside the “Prefabs” folder of the “Project” pane from the “Hierarchy”:

Prefabs

By doing so, you will create a Prefab based exactly on the original game object. You can notice that the game object that you have converted to a Prefab presents a new row of buttons just under its name:

Prefab connection

Note on the “Prefab” buttons: if you modify the game object later, you can “Apply” its changes to the Prefab or “Revert” it to the Prefab properties (canceling any change you’ve made on the game object). The “Select” button move your selection directly to the Prefab asset in the “Project” view (it will be highlighted).

Creating prefabs with the platform objects will make them easier to reuse later. Simply drag the Prefab into the scene to add a copy. Try to add another platform that way.

You are now able to add more platforms, change their positions, scales and planes.

You can put some in background or foreground too. Remember that the “Background”, “Middleground” and “Foreground” objects are just folders. So you need to set the right “Sprite Layer” (Platforms) and change the “Order in Layer”.

Use -10 for far platforms, and increase this number as you reach the foreground. An example:

Add a platform in background

It’s not very fancy but in two chapters we will add a parallax scrolling and it will suddenly bring the scene to life.

Camera and lights

Well. In the previous version of this tutorial (for Unity 4.2), we had a long and detailed explanation on how to set the camera and the lights for a 2D game.

The good news is that it’s completely useless now. You have nothing to do. It just works™.

Aside: if you click on the Main Camera game object, you can see that it has a “Projection” flag set to “Orthographic”. This is the setting that allows the camera to render a 2D game without taking the 3D into account. Keep in mind that even if you are working with 2D objects, Unity is still using its 3D engine to render the scene. The gif above shows this well.

Next step

You have just learned how to create a simple static background and how to display it properly. Then, we have taught you how to make simple sprites from an image.

In the next chapter, we will learn how to add a player and its enemies.

© 2016 Pixelnest Studio — we craft games and apps

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *