SetParent after Instantiate

Hello guys. I’m making a simple 2D game for android and i have really annoying problem.

I’m trying to instantiate a UI Image and i’m parenting it to my canvas. That works fine okey but, then when i scale my screen weird things happens. If my screen is small my image is big, if my screen is huge my image is small. What should i do to fix this issue? I’ve searched a little bit and i came across with using SetParent but i couldn’t do it. Thanks for your help!

This is my code:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class BallSpawner : MonoBehaviour
{
    
    public GameObject[] Objects;
    public float Timer;
    public bool FirstPlay;
        
    void Start()
    {
        Timer = 5;
    }
           
    void Update()
    {
        if(FirstPlay == true)
        {
            Timer = 2;
            FirstPlay = false;
        }

        Timer -= 1 * Time.deltaTime;
        if(Timer <= 1) {
        GameObject instance1 = (GameObject)Instantiate(Objects[Random.Range(0, Objects.Length)], transform.position, transform.rotation);
            instance1.transform.SetParent(newParent, false);
        Timer = 5;
         
        }
        
    }
}

check the asset store

1 Answer

1

As a matter of fact, the Canvas is essentially the same size and set parent is working properly. This is a regular problem where the canvas scales with screen size, but not completely. In OnGUI(), this was taken care of by making two variables Screen.height and Screen.width to support all sizes. Maybe you can scale the RectTransform of your UGUI component using the same method?

Create two variables and set them to the current screen’s height and width. Then, upon instantiation, set the rect transform of the object accordingly taking help from the two variables.

Hope this helps.