Как изменить sprite unity

Learn the different methods for changing a Sprite at runtime in Unity. Including loading from Sprite Sheets or by filename in code…

Although it’s a simple thing to do, changing a Sprite at runtime in Unity is a question that’s asked surprisingly often.

This may simply be because each developer’s specific needs are different, so it’s not always clear which method is the best or is the most efficient.

However, if you’ve ever tried to load all of the Sprites from a Sprite Sheet into an array from a script, or if you’ve tried to load a Sprite by its filename, what appears to be a simple task can quickly become confusing.

Especially for a beginner, like me.

But don’t worry…

There are several different uses and multiple methods available for changing sprites at runtime. So I’ve done a little digging and will be exploring each of them, along with their benefits and drawbacks, so that you can more confidently choose which one to use.

Here’s what you’ll learn in this post:

  • How to change a single Sprite from script
  • How to load Sprite from a Sprite Sheet into a Sprite Array (2 methods)
  • How to load Sprites by filename (using the Resources folder)
  • How to load Sprites by file path (using Addressable Assets)
  • 3 Examples for changing a Sprite from a Sprite Array

Let’s start with the basics…

To change a Sprite from a script in Unity, create a reference variable to hold the new Sprite. Then set the Sprite property of the Sprite Renderer Component on the Game Object you wish to change to match the new, replacement Sprite.

In scripting, it looks like this:

public SpriteRenderer spriteRenderer;
public Sprite newSprite;
void ChangeSprite()
    {
        spriteRenderer.sprite = newSprite; 
    }

In the inspector select the new Sprite that you want to use by dragging it into the field or by using the circle select button.

How to change a Sprite in Unity (Selecting the Sprite)

Select the new Sprite by dragging it into the field or by using Circle Select.

Make sure to also set the Sprite Renderer reference in the Inspector, otherwise you’ll get an error.

Alternatively, if the script is on the same Game Object, you can easily get it by using Get Component in Start.

void Start()
    {
        spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
    }

Then, when you want to change the Sprite, just call the Change Sprite function.

Like in this example if the Left Mouse Button is clicked:

void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            ChangeSprite(newSprite);
        }
    }

The example will easily change a Sprite Renderer’s existing sprite to use a different one instead. But what if you want to change to one of a number of different Sprites?

What if you have multiple Sprites, such as Slices stored in a Sprite Sheet, and you want to switch to one of them, or all of them in order, or a random Sprite, all from a script?

How to change a Sprite from a Sprite Sheet in Unity

Sprite Sheet Example in Unity

Changing a Sprite to another image from a Sprite Sheet can be done using a similar method as changing a single Sprite.

What’s different is that, in this case, the method of loading the Sprites is different, as you’ll be storing multiple Sprites in an array and retrieving the one that you want with an index.

Creating a Sprite array is simple, just add brackets to the Sprite variable to declare it as an array.

Like this:

public Sprite[] spriteArray;

Next we need to add the Sprites to the array.

There are two main ways of doing this. We’ll start with the simplest method first, which is the manual method.

Method #1. The Manual Method

This method works in much the same way as changing a single Sprite, by manually dragging the Sprites to your array in the Inspector.

Adding Sprites from a Sprite Sheet into an Array

Drag multiple Sprites to the Sprite array to automatically add them.

It helps to lock the inspector window when doing this, as it’s very easy to accidentally switch to the import settings of the file you’re trying to drag across.

How to lock the Inspector in Unity

Locking the Inspector makes it easier to add Sprites to the array.

Once the Sprites are loaded into the array you’ll be able to retrieve them using their index, like this:

void ChangeSprite() 
    { 
        spriteRenderer.sprite = spriteArray[0]; 
    }

Simply pass in the array element number in the square brackets that corresponds with the Sprite you wish to switch to.

To check which Sprite is assigned to which element, click the array dropdown in the Inspector.

When to use the manual method

The Manual Method is the simplest way to switch between multiple Sprites and is ideal if you are able to assign the sprites you’re going to use manually in the Inspector. For example, when using a Prefab.

But, what if you want to access Sprites entirely from scripting, without getting a reference to them first?

Well, as it turns out, there is a way to access Sprites from a script by their filename automatically.

Method #2. The Automatic Method

The Automatic Method allows you to access individual Sprites, or even a set of Sprites from a Sprite Sheet, without needing to get a reference to them in the Inspector.

Instead, by using this method, you will be able to load Sprites into a Scene with their filename from the Resources folder, a special folder that Unity will automatically load assets from (even if they’re not referenced in the Scene).

Normally, this is not how Unity works, as assets are usually identified by assigning references to them (as is the case in the Manual Method). As a result, using this method comes with a few words of caution (more on that later) but, if it works for you and your project, and you understand what you’re doing, here’s how to do it.

How to use the Resources folder in Unity

Add a folder named Resources anywhere in your Assets directory.

  1. First, create a new folder inside of your Assets folder called Resources. This can be placed anywhere in your Assets directory.
  2. Next place the Sprites into the Resources folder.
  3. Lastly, from a script, load the Sprite with Resources.Load<Type>(“filename”) passing in a String for the filename (without its extension).

Instead of manually adding the Sprites to the array, we can now, instead, load all of the Sprites associated with a Sprite Sheet by using Load All.

Like this:

void Start()
    {
        spriteArray = Resources.LoadAll<Sprite>("BirdHeroSprite");
    }

In the example above I’ve loaded every file of the type Sprite found in the BirdHeroSprite Texture, which is essentially a directory from which all the Slices are loaded.

While extremely useful, the Resources folder should be used with caution.

Reasons you shouldn’t use the Resources folder

Despite offering a useful option for loading assets, using the Resources folder is, generally, not recommended, as it’s not good practice.

But why?

The main reasons you should avoid using the Resources folder in Unity include:

  • Increased memory usage and a bigger application size: as everything inside the Resources folder is packaged and loaded, whether you need it or not.
  • Assets are more difficult to manage: as using filename paths can make it more likely that a connection will be broken if a file name or string is changed.
  • Longer loading and startup time: as, if you’re using a large number of assets, the operation to load them all takes exponentially longer as more and more is added to the Resources folder. In extreme cases (think thousands of assets) this can add multiple seconds to the startup time of applications to load assets that are not initially required (source).

So, while more experienced developers will no doubt understand the risks of using this special folder, and will be able to work around issues like these easily, it’s worth knowing that the general advice is not to use the Resources folder wherever possible.

So… wait, hang on…

If the Resources folder isn’t recommended, then why does it exist? And what’s the right way to use it?

When it’s OK to use the Resources folder

According to Unity, there are a couple of use cases for which the Resources folder is particularly useful:

  • Prototyping – Where performance is less important than being able to rapidly create ideas. In this case, the flexibility of the Resources folder can be extremely helpful and outweighs the performance hit.
  • Minor Uses – Using relatively few assets, that are not memory intensive, and are unlikely to change between platforms is much less likely to cause you significant issues.

Generally speaking, if your game is small or performance is not (yet) critical to your project, then using the Resources folder isn’t necessarily a problem. For more information on what Unity considers to be best practice when using the Resources folder, see this tutorial.

So what can you do if you want to load a Sprite by its filename, without using the Resources folder?

Well, what if I told you that there is an option that leverages the flexibility of the Resources folder but without the potential drawbacks.

How to load a Sprite from a script by filename (using Addressable Assets)

This method requires a little extra work to set up, but it allows you to load assets into a Scene with a filename and without the drawbacks of the Resources folder.

What are Addressable Assets in Unity?

[su_quote]The Addressable Asset system provides an easy way to load assets by “address”. It handles asset management overhead by simplifying content pack creation and deployment. The Addressable Asset system uses asynchronous loading to support loading from any location with any collection of dependencies. Whether you use direct references, traditional asset bundles, or Resource folders for asset management, Addressable Assets provide a simpler way to make your game more dynamic.[/su_quote]

