Search code examples
unity-game-enginegameobject

Convert GameObject to image?


So I'm making a card game and want my users to be able to create custom cards and not only use them in the game but also be able to print them.

Currently, I'm stuck on converting the UI GameObject of the card into a single image.

The card GameObject has a template card background, several other images (resources, main image, etc), and multiple text boxes (title, type, and description). Then I want to take that card hierarchy and convert it to a single image.

I thought this would be a fairly simple task but it appears to be a non-trivial... Or am I being a melon here?


Solution

  • Good question !

    A button calling Capture below upon press and some GameObject image to capture:

    enter image description here

    Code:

    using System.IO;
    using UnityEngine;
    
    public class NewBehaviourScript : MonoBehaviour
    {
        public GameObject GameObject;
    
        public void Capture()
        {
            var rectTransform = GameObject.GetComponent<RectTransform>();
            var delta         = rectTransform.sizeDelta;
            var position      = rectTransform.position;
    
            var offset = new RectOffset((int) (delta.x / 2), (int) (delta.x / 2), (int) (delta.y / 2), (int) (delta.y / 2));
            var rect   = new Rect(position, Vector2.zero);
            var add    = offset.Add(rect);
    
            var tex = new Texture2D((int) add.width, (int) add.height);
            tex.ReadPixels(add, 0, 0);
    
            var encodeToPNG = tex.EncodeToPNG();
    
            File.WriteAllBytes("card.png", encodeToPNG);
    
            DestroyImmediate(tex);
        }
    }
    

    In short, get object rect on screen, copy pixels, voila!

    Result:

    enter image description here