Page 1 of 1

Unity Scripting : Instantiation

PostPosted: Wed Feb 11, 2015 6:09 pm
by BenChang
Code: Select all
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class InstantiationExample : MonoBehaviour {
   public GameObject prefab;
   private List<GameObject> objs;
   
   void Start () {
      objs  = new List<GameObject>();
   }
   
   void Update () {
      if (Input.GetKeyDown(KeyCode.A))
      {
         Spawn();      
      }
      if (Input.GetKeyDown (KeyCode.S))
      {
         Kill ();
      }
   }
   
   void Spawn()
   {
      GameObject g = Instantiate (prefab) as GameObject;
      objs.Add (g);
      g.transform.parent = transform;
      g.transform.localPosition = new Vector3 ( objs.Count,0,0);
   }
   
   void Kill ()
   {
      if (objs.Count>0)
      {
      int i = (int) Random.Range(0,objs.Count);
      Destroy (objs[i]);
      objs.RemoveAt (i);
      }
   }
}