Unity3d.com – Source

How to change a Sprite from a Sprite Sheet in scripting using Addressable Assets in Unity:

  1. Select Window > Package Manager and install the Addressable Assets package from the Package Manager (this requires Unity 2018.3 or later).
    Install Addressable Assets from the Unity Package Manager
  2. Next select Window > Asset Management > Addressables > Groups to open the Addressables Groups Window.
    Unity Addressables Window
  3. Click the button labelled Create Addressable Settings, this will create a default Addressable Group.
    Create a new Default Addressable Group
  4. In the Project Folder, select the Texture containing the Sprites you want to use and, in the Inspector, check the Addressable checkbox. This will reveal the asset’s Addressable Path, which you’ll need for the script.
    Unity Addressable Asset Checkbox location
  5. The file should now have been added to the default Addressable Group.
    Addressable Group Contents

The asset is now Addressable and can be accessed from a script without a reference.

Using Addressable Assets after using the Resources folder

If you were already using the Resources folder, you may have noticed the Resources directory, and its files, in the Groups Window alongside the Addressable Group. If so, dragging those assets to the Addressable Group will automatically mark them Addressable and move them into a new folder for you (as they can’t stay in Resources for this to work).

How to fix the Invalid Key Exception Error when using Addressable Assets

Depending on your version of Unity, the path that is assigned to the asset may continue to match the string that was being used for the Resources folder value (e.g. BirdHeroSprite, without a folder path or a file extension).

However, if you’re getting an Invalid Key Exception error be sure to check that the Addressable Path (displayed next to the asset’s Addressable Checkbox) matches the value you’re using in the script.

How to access Addressable Sprite Assets from a Script

Now that the Sprites are addressable it’s possible to load them from a script, without a reference. Here’s how to do it:

First, add the following two namespaces to the top of the script. These are required for the Addressable features and loading operations to work properly.

using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

You can add them below the existing namespace declarations, using UnityEngine etc.

Next we need to load the Sprites from the Sprite Sheet, just as we did when using the Resources folder.

This happens in two steps:

  1. First, load the Sprites using an asynchronous operation.
  2. When that operation is completed, assign the result to the Sprite Array.

In scripting it looks like this:

public SpriteRenderer spriteRenderer;
public Sprite[] spriteArray;
void Start()
{
    AsyncOperationHandle<Sprite[]> spriteHandle = Addressables.LoadAssetAsync<Sprite[]>("Assets/BirdHeroSprite.png");
    spriteHandle.Completed += LoadSpritesWhenReady;
}
void LoadSpritesWhenReady(AsyncOperationHandle<Sprite[]> handleToCheck)
{ 
    if(handleToCheck.Status == AsyncOperationStatus.Succeeded)
    {
        spriteArray = handleToCheck.Result;
    }
}

Instead of setting the contents of the array directly, what’s happening here is we’re starting a loading operation and creating a reference to it (the AsyncOperationHandle). Then when the loading is finished, we’re assigning the result to the Array, using the Handle reference to look up what was loaded.

Doing it in this way allows time for the assets to load.

Registering the function LoadSpritesWhenReady to the spriteHandle.Completed event means that, as soon as the assets are finished loading, the function will be called and the Sprites will be assigned to the Array.

While this part of the method could be done in several ways (inside a Coroutine for example), using an action like this avoids having to repeatedly check in Update, which would inefficient, especially since we know it’s only going to happen once.

Although using Addressable Assets requires more work than simply dropping the Sprites into the Resources folder, it’s more efficient, and it’s a much more up to date solution when compared to using the Resources folder.

A comprehensive guide of the Addressable Asset system is beyond the scope of this article but you can view the full Unity documentation here.

Now that you’ve loaded the Sprites into the Array, it’s time to put them to good use.

How to change a Sprite from an array (3 examples)

Once the Sprites are assigned to the array, you can change the Sprite Renderer’s Sprite property using the same function as in the first example. Simply pass in the name of the array and the index of the Sprite.

