Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Showing a preview of a level (By instantiating sprites as images in a canvas)

Discussion in 'UGUI & TextMesh Pro' started by simplebitstudios, Dec 5, 2023.

  1. simplebitstudios


    Feb 14, 2018
    Hi everyone. I have been working on a save and load system, where i want the user to be able to see a preview of the level that they have created. I know the positions of the items that they have placed (in world space coordinates) and i have the sprites that they have placed (a tree, a rock etc).

    The problem is that i want to convert the world space coordinate of an item to screen space so that it fits relative into a small box by 16:9 (these are the image containers that will contain all the gameobjects as images). By doing this i am recreating the level (somewhat) as images inside of a canvas. I have tried many different things, but no matter what i do it seems like either the scaling of the images are off (too big or small relative to the world space item) or the position is somewhat off. Has anyone ever done something like this before?

    The code below is what i have tried, but it only seems to be perfect sizing when playing on a 16:9 aspect ratio. Could this have something to do with orthographic size? (3.5 right now). My reference resolution is 780 x 360 - Screen Match Mode: Expand

    Code (CSharp):
    1.         for (int i = 0; i < worldSpaceObjects.Count; i++)
    2.         {
    3.             Image image = Instantiate(_loadItemPrefab,, Quaternion.identity, _loadImageBackground);
    4.             image.sprite = _sandboxLevelData.ItemsDB[worldSpaceObjects[i].ID].Icon;
    6.             RectTransform rectTransform = image.GetComponent<RectTransform>();
    8.             Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, worldSpaceObjects[i].Position);
    9.             rectTransform.anchoredPosition = _loadTestCanvas.InverseTransformPoint(screenPoint);
    10.             rectTransform.sizeDelta = new Vector2(image.sprite.rect.width / _loadTestCanvas.localScale.x, image.sprite.rect.height / _loadTestCanvas.localScale.x);
    11.             rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, rectTransform.anchoredPosition.y + rectTransform.rect.height / 2);
    12.         }
    Image of what im trying to to do

    Attached Files: