- Home /
How to combine sprites together dynamically?
Is there a way to combine multiple sprites into a single sprite dynamically(say, when the sprite count reaches 500 or so). The game object we use consists of a sprite renderer which has a sprite attached to it. When i run my application the gameobject keeps on increasing and ideally we will have about 1200 gameobjects in our scene at runtime. When the count goes to 4000, the fps is dropping drastically to 15 fps. Is there a way to reduce this number by combining the objects together at runtime.
Have you looked into Batching? How many Draw Calls are you seeing?
Answer by Cavite8567 · Mar 19, 2018 at 05:04 PM
Yes, sort of, I'm not sure if this is the best method but you can create a new Texture that is as tall as the sprites added together vertically, and as wide as the textures added horizontally. This script will make the objects texture equal to the texture of tex1 on the bottom and tex2 on the top. Also keep in mind that both textures have to be read and writeable. Hopefully this helps!
using UnityEngine;
using System.Collections;
public class DynamicSprites : Monobehavior {
public Texture2D mainTex;
public Sprite tex1;
public Sprite tex2;
void Update()
{
for(int x = 0; x < tex1.width; x++)
{
for(int y = 0; y < tex1.height; y++)
{
mainTex.SetPixel(x,y,tex1.GetPixel(x,y));
}
}
for(int x = 0; x < tex2.width; x++)
{
for(int y = 0; y < tex2.height; y++)
{
// Add the height or width of the first image to either the x or y, in this case y because the texture will be on top.
mainTex.SetPixel(x,y + tex1.height,tex1.GetPixel(x,y));
}
}
mainTex.Apply();
GetComponent<SpriteRenderer>().sprite = Sprite.Create(mainTex, new Rect(0,0,mainTex.width,mainTex.height), Vector2.zero);
}
}
I get this error "Texture 'Checkmark' is not readable, the texture memory can not be accessed from scripts." when I try GetPixel()
Turn on "Read/Write" for that texture, in import settings.
Yes, or you can use this too: https://answers.unity.com/questions/988174/create-modify-texture2d-to-readwrite-enabled-at-ru.html
Answer by viku_99 · Feb 05, 2019 at 09:22 AM
Assign camera and render texture and render it in new raw image or image and you will save those combine sprites.@anto_skillveri