For example, to switch to the first Sprite in the array would look like this in scripting:

public SpriteRenderer spriteRenderer;
public Sprite[] spriteArray;
void ChangeSprite()
{
    spriteRenderer.sprite = spriteArray[0]; 
}

Or, if you want to switch to a random Sprite simply pass in a random number between zero and the length of the array. Like this:

public SpriteRenderer spriteRenderer;
public Sprite[] spriteArray;
void ChangeSprite()
{
    spriteRenderer.sprite = spriteArray[ Random.Range(0, spriteArray.Length)]; 
}

Lastly, if you want to cycle through each sprite of the array, create an Integer variable to store the last Sprite index. Then increment it every time you change the Sprite:

public SpriteRenderer spriteRenderer;
public Sprite[] spriteArray;
public int currentSprite;
void ChangeSprite()
{
    spriteRenderer.sprite = spriteArray[currentSprite];
    currentSprite++;
    if(currentSprite >= spriteArray.Length)
    {
        currentSprite = 0;
    }
}

You’ll notice in the example above that I’ve added an If Statement. This is to check if the index number has reached the end of the array. This is important as trying to retrieve a Sprite outside of the array’s range will result in an error.

Now it’s your turn

Now that you know a bit more about changing Sprites, how will you use what you’ve learned?

Or perhaps you’re still looking for a different method for changing Sprites?

Or maybe you know of a much better method for managing Sprites and are already using it in your game.

Whatever it is, let me know by leaving a comment below.

Image Attribution

  • Icons made by Kiranshastry from www.flaticon.com
  • Icons made by itim2101 from www.flaticon.com

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.

My favourite time-saving Unity assets

Rewired (the best input management system)

Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.

DOTween Pro (should be built into Unity)

An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.

Easy Save (there’s no reason not to use it)

Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.

$begingroup$

Inside the script code of the the hero(object) I want add the possibility to change its sprite.

So the player hits the space button and the sprite changes into the other sprite already added to the project.

Can you provide me a sample code to do this?

asked Apr 1, 2014 at 3:05

Fab's user avatar

$endgroup$

1

$begingroup$

The code has been commented for you. Enjoy.

public Sprite sprite1; // Drag your first sprite here
public Sprite sprite2; // Drag your second sprite here

private SpriteRenderer spriteRenderer; 

void Start ()
{
    spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
    if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
        spriteRenderer.sprite = sprite1; // set the sprite to sprite1
}

void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space)) // If the space bar is pushed down
    {
        ChangeTheDamnSprite (); // call method to change sprite
    }
}

void ChangeTheDamnSprite ()
{
    if (spriteRenderer.sprite == sprite1) // if the spriteRenderer sprite = sprite1 then change to sprite2
    {
        spriteRenderer.sprite = sprite2;
    }
    else
    {
        spriteRenderer.sprite = sprite1; // otherwise change it back to sprite1
    }
}

You need to have a sprite renderer attached to your GameObject.
Create a new C# Script and attach to it a GameObject. Paste the code in between the parenthesis… I’m sure you can figure it out from there :)

answered Apr 1, 2014 at 5:52

Savlon's user avatar

SavlonSavlon

1,0921 gold badge8 silver badges14 bronze badges

$endgroup$

3

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

$begingroup$

Inside the script code of the the hero(object) I want add the possibility to change its sprite.

So the player hits the space button and the sprite changes into the other sprite already added to the project.

Can you provide me a sample code to do this?

asked Apr 1, 2014 at 3:05

Fab's user avatar

$endgroup$

1

$begingroup$

The code has been commented for you. Enjoy.

public Sprite sprite1; // Drag your first sprite here
public Sprite sprite2; // Drag your second sprite here

private SpriteRenderer spriteRenderer; 

void Start ()
{
    spriteRenderer = GetComponent<SpriteRenderer>(); // we are accessing the SpriteRenderer that is attached to the Gameobject
    if (spriteRenderer.sprite == null) // if the sprite on spriteRenderer is null then
        spriteRenderer.sprite = sprite1; // set the sprite to sprite1
}

void Update ()
{
    if (Input.GetKeyDown (KeyCode.Space)) // If the space bar is pushed down
    {
        ChangeTheDamnSprite (); // call method to change sprite
    }
}

void ChangeTheDamnSprite ()
{
    if (spriteRenderer.sprite == sprite1) // if the spriteRenderer sprite = sprite1 then change to sprite2
    {
        spriteRenderer.sprite = sprite2;
    }
    else
    {
        spriteRenderer.sprite = sprite1; // otherwise change it back to sprite1
    }
}

You need to have a sprite renderer attached to your GameObject.
Create a new C# Script and attach to it a GameObject. Paste the code in between the parenthesis… I’m sure you can figure it out from there :)

answered Apr 1, 2014 at 5:52

Savlon's user avatar

SavlonSavlon

1,0921 gold badge8 silver badges14 bronze badges

$endgroup$

3

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

Смена спрайта из скрипта

Смена спрайта из скрипта

Здравствуйте все!
Подскажите,пожалуйста, как из скрипта изменить спрайт объекта? Если точнее,то делаю кнопку,при наведении на неё соответственно должна менять картинку.

rockmagic
UNец
 
Сообщения: 7
Зарегистрирован: 23 июн 2014, 15:55

Re: Смена спрайта из скрипта

Сообщение Chaz 10 июл 2014, 22:19

Chaz
Адепт
 
Сообщения: 1412
Зарегистрирован: 07 апр 2012, 11:24

Re: Смена спрайта из скрипта

Сообщение Левш@ 11 июл 2014, 04:06

Если именно спрайт, то cам спрайт и надо менять видимо, у него нет параметра <texture>.
Решение в соответствующей архитектуре обьекта и кода в несколько строк. :)
Например — создаешь пустышку, вешаеш на нее колайдер.
Удочеряеш ей 2 спрайта (не нужный — неактивный).
По событиям OnMouse — активируешь деактивируешь соответствующие спрайты.

А проще это через ГУЙ реализовать. :)

Последний раз редактировалось Левш@ 08 июл 2015, 00:58, всего редактировалось 1 раз.

Аватара пользователя
Левш@
Адепт
 
Сообщения: 4073
Зарегистрирован: 14 окт 2009, 16:34
Откуда: IBERIA
Skype: bars_levsha
  • Сайт

Re: Смена спрайта из скрипта

Сообщение rockmagic 11 июл 2014, 10:46

Ура,я это сделал.Это делается так:

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

public class StGameButSc : MonoBehaviour {

       
        public Sprite[] sprites = new Sprite[2];

       

        void OnMouseEnter()

        {
                gameObject.GetComponent<SpriteRenderer>().sprite = sprites[1];
        }

        void OnMouseExit()

        {

                gameObject.GetComponent<SpriteRenderer>().sprite = sprites[0];

        }
}

rockmagic
UNец
 
Сообщения: 7
Зарегистрирован: 23 июн 2014, 15:55

Re: Смена спрайта из скрипта

Сообщение Cuprum 07 июл 2015, 22:54

А что такое солайдер?

Cuprum
UNец
 
Сообщения: 16
Зарегистрирован: 07 июл 2015, 13:00


Вернуться в Почемучка

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

Сейчас этот форум просматривают: Google [Bot] и гости: 25



Sprites are 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.

Unity provides a placeholder Sprite Creator, a built-in Sprite Editor, a Sprite RendererA component that lets you display images as Sprites for use in both 2D and 3D scenes. More info
See in Glossary
and a Sprite PackerA facility that packs graphics from several sprite textures tightly together within a single texture known as an atlas. Unity provides a Sprite Packer utility to automate the process of generating atlases from the individual sprite textures. More info
See in Glossary

See Importing and Setting up Sprites below for information on setting up assets as Sprites in your Unity project.

