简体   繁体   中英

How to store a sprite in a global variable using c# script after touch event in unity for a 2D game?

I am new to unity and want to store a sprite in a global variable to access in other scene after touch event occurs. Any idea in this regard will be appreciated.

I would like to propose an approach to solve this case.

Define a sprite manager class "MySpriteManager" as follows:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class MySpriteManager {
    private static Dictionary<string, Sprite> spriteMap = new Dictionary<string, Sprite>();

    public static void AddSprite(string key, Sprite value) {
        spriteMap.add(key, value);
    }

    public static Sprite GetSprite(string key) {
        return spriteMap[key];
    }
}

Whenever you want to save a sprite instance for future uses,

MySpriteManager.AddSprite("my_sprite_key", my_sprite_instance);

To retrieve a previously saved sprite instance,

Sprite savedSprite = MySpriteManager.GetSprite("my_sprite_key");

Hopefully the idea is illustrated clearly enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM