Home > database >  Make instantiated object visible on canvas
Make instantiated object visible on canvas

Time:11-13

I have a canvas, and I'd like an instantiated object to be positioned and visible on it.

In Scene view, it looks like it's right in the middle of the canvas. In Game view, it's not visible.

GameObject prefab = Resources.Load<GameObject>("cereal");
Vector3 point = new Vector3(0, 0, 10);
GameObject clone = Instantiate(prefab, point, Quaternion.identity) as GameObject;
clone.transform.parent = canvas.transform;
clone.transform.localScale = new Vector3(100f, 100f, 100f);

What am I doing wrong here?

CodePudding user response:

It depends on what render mode of canvas you are using.

Canvas has 3 rendering modes Screen Space - Overlay, Screen Space - Camera and World Space

  • For Screen Space - Overlay, if you want to show an object in the canvas rect you should use Camera.ScreenToWorldPoint() to convert the screen position to the world, but you must know where on the screen you want to see the object. Screen position it's position, where x in range 0 - Screen.width, y in range 0 - Screen.height. You must set the distance to the camera yourself.
    Example:

//Get the center of the screen; var centerOfTheScreen = new Vector3(Screen.width/2, Screen.height/2);
var camera = Camera.main;
var distance = camera.transform.forward * 10;// here you can set prefered distance;
var objectPosition = camera.ScreenToWorldPoint(centerOfTheScreen) distance;
var instance = Instanitate(prefab, objectPosition, Quaternion.identity);

  • For Screen Space - Camera you can use world position of the camera. In this mode no need to convert screen to world position, camera position will be enough. You can use distance calculation form the previous mode (var distance = camera.transform.forward * 10;) and add it to the camera position. It`s will looks like:

var camera = Camera.main;
var distance = camera.transform.forward * 10;// here you can set prefered distance;
var objectPosition = camera.transform.position distance;
var instance = Instanitate(prefab, objectPosition, Quaternion.identity);

  • For World Space you can directly use world position of the canvas gameobject, but, I think, it`s not you case. Just use canvas position instead camera. Example:

//This code snippet create object benind canvas. If you want create object on canvas - remove distance var distance = canvas.transform.forward * 10;// here you can set prefered distance;
var objectPosition = canvas.transform.position distance;
var instance = Instanitate(prefab, objectPosition, Quaternion.identity);

UPD: If you want to make an object the child of a canvas transform, you can use instance.transform.SetParent(canvas.transform, false) and after that use the calculation described above. For the World Space canvas it will be even easier.

  • Related