Sprite Tools

Sprite Creator

Use the Sprite Creator to create placeholder sprites in your project, so you can carry on with development without having to source or wait for graphics.

Sprite Editor

The Sprite Editor lets you extract sprite graphics from a larger image and edit a number of component images within a single texture in your image editor. You could use this, for example, to keep the arms, legs and body of a character as separate elements within one image.

Sprite Renderer

Sprites are rendered with a Sprite Renderer component rather than the Mesh RendererA mesh component that takes the geometry from the Mesh Filter and renders it at the position defined by the object’s Transform component. More info
See in Glossary
used with 3D objectsA 3D GameObject such as a cube, terrain or ragdoll. More info
See in Glossary
. Use it to display images as Sprites for use in both 2D and 3D scenesA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary
.

Sprite Packer

Use Sprite Packer to optimize the use and performance of video memory by your project.

Importing and Setting Up Sprites

Sprites are a type of AssetAny media or data that can be used in your game or project. An asset may come from a file created outside of Unity, such as a 3D Model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
See in Glossary
in Unity projects. You can see them, ready to use, via the ProjectIn Unity, you use a project to design and develop a game. A project stores all of the files that are related to a game, such as the asset and Scene files. More info
See in Glossary
view.

There are two ways to bring Sprites into your project:

  1. In your computer’s Finder (Mac OS X) or File Explorer (Windows), place your image directly into your Unity Project’s Assets folder.

    Unity detects this and displays it in your project’s Project view.

  2. In Unity, go to Assets > Import New Asset to bring up your computer’s Finder (Mac OS X) or File Explorer (Windows).

    From there, select the image you want, and Unity puts it in the Project view.

See Importing for more details on this and important information about organising your Assets folder.

Setting your Image as a Sprite

If your project mode is set to 2D, the image you import is automatically set as a Sprite. For details on setting your project mode to 2D, see 2D or 3D Projects.

However, if your project mode is set to 3D, your image is set as a TextureAn 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
, so you need to change the asset’s Texture Type:

  1. Click on the asset to see its Import Inspector.
  2. Set the Texture Type to Sprite (2D and UI):

Set Texture Type to Sprite (2D and UI) in the Assets Inspector

Set Texture Type to Sprite (2D and UI) in the Asset’s Inspector

For details on Sprite Texture Type settings, see Texture type: Sprite (2D and UI).

Sorting Sprites

Renderers in Unity are sorted by several criteria, such as their Layer order or their distance from the Camera. Unity’s GraphicsSettings (menu: Edit > Project SettingsA broad collection of settings which allow you to configure how Physics, Audio, Networking, Graphics, Input and many other areas of your project behave. More info
See in Glossary
, then select the Graphics category) provide a setting called Transparency Sort Mode, which allows you to control how Sprites are sorted depending on where they are in relation to the Camera. More specifically, it uses the Sprite’s position on an axis to determine which ones are transparent against others, and which are not.

An example of when you might use this setting is to sort Sprites along the Y axis. This is quite common in 2D games, where Sprites that are higher up are sorted behind Sprites that are lower, to make them appear further away.

There are four Transparency Sort Mode options available:

  • Default — Sorts based on whether the CameraA component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
    See in Glossary
    ’s Projection mode is set to Perspective or Orthographic

  • Perspective — Sorts based on perspective view. Perspective view sorts Sprites based on the distance from the Camera’s position to the Sprite’s center.

  • Orthographic — Sorts based on orthographic view. Orthographic view sorts Sprites based on the distance along the view direction.

  • Custom Axis — Sorts based on the given axis set in Transparency Sort Axis

If you have set the Transparency Sort Mode to Custom, you then need to set the Transparency Sort Axis:

If the Transparency Sort Mode is set to Custom Axis, renderers in the Scene viewAn interactive view into the world you are creating. You use the Scene View to select and position scenery, characters, cameras, lights, and all other types of Game Object. More info
See in Glossary
are sorted based on the distance of this axis from the camera. Use a value between –1 and 1 to define the axis. For example: X=0, Y=1, Z=0 sets the axis direction to up. X=1, Y=1, Z=0 sets the axis to a diagonal direction between X and Y.

