Change the sprite image while the game is running

Page update date :
Page creation date :

Verification environment

Windows
  • Windows 11
Unity Editor
  • 2020.3.25f1
Input System Packages
  • 1.2.0

Prerequisites for this tip

The following settings are pre-configured as a prerequisite for the explanation of these tips.

About changing the image of a sprite

As you can see when playing a 2D game, you will often see a scene where the image set as a sprite switches in the middle. For example, the door is closed at first, but by opening it, it is displayed as an open door.

To achieve this, you can prepare two objects, a closed door and an open door, and show or hide them. Here, we will try to achieve it by switching the image of the sprite.

Adding and placing images in a project

This time, you need an image before the change and an image after the change, so please prepare two. Here, the UnityTipsUnityTipsChange file name is , respectively.

Drop the sprite from the project and place it. When the button is clicked, the image changes, so place the button from the UI.

Creating an Image Change Script

Create a script. The name is arbitrary, but in this case SpriteChange , it is .

This time, click the button so that the image of the sprite changes at the timing. Also, the sprite to be changed will be set in advance. If you change it, you can create and configure sprites dynamically. The way to change it is basically the same.

The script looks like this:

using UnityEngine;

public class SpriteChange : MonoBehaviour
{
  /// <summary>画像を変更するスプライトオブジェクト。</summary>
  [SerializeField] private GameObject TargetSprite;

  /// <summary>変更後の画像を持つスプライト。</summary>
  [SerializeField] private Sprite NextSprite;

  /// <summary>ボタンをクリックしたときに呼ばれます。</summary>
  public void OnClick()
  {
    if (TargetSprite == null)
    {
      Debug.Log($"{nameof(TargetSprite)} が null です。");
      return;
    }
    if (NextSprite == null)
    {
      Debug.Log($"{nameof(NextSprite)} が null です。");
      return;
    }

    // 変更対象のオブジェクトが持つ SpriteRenderer を取得
    var spriteRenderer = TargetSprite.GetComponent<SpriteRenderer>();
    if (spriteRenderer == null)
    {
      Debug.Log($"{nameof(TargetSprite)} に {nameof(SpriteRenderer)} コンポーネントがありません。");
      return;
    }

    // SpriteRenderer の sprite に変更後のスプライトをセット
    spriteRenderer.sprite = NextSprite;
  }
}

In the field, prepare the sprite, the object to be changed, and the sprite that will be the image after the change.

GameObject You can see that you can set the target object from the hierarchy. Sprite It may be a question of what to set in .

For this, I think that the "texture type" of the image file added to the project is "Sprite (2D and UI)" by default, so it can be automatically treated as a sprite. So you can treat it as a sprite just by setting the image file.

/// <summary>画像を変更するスプライトオブジェクト。</summary>
[SerializeField] private GameObject TargetSprite;

/// <summary>変更後の画像を持つスプライト。</summary>
[SerializeField] private Sprite NextSprite;

OnClick The method is expected to be called when the button is clicked. The method name is arbitrary.

OnClick In the method, we are switching the image. Since is the one that has SpriteRenderer the image information, we get the component from the SpriteRenderer GameObject. SpriteRenderer The class has a property where you can swap the image by setting it to a sprite that has a sprite new image.

// 変更対象のオブジェクトが持つ SpriteRenderer を取得
var spriteRenderer = TargetSprite.GetComponent<SpriteRenderer>();

// 省略

// SpriteRenderer の sprite に変更後のスプライトをセット
spriteRenderer.sprite = NextSprite;

After you save the script, attach it to the object. The object to be attached is optional, but in this case EventSystem , it is attached to . Since there are "Target Sprite" and "Next Sprite" as parameters, "Target Sprite" has sprite objects from the hierarchy, "Next Sprite" is set to the changed image file from the project.

Specify the method from OnClick the script attached to the button's click event EventSystem .

Run the game and try to press the button. If the image changes, it is a success.