GameObject - Transform Component

From ETC Public Wiki
Revision as of 14:26, 31 August 2012 by Khilf (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Overview


Components of Game Object


Moving an Object


  • Every GameObject has a component called Transform.
  • Transform, controls the position, rotation, and the scaling of that Object.
void Update(){
     
     // Moving in the forward direction of this Object over time
     transform.Translate(Vector3.forward * Time.deltaTime);

}


Instantiate an Object


  • Clones the original object and returns a clone.
  • Common use for creating projectiles.
  • Instantiate
using UnityEngine;
using System.Collections;

// Here is an example of instantiating prefabs from a Fall 2012 BVW workshop during Round 0
public class BlimpFactory : MonoBehaviour {
   
    public GameObject blimpToSpawn;
    public float blimpDelay;
   
    // Use this for initialization
    void Start () {
        StartCoroutine(MakeBlimps());
    }
   
    // Update is called once per frame
    void Update () {
   
    }
   
    // This coroutine will spawn an object based on the public variable blimpToSpawn and wait blimpDelay seconds between
    // each blimp.  This works for any prefab.
    IEnumerator MakeBlimps()
    {
        int blimpNum = 0;
       
        while (true)
        {
            // Instantiate returns a reference to the cloned object.  You'll usually need to cast it to GameObject as shown
            // below if you intend to make any changes to it.  In this example, we rename it differently and give it a number.
            // Usually cloned objects have the same name as their source object, but with "(Clone)" appended to their name.
            GameObject newBlimp = (GameObject)Instantiate(blimpToSpawn, transform.position, transform.rotation);
            newBlimp.name = "Cloned Blimp #" + blimpNum++;
           
            yield return new WaitForSeconds(blimpDelay);
           
            transform.Rotate(0.0f, 10.0f, 0.0f);
        }
    }
}


Destroying an Object


void Update(){
        
      if(transform.position.y > 11.5)
	  Destroy(this.gameObject);

}