For example, if you want Sprites to behave like the ones in the image above (those higher up the y axis standing behind the Sprites that are lower on the axis), set the Transparency Sort Mode to Custom Axis, and set the Y value for the Transparency Sort Axis to a value higher than 0.

Sorting Sprites using script

You can also sort Sprites per camera through scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary
, by modifying the following properties in Camera:

  • TransparencySortMode (corresponds with Transparency Sort Mode)

  • TransparencySortAxis (corresponds with Transparency Sort Axis)

For example:

var camera = GetComponent<Camera>();

camera.transparencySortMode = TransparencySortMode.CustomAxis;

camera.transparencySortAxis = new Vector3(0.0f, 1.0f, 0.0f);

  • 2018–04–25 Page amended

  • 2017–05–24 Page amended

  • Transparancy Sort Mode added in 5.6

Mifodiy

0 / 0 / 0

Регистрация: 07.04.2016

Сообщений: 3

1

22.10.2018, 13:55. Показов 50774. Ответов 10

Метки image, unity3d, спрайты (Все метки)


День добрый.
В Unity я новичок, в C# тоже, поэтому прошу сильно не пинать.
Сабж.
Есть объект Image, на нем спрайт и рядом кнопка. В папке Assets/Resourses лежат 3 спрайта. Планируется, чтобы при нажатии на кнопку, спрайт менялся циклически на один из трех (1-2-3-1 и т.д.). Но вместо этого изначальный спрайт меняется на белый фон и ничего больше не происходит. Прошу, ткните носом, где я ошибся. Заранее благодарю

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
 
 
 
public class ChangeClass : MonoBehaviour {
    private Sprite spr, spr1, spr2, spr3;
    public GameObject img;
    
    void Start(){
        
        
        img = GameObject.Find("ClassImage");
        spr = img.GetComponent<Image>().sprite;
        spr1 = Resources.Load<Sprite>("mage");
        spr2 = Resources.Load<Sprite>("snipe");
        spr3 = Resources.Load<Sprite>("warrior");
        Debug.Log(spr);
 
        if (spr = spr3) {
            img.GetComponent<Image>().sprite = spr1;
        }
        if (spr = spr1) {
                img.GetComponent<Image>().sprite = spr2;
            }
            else img.GetComponent<Image>().sprite = spr3;
    }
    
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Storm23

Эксперт .NETАвтор FAQ

10365 / 5096 / 1824

Регистрация: 11.01.2015

Сообщений: 6,226

Записей в блоге: 34

22.10.2018, 21:54

2

Mifodiy,
Во-первых, нельзя так сравнивать объекты.
Когда вы загружаете спрайт из ресурсов, создается новый объект. И сравнивать его с объектом в компоненте Image — нет смысла, они всегда будут не равны.
Во-вторых, не нужно завязывать логику приложения на визуальные компоненты и их содержимое.
Нужно создать модель данных и менять ее, а по модели данных уже строить визуальные компоненты.
В вашем случае модель простейшая — это просто номер картинки, которую нужно отображать. Нужно создать отдельное поле типа int, которое будет содержать номер отображаемой картинки и менять его при надобности. И тогда вы будете ориентироваться на ваши данные, а не на содержимое Image.

Вот пример:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using UnityEngine;
using UnityEngine.UI;
 
public class ImageChanger : MonoBehaviour
{
    //index of current image
    public int CurrentImageNumber;
 
    //names of images in Resources folder
    public string[] ImageNames = new string[] {"img1", "img2", "img3"};
 
    void Start ()
    {
        //load CurrentImageNumber from disk
        CurrentImageNumber = PlayerPrefs.GetInt("CurrentImageNumber");
        //show image
        ShowImage();
    }
 
    private void ShowImage()
    {
        //get name of image for CurrentImageNumber
        var name = ImageNames[CurrentImageNumber];
        //set image to Image component
        GetComponent<Image>().sprite = Resources.Load<Sprite>(name);
    }
 
    // Go to next CurrentImageNumber and show image
    // this method is handler of button click
    public void GoToNextImage()
    {
        //next CurrentImageNumber
        CurrentImageNumber = (CurrentImageNumber + 1) % ImageNames.Length;
        //show image
        ShowImage();
        //save CurrentImageNumber to disk
        PlayerPrefs.SetInt("CurrentImageNumber", CurrentImageNumber);
    }
}

Этот скрипт вешается на ваш Image.
А метод GoToNextImage вешается как обработчик на OnClick кнопки:

Изменить спрайт объекта Image



1



0 / 0 / 0

Регистрация: 07.04.2016

Сообщений: 3

22.10.2018, 22:42

 [ТС]

3

Спасибо огромное!



0



0 / 0 / 0

Регистрация: 04.07.2016

Сообщений: 6

11.04.2020, 16:22

4

Можешь про свой скрипт немного рассказать, просто я сейчас по нажатию хочу поменять картинку, но чет не вдупляю, откуда должны браться сами картинки



0



MrFelix

74 / 52 / 25

Регистрация: 08.03.2020

Сообщений: 243

11.04.2020, 16:32

5

Врядли он тебе подскажет, ибо тема 2018 года )
А по поводу картинок:

C#
1
2
3
4
5
[SerializeField] private Sprite[] spriteMassive; //если много картинок нужно или 
[SerializeField] private Sprite oneSprite; //один спрайт
 
yourImage.sprite = spriteMassive[1];
yourImage.sprite = oneSprite;

Добавлено через 52 секунды
PS Ссылки на картинки в испекторе укажешь

Добавлено через 1 минуту
https://habr.com/ru/post/359106/ можно ещё статью почитать



0



Katurina

2 / 2 / 0

Регистрация: 01.02.2017

Сообщений: 16

13.04.2020, 19:22

6

Картинка должна лежать в папке Assets/Resourses в проекте Unity (та на которую меняешь)
Смена происходит кодом:

C#
1
2
public image img;
img.sprite = Resources.Load<Sprite>('имя')

ps При этом надо очень внимательно с именем (одна опечатка и код работать не будет)
(данный пример применяется к объекту Image



0



74 / 52 / 25

Регистрация: 08.03.2020

Сообщений: 243

13.04.2020, 19:58

7

Цитата
Сообщение от Katurina
Посмотреть сообщение

ps При этом надо очень внимательно с именем (одна опечатка и код работать не будет)

Вот именно и вам тоже ))
public Image img;



0



0 / 0 / 0

Регистрация: 13.12.2020

Сообщений: 1

13.12.2020, 11:22

8

Цитата
Сообщение от Storm23
Посмотреть сообщение

Этот скрипт вешается на ваш Image.

Можете кто-нибудь объяснить, как повесить скрипт на Image



0



250 / 186 / 68

Регистрация: 04.03.2019

Сообщений: 1,010

16.12.2020, 23:44

9

JordyBordy, просто потянуть скрипт в нужное место.
2) вариант . ест ькнопка Add Component, там где компоненты все и там выбрать скрипт.



0



0 / 0 / 0

Регистрация: 22.02.2021

Сообщений: 1

22.02.2021, 20:54

10

Добавлено через 2 минуты
При попытке повесить скрипт на Image, пишет ошибку
The script don’t inherit a native class that can manage a script



0



0 / 0 / 0

Регистрация: 05.02.2022

Сообщений: 1

05.02.2022, 18:16

11

это значит, что имя скрипта не совпадает с именем класса



0



Понравилась статья? Поделить с друзьями:
  • Как изменить spf запись для почтового сервера
  • Как изменить spd оперативной памяти
  • Как изменить spawn rate minecraft
  • Как изменить spacing
  • Как изменить sources list ubuntu