Question by
Dabbash · May 02, 2016 at 02:57 PM ·
gameobjectclonerandom spawn
How to generate random clone
Hi, Im new to unity and I really need some help, my project is to click by mouse any where in the screen and it pop up a new clone of the original GameObject, so if some one can help me with a full code in C# to learn. Thank you :)
Comment
Answer by Nido · May 02, 2016 at 03:11 PM
Instantiate the selected gameObject at the mouse position. If you want to make a random gameObject from a pool, just store a GameObject[] (array) with some "originals" inside, and when you click the mouse....
using UnityEngine;
using System.Collections;
public class RandomInstantiate : MonoBehaviour
{
public GameObject[] yourArray;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 spawnPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f));
int index = Random.Range(0, yourArray.Length);
Instantiate(yourArray[index], spawnPosition, Quaternion.identity);
}
}
}