You are on page 1of 5

Aprendiendo Unity: Gua de Introduccin de Programacin Bsica Andrs Hernndez Universidad Militar Nueva Granada

USO DE SCRIPTS EN UNITY Las secuencias de comando en Unity se logran a traves de la ejecucin de scripts simples hechos en JavaScript, Boo (variacin de phyton) o C #. Se pueden utilizar uno o todos los lenguajes de script en un solo proyecto, no hay restriccin para el uso de ms de uno. Cabe mencionar, que gran parte de los scripts encontrados en ejemplos y tutoriales estn construidos en Java. Crear un nuevo script en Unity A diferencia de otros archivos como mallas o texturas, los archivos de secuencias de comandos se pueden crear desde Unity. Para crear un nuevo script, realice lo siguiente: Assets-> Create-> JavaScript (o assets-> Create-> C Sharp Script o assets-> Create-> Boo Script) en el men principal. Esto crear un nuevo script llamado NewBehaviourScript ubicado en la carpeta seleccionada por el usuario. Si no hay ninguna carpeta seleccionada, el script se crear la carpeta raz. Se puede editar el script haciendo doble clic sobre este desde el visor de proyecto. Esto abrir Unitron, el editor de scripts de Unity. Toda la programacin se hace en un editor de texto externo como Unitron, y no en Unity directamente. Para configurar el editor de scripts por defecto, vaya a Unity-> Preferences-> External Script Editor. Un script vacio luce de esta manera:
funcin Update () ( )

Adicionandole una funcionalidad especifica como imprimir un mensaje en consola sera:


funcin Update () ( print ("Hola Mundo"); )

Aplicar secuencia de comandos a objetos del juego Para aplicar un script a un objeto determinado puede arrastrar el archivo de comandos y soltarlo sobre el objeto dentro del men de jerarquas o en Assets -> Scripts -> New Behaviour Script, una vez seleccionado el objeto. Manipular objetos Un print () es una declaracin que puede ser muy til al depurar el script, pero no manipula el objeto al cual se encuentra atado el script. Aadiendo algo de funcionalidad para transformar el objeto como por ejemplo:
funcin Update () ( transform.Rotate (0, 5 * Time.deltaTime, 0); )

Algunos parametros importantes para tener en cuenta son:

1. 2. 3. 4. 5.

funcin Update () () es un contenedor de cdigo que ejecuta se ejecuta en Unity varias veces por segundo (una vez por frame). Similar al void main de C++ transform es una referencia a la clase GameObject de transformacin de componentes . Rotate () es una funcin que figura en el componente de Transform. Los nmeros entre las comas representan los grados de rotacin alrededor de cada eje de un espacio 3D: X, Y y Z. Time.deltaTime es un miembro de la clase Tiempo que unifica el movimiento de ms de un segundo, por lo que el cubo gira a la misma velocidad sin importar el nmero de fotogramas por segundo que se despliegue en la mquina donde se ejecuta la prueba. Por lo tanto, 5 * Time.deltaTime significa 5 grados por segundo.

Con todo esto en mente, se puede leer este cdigo como "durante todos los fotogramas, gire este componente GameObject del" Transform "una pequea cantidad de modo que ser igual a cinco grados en el eje Y cada segundo." Se puede acceder a un gran nmero de diferentes componentes de la misma manera que se accedi a transform. Todos los componentes a los que se puede tener acceso fcilmente se enumeran a continuacin: Libreria de GameObect
Variables transform rigidbody camera light animation constantForce renderer audio guiText networkView guiTexture

The Transform attached to this GameObject. (null if there is none attached) The Rigidbody attached to this GameObject (Read Only). (null if there is none attached) The Camera attached to this GameObject (Read Only). (null if there is none attached) The Light attached to this GameObject (Read Only). (null if there is none attached) The Animation attached to this GameObject (Read Only). (null if there is none attached) The ConstantForce attached to this GameObject (Read Only). (null if there is none attached) The Renderer attached to this GameObject (Read Only). (null if there is none attached) The AudioSource attached to this GameObject (Read Only). (null if there is none attached) The GUIText attached to this GameObject (Read Only). (null if there is none attached) The NetworkView attached to this GameObject (Read Only). (null if there is none attached) The GUITexture attached to this GameObject (Read Only). (null if there is none attached)

collider hingeJoint particleEmitter layer active tag

The Collider attached to this GameObject (Read Only). (null if there is none attached) The HingeJoint attached to this GameObject (Read Only). (null if there is none attached) The ParticleEmitter attached to this GameObject (Read Only). (null if there is none attached) The layer the game object is in. A layer is in the range [0...32] Is the GameObject active? Activates/Deactivates the GameObject. The tag of this game object.

Constructors GameObject

Creates a new game object, named name.

Functions GetComponent

Returns the component of Type type if the game object has one attached, null if it doesn't. You can access both builtin components or scripts with this function. Returns the component of Type type in the GameObject or any of its children using depth first search. Returns all components of Type type in the GameObject. Returns all components of Type type in the GameObject or any of its children. Sets the active state of this and all the game objects children to state. Is this game object tagged with tag? Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour Calls the method named methodName on every MonoBehaviour in this game object. Calls the method named methodName on every MonoBehaviour in this game object or any of its children. Adds a component class named className to the game object. Samples an animation at a given time for any animated properties.

GetComponentInChildren GetComponents GetComponentsInChildren SetActiveRecursively CompareTag SendMessageUpwards

SendMessage BroadcastMessage AddComponent SampleAnimation

Class Functions

CreatePrimitive FindWithTag FindGameObjectsWithTag Find

Creates a game object with a primitive mesh renderer and appropriate collider. Returns one active GameObject tagged tag. Returns null if no GameObject was found. Returns a list of active GameObjects tagged tag. Returns null if no GameObject was found. Finds a game object by name and returns it.

Inherited members Inherited Variables name hideFlags

The name of the object. Should the object be hidden, saved with the scene or modifyable by the user?

Inherited Functions GetInstanceID

Returns the instance id of the object.

Inherited Class Functions operator bool Does the object exist? Instantiate Destroy DestroyImmediate FindObjectsOfType FindObjectOfType operator == operator != DontDestroyOnLoad Clones the object original and returns the clone. Removes a gameobject, component or asset. Destroys the object obj immediately. It is strongly recommended to use Destroy instead. Returns a list of all active loaded objects of Type type. Returns the first active loaded object of Type type. Compares if two objects refer to the same Compares if two objects refer to a different object Makes the object target not be destroyed automatically when loading a new scene.

Listado de Libreras
Animation AnimationClip AnimationCurve AnimationEvent AnimationState GUITexture

GUIUtility GameObject (Libreria de transformaciones, revisar detalladamente) GeometryUtility Gizmos Graphics

Nota: Para ver el listado completo referirse al manual de scripting de Unity online en :

http://unity3d.com/support/documentation/ScriptReference/GameObject.html

Referentes http://unity3d.com/support/documentation/ScriptReference.html Guia de Clases y Componentes oficial http://unityspain.com/soporte/guiadeprogC.html Programacin Bsica de C# http://www.unifycommunity.com/wiki/index.php?title=Main_Page Wikia de Scripts

You might also like