I have three scenes.
1) Where you make your team.
2) Where the level is built.
3) The game.
On my team, there are 5 choices for each team member.
I am trying to figure out how I set the player and then recall the Image or Sprite of that player on another scene.
I figured a playerPref would work, but it seems like this is not an option.
What is a good way of saving an image from one scene and recalling the image in a different scene?
You can store texture of sprite as base64 in playerprefs, then you can create sprite from stored texture. But texture must be Read/Write Enabled and supported format like ARGB32, RGBA32, RGB24 etc. Here is an example;
using UnityEngine;
using System.Collections;
public class TextureStore
{
public static void WriteTextureToPlayerPrefs (string tag, Texture2D tex)
{
// if texture is png otherwise you can use tex.EncodeToJPG().
byte[] texByte = tex.EncodeToPNG ();
// convert byte array to base64 string
string base64Tex = System.Convert.ToBase64String (texByte);
// write string to playerpref
PlayerPrefs.SetString (tag, base64Tex);
PlayerPrefs.Save ();
}
public static Texture2D ReadTextureFromPlayerPrefs (string tag)
{
// load string from playerpref
string base64Tex = PlayerPrefs.GetString (tag, null);
if (!string.IsNullOrEmpty (base64Tex)) {
// convert it to byte array
byte[] texByte = System.Convert.FromBase64String (base64Tex);
Texture2D tex = new Texture2D (2, 2);
//load texture from byte array
if (tex.LoadImage (texByte)) {
return tex;
}
}
return null;
}
}
You could just save the name of the sprite to PlayerPrefs, and then load it from resources: Resources.Load(spriteName);
you can create a static texture variable. write texture of the image to that variable and read it on the other scene
Related
I want to access the sprites under the png I've got selected. (Which has already been sliced in the sprite editor)
Example: Here I know how I can make my GUIEditor see I have Druid_jump selected, now I want to grab hold of the Sprite type objects Druid_Jump_0_00 until Druid_Jump_3_03 by code (without interaction of my user) so that I can set up the 4 animations for them
I was trying with the following code sample:
List<Texture2D> textures = new List<Texture2D>(Selection.GetFiltered<Texture2D>(SelectionMode.Unfiltered));
foreach (Texture texture in textures)
{
if (texture != null)
{
string path = AssetDatabase.GetAssetPath(texture);
string containingFolder = null;
if (string.IsNullOrEmpty(containingFolder))
{
containingFolder = path.Remove(path.LastIndexOf('/'));
}
var importer = AssetImporter.GetAtPath(path) as TextureImporter;
List<Sprite> currentFrames = new List<Sprite>();
int index = 0;
foreach (SpriteMetaData spriteMetaData in importer.spritesheet)
{
string[] slice = spriteMetaData.name.Split('_');
if (slice[2] != index.ToString())
{
//CreateAnimation(currentFrames.Count, currentFrames);
currentFrames = new List<Sprite>();
index++;
}
// The Code works fine until here, I need the "Sprite" type object to set up the animation
Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>($"{containingFolder}/{spriteMetaData.name}");
//currentFrames.Add(sprite);
Debug.Log(sprite.name);
}
}
}
I was hoping Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>($"{containingFolder}/{spriteMetaData.name}"); would get the individual Sprite, but it currently finds null, while the spriteMetaData is actually returning the correct spritenames.
Sprite sprite = Sprite.Create(Texture2D texture, Rect rect, Vector2 pivot);
Your rect will be probably (0,0,resultionX,resulutionY), and pivot (0.5f, 0.5f)
Considering the image was already sliced into sprites, the correct answer was using AssetDatabase.LoadAllAssetsAtPath instead, which returns an Object array and includes the sprites under the png image. The AssetDatabase.GetAssetPath function does not include those.
Once we have the object array, we loop through the objects and cast the object to the sprite type and then we are good to go.
Object[] data = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(texture));
if(data != null)
{
foreach (Object obj in data)
{
if (obj.GetType() == typeof(Sprite))
{
Sprite sprite = obj as Sprite;
This question already has answers here:
How to pass data (and references) between scenes in Unity
(6 answers)
Closed 1 year ago.
I'm new to working in unity and i don't quite understand how to transfer data between scenes. In my case it's the sprites for my inventory when the player picks up an item. here is the code for the items sprites etc.
public class Items : MonoBehaviour
{
public string ItemName;
public string ItemText;
public int itemInList;
public Sprite itemSprite;
public InventorySlot inventorySlot;
public ItemSprites itemSprites;
public Sprite blueberrySprite;
public Sprite cheesecakeSprite;
public Sprite whitebreadSprite;
public Sprite cookiesSprite;
public void Awake()
{
//DontDestroyOnLoad(this);
}
public void gettingID()
{
GameObject Go = new GameObject();
Go.AddComponent<InventorySlot>();
inventorySlot = Go.GetComponent<InventorySlot>();
inventorySlot.itemID = itemInList;
}
public void ItemList()
{
// Cheesecake
if(itemInList == 1)
{
ItemName = "Cheesecake";
ItemText = "A delishious Juicy Cheesecake";
itemSprite = cheesecakeSprite;
}
// White Bread
if (itemInList == 2)
{
ItemName = "White Bread";
ItemText = "a basic white loaf that smells amazing";
itemSprite = whitebreadSprite;
}
// Cookies
if (itemInList == 3)
{
ItemName = "Cookies";
ItemText = "just plain Chocolatechip cookies, still delishious though";
itemSprite = cookiesSprite;
}
// Blueberries
if (itemInList == 4)
{
ItemName = "Blueberries";
ItemText = "Big juicy yummy blueberries!";
itemSprite = blueberrySprite;
Debug.Log(ItemText);
}
}
it works just fine when I'm in the scene where the script exist but when I try to use it in my new scene the image will turn out white(blank). I guess that is because the gameobject is not set anymore in the new scene, but how do i transfer the set gameobject sprite to a new scene? I now that you can make stuff static but if I read correctly then it doesn't work on gameobjects. and Dontdestroyonload doen't seem to work either cus the script is not attached to a gameobject in the scene.
a) You can make your sprite a static property in your class and you should be able to access it from anywhere in unity. You can make a simple DataHolder class to hold this value and other static values in your Game (It need not be a MonoBehaviour). However, you will need to load them somehow (From resources or AssetBundles) into your static Array
b) Check my Answer here on how to properly persist a GameObject in the Game if you are using DontDestroyOnLoad and have it attached to a GameObject in the scene. This should be a good option to use, considering you already have a MonoBehaviour class. Just attach it to a GameObject and Follow the answer in the link to maintain one correct instance of the Component.
c) Consider using a simple ScriptableObject if you want to save these values across multiple Game Sessions. It is a simple data container that helps you save data Independent of Classes.
Follow this link for Unity's Documentation on ScriptableObjects
So I have a Sprite 2d and UI in unity. (Png image) That contains many small images like buttons. So I slice them and I can use them individualy in unity. But the thing is that I want to export each of the png Images that I got while slicing them for another use. So can I do that? And have them as separate pngs?
And what I want is these Images:
To export them in my (lets say) desktop as individual pngs.
Thank you!
I had a need for this too, I ended up solving it with a simple editor script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ExportSubSprites : Editor {
[MenuItem("Assets/Export Sub-Sprites")]
public static void DoExportSubSprites() {
var folder = EditorUtility.OpenFolderPanel("Export subsprites into what folder?", "", "");
foreach (var obj in Selection.objects) {
var sprite = obj as Sprite;
if (sprite == null) continue;
var extracted = ExtractAndName(sprite);
SaveSubSprite(extracted, folder);
}
}
[MenuItem("Assets/Export Sub-Sprites", true)]
private static bool CanExportSubSprites()
{
return Selection.activeObject is Sprite;
}
// Since a sprite may exist anywhere on a tex2d, this will crop out the sprite's claimed region and return a new, cropped, tex2d.
private static Texture2D ExtractAndName(Sprite sprite) {
var output = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height);
var r = sprite.textureRect;
var pixels = sprite.texture.GetPixels((int)r.x, (int)r.y, (int)r.width, (int)r.height);
output.SetPixels(pixels);
output.Apply();
output.name = sprite.texture.name + " " + sprite.name;
return output;
}
private static void SaveSubSprite(Texture2D tex, string saveToDirectory) {
if (!System.IO.Directory.Exists(saveToDirectory)) System.IO.Directory.CreateDirectory(saveToDirectory);
System.IO.File.WriteAllBytes(System.IO.Path.Combine(saveToDirectory, tex.name + ".png"), tex.EncodeToPNG());
}
}
First, drop this into a script file named EditorSubSprites.cs and make sure that it resides in an Editor folder. If you have no editor folder you can simply create at /Assets/Editor/
To use, expand a texture asset's sprites, and select as many of the sprites as you wish to export. Right-click and select "Export SubSprites".
Use Photoshop, Crop it, a Lot of Cut and Paste is going to happen save as PNG.
Import it to unity inside the folder, i like your designs. Also Watch Brackeys Tutorial on Youtube, https://www.youtube.com/user/Brackeys , he save me from my school years.
(edit : i recommend Photoshop because its the only thing i know.)
I have a requirement of comparing two sprite textures for knowing those two sprites belongs to same image or not. Here those textures are loaded from urls. Thanks in advance.
Here is the sample code for getting sprite texture:
WWW imageLink = new WWW(imageUrl);
var spriteTexture = imageLink.texture;
In on of my case same image with two different urls. Once url is loaded, have a requirement of identifying those textures have belongs to same image. Please suggest any idea.
There is no easy util to compare the two textures, but luckily it's easy to write one. The method of Texture2D.GetPixels() will give you a Color[] array which represents a flattened 2d array of pixel colors. Each row of pixels will be placed one after the other, starting from the bottom to the top. Comparing the two arrays should prove the two textures are identical. I tried this code:
private bool CompareTexture (Texture2D first, Texture2D second)
{
Color[] firstPix = first.GetPixels();
Color[] secondPix = second.GetPixels();
if (firstPix.Length!= secondPix.Length)
{
return false;
}
for (int i= 0;i < firstPix.Length;i++)
{
if (firstPix[i] != secondPix[i])
{
return false;
}
}
return true;
}
With you code, you will simply need to call:
WWW imageLink = new WWW(imageUrl1); //first image URL
WWW imageLink2 = new WWW(ImageUrl2); //second image URL
if (CompareTexture(imageLink.texture, imageLink2.texture) {
....
}
To compare both textures.
I add a cube to unity scene. I want to set this cub's texture by using an image.
I use below code to load image and set texture :
Texture2D text2D = new Texture2D(Screen.width, Screen.height,TextureFormat.RGB24 , false);
text2D.SetPixels(((Texture2D)Resources.Load("image")).GetPixels());
MeshRenderer renderer = cube.GetComponent<MeshRenderer>();
renderer.material.mainTexture = text2D;
I see only a gray cube not the image on the scene.
You can shorten this quite a bit with only:
renderer.material.mainTexture = Resources.Load<Texture2D>("image");
Note that if the image is not found then you get null.
To see changes on the Texture2D, use text2d.Apply();
This is even more easy to do.
Try
public GameObject _cube;
void Start()
{
Renderer rend = _cube.GetComponent<Renderer> ();
rend.material.mainTexture = Resources.Load ("image") as Texture;
}
LoadImage method can also be used to do the job. But here, you have to pass in the image as .bytes format.
Example:
public TextAsset image;
void Start()
{
var texture = new Texture2D(100, 100, TextureFormat.ARGB32, false);
texture.LoadImage(image.bytes);
GetComponent<Renderer>().material.mainTexture = texture;
texture.Apply();
}