Instantiate an Image from the UI

Actually I tried to use this code in order to Instantiate an UI element which is an image via a button.
When I press the button it instantiate the image or panel in the hierarchy but it doesn’t show that in the execution, I searched but I didn’t find how to fix that.
Here is the code used:

using UnityEngine;
using System.Collections;

public class Instantiation2 : MonoBehaviour
{
public Transform _prefab;
public float _radius = 2;

// Update is called once per frame
public void Update ()
{
//if ( Input.GetKey(“space”) )
//{
//Create a random position.
//The insideUnitSphere return a random position inside a sphere of radius 1.
Vector3 rndPos = Random.insideUnitSphere * _radius;

//Create a random rotation.
//Quaternion rndRotation = Random.rotation;

//Instantiate a new object at a random position
Transform newGameObj = Instantiate( _prefab, rndPos,Quaternion.identity) as Transform;
//}
}
}

I don’t know what I’m missing in this. Thank you for any suggestions :slight_smile:

Shouldn’t you be instantiating it as a game object?

I didn’t understand what do you mean ? !
How I could do with game object ?

Where you are instantiating it you are saying to instantiate it as a transform, which is just a set of vector coordinates.

I normally just use:
Instantiate (prefabName, spawnSpot.transform.position, spawnSpot.transform.rotation);

I will test it !
I don’t have much idea how to instantiate.

I got this error :

The name spawnSpot doesn’t exist in this actuel context

@tedthebug
using instantiate with a transform still creates a gameobject, it just returns a reference to the transform component. This is instantiates behaviour regardless of what is passed into it i.e. have the prefab reference by a script component type, the entire prefab is created and a reference to the script component is returned.

@rimiki
UI elements need to be parented to something that either is a canvas or is a child of a canvas

http://docs.unity3d.com/Manual/HOWTO-UICreateFromScripting.html

1 Like

Thanks for clearing that up for me, seems I must’ve missed that bit in class (or just didn’t understand it when they said it)