Unity Scripting : Instantiation

Unity Scripting : Instantiation

Postby BenChang » Wed Feb 11, 2015 6:09 pm

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);
      }
   }
}
User avatar
BenChang
 
Posts: 176
Joined: Mon Jan 17, 2011 4:48 pm

Return to Game Development

Who is online

Users browsing this forum: No registered users and 2 guests

cron