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
@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