Unity 3D Game Engine – JS – Basics – GameObjects – Get
A good practice is to check the properties of external GameObjects using JS.
Now, using a script inside an Empty Object we will drive other GameObjects.
Follow this steps:
1. store the GameObject inside a variable: var myobject : GameObject;
2. DRAG AND DROP from Hierarchy to Inspector var slot the object
3. Code it:
varname.property = ….
varname.component.property = …
See the JavaScript:
var myobject : GameObject; // ASSIGN IN INSPECTOR!!!!!!! function Update () { // NOTICE: varname.property = .... myobject.transform.Rotate(Vector3.back, 30f * Time.deltaTime); // NOTICE: varname.component.property = .... myobject.renderer.material.color.a = 0.5; // set transparency to 50% }
See API documentation at: http://docs.unity3d.com/ScriptReference/index.html
Let’s go on!
0. Project window> RMB> Import New Asset:
– Audio Clip
1. MAIN TOP MENU> GameObject> Create:
– Main Camera
– Point Light
– GUIText
– Cube
-> Transform
-> Mesh Filter
-> Box Collider
-> Mesh Renderer> add ‘material1’ (Transparent/Diffuse Shader)
-> Particle System
2. Create Empty Object, name it ‘Game Controller’
-> Audio Source without audio clip
->’GameController.JS’
#pragma strict // create var to get some external GameObjects START ################# // ASSIGN IN INSPECTOR var mytext : GUIText; var myobject : GameObject; var mycamera : Camera; var mylight : Light; var myaudio : AudioClip; // create var to get some external GameObjects END ################### function Start () { // instantiate objects at x=0 y=0 z=0, Quaternion.identity-> it means no rotation // You can use a prefab // Start() will be executed only once -> it will create only one clone Instantiate (myobject, new Vector3(0f,0f,0f), Quaternion.identity); // play audio clip at volume 0.7 audio.PlayOneShot(myaudio, 0.7); } function Update () { // change the property .text of GUIText // NOTICE: varname.property = .... mytext.text = "Change this properties using scripts!"; // rotate game object // NOTICE: varname.property = .... myobject.transform.Rotate(Vector3.back, 30f * Time.deltaTime); // translate game object myobject.transform.Translate(new Vector2(1,0)* 1f *Time.deltaTime); // set transparency // NOTICE: varname.component.property = .... myobject.renderer.material.color.a = 0.5; // set transparency to 50% // set particle system start color myobject.particleSystem.startColor = Color.cyan; // disable collider myobject.collider.enabled = false; // change light color mylight.light.color = Color.red; // change camera skybox color mycamera.camera.backgroundColor = Color.green; } // end Update() #######################################################
3. Hierarchy DRAG AND DROP:
– Main Camera over Inspector mycamera variable
– Point Light over Inspector mylight variable
– Gui Text over Inspector mytext variable
– Cube over Inspector myobject variable
– Audio Clip over Inspector myaudio variable
4. Play