This document provides an introduction to scripting with Unity using Javascript. It aims to teach the fundamentals of scripting through a tutorial that has the user write scripts to control a player camera and spawn objects. The summary covers:
1. The tutorial introduces scripting in Unity using Javascript and covers naming conventions, connecting variables to assign them via the GUI, accessing other components, and instantiating objects at runtime.
2. Early scripts have the player move the main camera using keyboard input and add a spotlight that follows it.
3. Debugging techniques like Debug.Log() and exposing private variables are demonstrated to help troubleshoot scripts.
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)noorcon
We go deeper into the concept of GameObjefts. How to create them, how to add components. Scripts are discussed and shown how they can be converted into components and attached to the GameObject. Finally the concept of Prefab and parent/child relationship are discussed.
Getting to know unity, special thanks to JUST and my friend Ruba Al-Saa'di and Dr. Natheer.
We are waiting for Patented a small request caused a technology revolution.
An introductory presentation about the Unity game engine given at GarageGeeks HQ in 2012, meant to bring programmers who have no game development experience up to speed with Unity
Introduction to Game Programming: Using C# and Unity 3D - Chapter 3 (Preview)noorcon
We go deeper into the concept of GameObjefts. How to create them, how to add components. Scripts are discussed and shown how they can be converted into components and attached to the GameObject. Finally the concept of Prefab and parent/child relationship are discussed.
Getting to know unity, special thanks to JUST and my friend Ruba Al-Saa'di and Dr. Natheer.
We are waiting for Patented a small request caused a technology revolution.
An introductory presentation about the Unity game engine given at GarageGeeks HQ in 2012, meant to bring programmers who have no game development experience up to speed with Unity
Unity 3d is a popular game engine used to design games for mobiles,xbox etc.
It was developed by unity technologies and it was useful to those who want to start game designing
Unity is a cross-platform game engine developed by Unity Technologies,[4] first announced and released in June 2005 at Apple Inc.'s Worldwide Developers Conference as an OS X-exclusive game engine. As of 2018, the engine has been extended to support 27 platforms.[5] The engine can be used to create both three-dimensional and two-dimensional games as well as simulations for desktops and laptops, home consoles, smart TVs, and mobile devices. Several major versions of Unity have been released since its launch, with the latest stable version being Unity 2018.2.2, released on August 10, 2018.[6]
Unity gives users the ability to create games in both 2D and 3D, and the engine offers a primary scripting API in C#, for both the Unity editor in the form of plugins, and games themselves, as well as drag and drop functionality. Prior to C# being the primary programming language used for the engine, it previously supported Boo, which was removed in the Unity 5[7] release, and a version of JavaScript called UnityScript, which was deprecated in August 2017 after the release of Unity 2017.1 in favor of C#.[8]
The engine has support for the following graphics APIs: Direct3D on Windows and Xbox One; OpenGL on Linux, macOS, and Windows; OpenGL ES on Android and iOS; WebGL on the web; and proprietary APIs on the video game consoles. Additionally, Unity supports the low-level APIs Metal on iOS and macOS and Vulkan on Android, Linux, and Windows, as well as Direct3D 12 on Windows and Xbox One.
Cocos2d is a well known open source software framework on game industry. It is is a 2D game framework built upon the OpenGL ES API’s.
In this session, I will talk about a hierarchical structures of an Cocos2d node and scenes. Also Cocos2d Graphic User Interface, Physical System, Audio, Particle System and Scene Transition technique will be shown. Finally this session will show various branches of Cocos2d open source projects including Cocos2d-x, Cocos2d-Swift, Cocos2d-html5, and Cocos2d-xna.
DSC RNGPIT - Getting Started with Game Development Day 1DeepMevada1
DSC RNGPIT had organized a session on Game Development where students where introduced to the basics of Game Development and the Unity Game Engine Interface.
Students were also introduced to the game development flowchart where an example of Flappy Bird was given, and were also given a task to make flowcharts for their games.
Unity 3d is a popular game engine used to design games for mobiles,xbox etc.
It was developed by unity technologies and it was useful to those who want to start game designing
Unity is a cross-platform game engine developed by Unity Technologies,[4] first announced and released in June 2005 at Apple Inc.'s Worldwide Developers Conference as an OS X-exclusive game engine. As of 2018, the engine has been extended to support 27 platforms.[5] The engine can be used to create both three-dimensional and two-dimensional games as well as simulations for desktops and laptops, home consoles, smart TVs, and mobile devices. Several major versions of Unity have been released since its launch, with the latest stable version being Unity 2018.2.2, released on August 10, 2018.[6]
Unity gives users the ability to create games in both 2D and 3D, and the engine offers a primary scripting API in C#, for both the Unity editor in the form of plugins, and games themselves, as well as drag and drop functionality. Prior to C# being the primary programming language used for the engine, it previously supported Boo, which was removed in the Unity 5[7] release, and a version of JavaScript called UnityScript, which was deprecated in August 2017 after the release of Unity 2017.1 in favor of C#.[8]
The engine has support for the following graphics APIs: Direct3D on Windows and Xbox One; OpenGL on Linux, macOS, and Windows; OpenGL ES on Android and iOS; WebGL on the web; and proprietary APIs on the video game consoles. Additionally, Unity supports the low-level APIs Metal on iOS and macOS and Vulkan on Android, Linux, and Windows, as well as Direct3D 12 on Windows and Xbox One.
Cocos2d is a well known open source software framework on game industry. It is is a 2D game framework built upon the OpenGL ES API’s.
In this session, I will talk about a hierarchical structures of an Cocos2d node and scenes. Also Cocos2d Graphic User Interface, Physical System, Audio, Particle System and Scene Transition technique will be shown. Finally this session will show various branches of Cocos2d open source projects including Cocos2d-x, Cocos2d-Swift, Cocos2d-html5, and Cocos2d-xna.
DSC RNGPIT - Getting Started with Game Development Day 1DeepMevada1
DSC RNGPIT had organized a session on Game Development where students where introduced to the basics of Game Development and the Unity Game Engine Interface.
Students were also introduced to the game development flowchart where an example of Flappy Bird was given, and were also given a task to make flowcharts for their games.
Introduction to Game Programming: Using C# and Unity 3D - Chapter 2 (Preview)noorcon
The reader is introduced to the Unity 3D IDE. The basic sections of the IDE are defined and explained. The reader is show how to navigate within the IDE and create GameObjects. How to perform transformations and etc… The Inspector Window is also discussed.
Introduction to html5 game programming with ImpactJsLuca Galli
A brief introduction to HTML5 Game Development that describes and use ImpactJs, one of the most famous and complete frameworks for HTML5 Games, mostly for learning purposes. The benefits of HTML5 Games are described, along with the importance of using a Framework and describing in details the ImpactJs Game Engine (no code provided, since it's proprietary). Two different games are coded on the fly during the lesson, while providing tips and suggestions. The Reference, Bibliography and Resources section provide useful pointers for beginners.
HoloLens Unity Build Pipelines on Azure DevOpsSarah Sexton
Developers of Unity UWP apps: stop wasting time compiling builds in Unity, then Visual Studio, then manually deploying. Save time with an automated pipeline! Create builds from start to finish, implement Unit Tests, save every build artifact, and even distribute using App Center! Learn how to create a Azure DevOps pipeline that can be used to build any Mixed Reality solution.
Applications use in Java GUIThe Java GUI consists of a separate, .pdfakshay1213
Applications use in Java GUI:
The Java GUI consists of a separate, automous task execution thread called the \"event loop\".
Every action that affects the GUI, e.g. calls to repaint the screen or to manipulate the properties
of a GUI component, or is a result of something happening to the GUI, e.g. the user clicks the
mouse or hits a key, is encapsulated in the form of an \"event\" that is placed into a queue for the
event loop to process. The result of processing an event may be a manipulation of the bits of
color on the screen or it may result in calls to methods in the developer\'s code.
1.A Java GUI application uses the standard Java components GUI component set, Swing, and is
deployed to the desktop.
2.The Swing GUI Builder in NetBeans IDE simplifies the GUI development process and enables
you to visually create Java GUI applications using pre-installed Swing and AWT components.
3.JavaFX is a rich set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications (RIAs) that behave consistently across multiple
platforms.
Similariti Between JAVA and JAVA GUI:
I think in many cases the overhead incurred to run a JVM is acceptable because of the
functionality the code base
provides.So winding back a bit, the reason that functionality can exist with Java has much to do
with the language/environment which frees programmers from a lot of resource management and
allows them to focus
more on plugging together components. Time to market and all that jazz.Like a lot of interpreted
languages, Java\'s development cycle ispretty excellent I think. A programmer can get a fairly
complicatedapplication off the ground quickly due to a number of things broughtabout both by
the interp-language development paradigm that allows for
immediate detection of errors and compile-and-test-as-you-code sessions.I think those are the
kinds of things which has made Java popular.
Some Java applications that you can install and play with on your own desktop machine:
1.Eclipse
2.NetBeans
3.jEdit
4.OpenOffice
Java is used in
JAVA GUI:
The Java GUI system however is a legacy issue where the system underwent a large-scale
upgrade , so some of the classes involved are spread over the (relatively) older java.awt packages
and the newer javax.swing packages. In general, if the class name starts with \"J\", then it is in
the Swing package. Since some functionality appears to be duplicated in the Swing packages,
such as frames and buttons, always use the Swing component over the older AWT components
when there is a choice.
Commonly Used Methods in GUI Components:
void setPreferredSize(int width, int height) :sets the size of a component to be used when the
layout manager is able to use that size, e.g. there is enough room. Some layout managers always
ignore the size setting of a component because the size is under other constraints..
String getText(), void setText(String s) :accessor methods for the text of labels, button.
this presentation serve as an introduction to Angular JavaScript framework and also touch on some basic modern JavaScript, front-end development basics.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
JMeter webinar - integration with InfluxDB and Grafana
2%20-%20Scripting%20Tutorial
1. Introduction to scripting with Unity
Scripting is an essential part of Unity as it
defines the behaviour of your game. This
tutorial will introduce the fundamentals of
scripting using Javascript. No prior knowledge
of Javascript or Unity is required.
Time to complete: 2 hours.
Author: Graham McAllister
Contents 1. Aims of this tutorial
Scripting is how the user defines a game’s behaviour (or
1. Aims of this tutorial rules) in Unity. The recommended programming
language for Unity is Javascript, however C# or Boo
2. Prerequisites can also be used. This tutorial will cover the
3. Naming conventions fundamentals of scripting in Unity and also introduce key
elements of the Application Programming Interface (API).
4. Player Input You can think of the API as code that has already been
5. Connecting variables written for you which lets you concentrate on your game
design and also speeds up development time.
6. Accessing components
A good understanding of these basic principles is
7. Instantiate essential in order to harness the full power of Unity.
8. Debugging
9. Common Script Types
2. Prerequisites
This tutorial focuses on the scripting element of Unity, it
is assumed you are already familiar with Unity’s interface
(if not you should read the Unity GUI tutorial).
In order to make scripting easier to understand, it is
preferable to have a code editor that has syntax
highlighting support for Javascript. This means that
reserved words (syntax used by Javascript itself) are
coloured differently than user defined words. One such
editor is SubEthaEdit.
NB: any text that requires the user to take an action
begins with a ‘-’.
2. 3. Naming Conventions
Before we begin, it is worth mentioning some conventions in Unity.
Variables - begin with a lowercase letter. Variables are used to store information about
any aspects of a game’s state.
Functions - begin with an uppercase letter. Functions are blocks of code which are
written once and can then be reused as often as needed.
Classes - begin with an uppercase letter. These can be thought of as collections of
functions.
Tip: When reading example code or the Unity API, pay close attention to the first letter of
words. This will help you better understand the relationship between objects.
4. Player Input
For our first program we’re going to allow the user
to move around in a simple game world.
Setting the scene
- Start Unity.
Firstly, let’s create a surface for the user to walk on.
The surface we’re going to use is a flattened cube
shape.
- Create a cube and scale its x,y,z dimensions to 5, 0.1, 5 respectively, it should now
resemble a large flat plane. Rename this object ‘Plane’ in the Hierarchy View.
- Create a 2nd cube and place it at the centre of this plane. If you can’t see the objects in
your Game View, alter the main camera so they’re visible. Rename the object to
Cube1.
- You should also create a point light and place it above the cubes so that they’re more
easily visible.
- Save the scene by selecting File->Save As and give the game a name.
Our first script
We’re now ready to start game programming. We’re going to allow the player to move
around the game world by controlling the position of the main camera. To do this we’re
going to write a script which will read input from the keyboard, then we attach (associate)
the script with the main camera (more on that in the next section).
- Begin by creating an empty script. Select Assets->Create->Javascript and rename this
script to Move1 in the Project Panel.
- Double-click on the Move1 script and it will open with the Update() function already
inserted (this is default behaviour), we’re going to insert our code inside this function.
Any code you insert inside the Update() function will be executed every frame.
2
3. In order to move a game object in Unity we need to alter the position property of its
transform, the Translate function belonging to the transform will let us do this. The
Translate function takes 3 parameters, x, y and z movement. As we want to control the
main camera game object with the cursor keys, we simply attach code to determine if the
cursor keys are being pressed for the respective parameters:
function Update () {
transform.Translate(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
}
The Input.GetAxis() function returns a value between -1 and 1, e.g. on the horizontal axis,
the left cursor key maps to -1, the right cursor key maps to 1.
Notice the 0 parameter for the y-axis as we’re not interested in moving the camera
upwards. The Horizontal and Vertical axis are pre-defined in the Input Settings, the names
and keys mapped to them can be easily changed in Edit->Project Settings->Input.
- Open the Move1 Javascript and type in the above code, pay close attention to capital
letters.
Attaching the script
Now that our first script is written, how do we tell Unity which game object should have this
behaviour? All we have to do is to attach the script to the game object which we want to
exhibit this behaviour.
- To do this, first click on the game object that you wish to have the behaviour as defined
in the script. In our case, this is the Main Camera, and you can select it from either the
Hierarchy View or the Scene View.
- Next select Components->Scripts->Move1 from the main menu. This attaches the
script to the camera, you should notice that the Move1 component now appears in the
Inspector View for the main camera.
Tip: You can also assign a script to an game object by dragging the script from the
Project View onto the object in the Scene View.
- Run the game (press the play icon at the lower left hand corner), you should be able to
move the main camera with the cursor keys or W,S,A,D.
You probably noticed that the camera moved a little too fast, let’s look at a better way to
control the camera speed.
Delta time
As the previous code was inside the Update() function, the camera was moving at a
velocity measured in meters per frame. It is better however to ensure that your game
objects move at the more predictable rate of meters per second. To achieve this we
multiply the value returned from the Input.GetAxis() function by Time.deltaTime and also
by the velocity we want to move per second:
3
4. var speed = 5.0;
function Update () {
var x = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
var z = Input.GetAxis("Vertical") * Time.deltaTime * speed;
transform.Translate(x, 0, z);
}
- Update the Move1 script with the above code.
Notice here that the variable speed is declared outside of the function Update(), this is
called an exposed variable, as this variable will appear in the Inspector View for whatever
game object the script is attached to (the variable gets exposed to the Unity GUI).
Exposing variables are useful when the value needs to be tweaked to get the desired
effect, this is much easier than changing code.
5. Connecting Variables
Connecting variables via the GUI is a very powerful
feature of Unity. It allows variables which would
normally be assigned in code to be done via drag and
drop in the Unity GUI. This allows for quick and easy
prototyping of ideas. As connecting variables is done
via the Unity GUI, we know we always need to expose
a variable in our script code so that we can assign the
parameter in the Inspector View.
We’ll demonstrate the connecting variables concept
by creating a spotlight which will follow the player
(Main Camera) around as they move.
- Add a spotlight to the Scene View. Move it if necessary so it’s close to the other game
objects.
- Create a new Javascript and rename it to Follow.
Let’s think what we want to do. We want our new spotlight to look at wherever the main
camera is. As it happens, there’s a built in function in Unity to do this, transform.LookAt().
If you were beginning to think ‘how do I do this?’ and were already imagining a lot of code,
then it’s worth remembering to always check the Unity API for a function that already
exists. We could also make a good guess at looking in the ‘transform’ section of the API
as we’re interested in altering the position or rotation of a game object.
Now we come to the connecting variables section; what do we use as a parameter for
LookAt()? Well we could hardcode a game object, however we know we want to assign
the variable via the GUI, so we’ll just use an exposed variable (of type Transform). Our
Follow.js script should look like this:
var target : Transform;
function Update () {
transform.LookAt(target);
}
4
5. - Attach the script to the spotlight and notice when the component gets added, the
“target” variable is exposed.
- With the spotlight still selected, drag the Main Camera from the Hierarchy View onto the
“target” variable in the Inspector View. This assigns the target variable, i.e. the
spotlight will now follow the Main Camera. If we wanted the spotlight to follow a
different game object we could just drag in a different object (as long as it was of type
Transform of course).
- Play the game. If you watch the Scene View you should see the spotlight following the
Main Camera around. You may want to change the position of the spotlight to improve
the effect.
6. Accessing Components
As a game object can have multiple scripts (or other components) attached, it is often
necessary to access other component’s functions or variables. Unity allows this via the
GetComponent() function.
We’re now going to add another script to our spotlight which will make it look at Cube1
whenever the jump button (spacebar by default) is pressed.
Let’s think about this first, what do we want to do:
1. Detect when the jump button has been pressed.
2. When jump has been pressed make the spotlight look at Cube1. How do we do this?
Well, the Follow script contains a variable “target” whose value determines which game
object the spotlight should look at. We need to set a new value for this parameter. We
could hardcode the value for the cube (see the section ‘Doing it with code’ later), however
we know that exposing the variable and assigning this via the GUI is a better way of doing
this.
- Create a new Javascript and name it Switch. Add the following code to Switch.js:
var switchToTarget : Transform;
function Update () {
if (Input.GetButtonDown("Jump"))
GetComponent(Follow).target = switchToTarget;
}
Notice in particular how Follow is the parameter to GetComponent(), this returns a
reference to the Follow script which we can then use to access its “target” variable.
- Add the Switch script to the spotlight and assign Cube1 to the switchToTarget
parameter in the Inspector View.
- Run the game. Move around and verify that the spotlight follows you as usual, then hit
the spacebar and the spotlight should focus on the Cube1.
Doing it with code
Earlier in the tutorial we mentioned that it would be possible to assign the variables via
code (as opposed to the Unity GUI), let’s take a look at how you would do that.
5
6. Remember this is only for comparison, assigning
variables via the GUI is the recommended approach.
The problem we were interested in earlier was how
do we tell the spotlight to look at Cube1 when the
jump button was pressed. Our solution was to
expose a variable in the Switch script which we could
then assign by dropping Cube1 onto it from the Unity
GUI. There are two main ways to do this in code:
1. Use the name of the game object.
2. Use the tag of the game object.
1. Game object name
A game object’s name can be seen in the Hierarchy View. To use this name with code we
use it as a parameter in the GameObject.Find() function. So if we want the jump button to
switch the spotlight from Main Camera to Cube1, the code is as follows:
function Update () {
if (Input.GetButtonDown("Jump"))
{
var newTarget = GameObject.Find("Cube").transform;
GetComponent(Follow).target = newTarget;
}
}
Notice how no variable is exposed as we name it directly in code. Check the API for more
options using Find().
2. Game object tag
A game object’s tag is a string which can be used to identify a component. To see the
built-in tags click on the Tag button in the Inspector View, notice you can also create your
own. The function for finding a component with a specific tag is GameObject.FindWithTag
() and takes a string as a parameter. Our complete code to do this is:
function Update () {
if (Input.GetButtonDown("Jump"))
{
var newTarget = GameObject.FindWithTag("Cube").transform;
GetComponent(Follow).target = newTarget;
}
}
6
7. 7. Instantiate
It is often desirable to create objects during run-time (as the game is being played). To do
this, we use the Instantiate function.
Let’s show how this works by instantiating (creating) a new game object every time the
user presses the fire button (either the left mouse button or left ctrl on the keyboard by
default).
So what do we want to do? We want the user to move around as usual, and when they hit
the fire button, instantiate a new object. A few things to think about:
1. Which object do we instantiate?
2. Where do we instantiate it?
Regarding which object to instantiate, the best way of solving this is to expose a variable.
This means we can state which object to instantiate by using drag and drop to assign a
game object to this variable.
As for where to instantiate it, for now we’ll just create the new game object wherever the
user (Main Camera) is currently located whenever the fire button is pressed.
The Instantiate function takes three parameters; (1) the object we want to create, (2) the
3D position of the object and (3) the rotation of the object.
The complete code to do this is as follows (Create.js):
var newObject : Transform;
function Update () {
if (Input.GetButtonDown("Fire1")) {
Instantiate(newObject, transform.position, transform.rotation);
}
}
Don’t forget that transform.position and transform.rotation are the position and rotation of
the transform that the script is attached to, in our case this will be the Main Camera.
However, when an object is instantiated, it is usual for that object to be a prefab. We’ll
now turn the Cube1 game object into a prefab.
- Firstly, let’s create an empty prefab. Select Assets->Create->Prefab. Rename this
prefab to Cube.
- Drag the Cube1 game object from the Hierarchy View onto the Cube prefab in the
Project view. Notice the prefab icon changes.
Now we can create our Javascript code.
- Create a new Javascript and name it Create. Insert the above code.
- Attach this script to the Main Camera and assign the Cube prefab to the newObject
variable of Main Camera.
- Play the game and move around as usual. Each time the fire button is clicked (LMB or
left ctrl) and you should notice a new cube appearing.
7
8. 8. Debugging
Debugging is the skill of finding and fixing human errors in your code (ok let’s call them
mistakes!). Unity provides help via the Debug class, we’ll now look at the Debug.Log()
function.
Log
The Log() function allows the user to send a message to the Unity Console. Reasons for
doing this might include:
1. To prove that a certain part of the code is being reached during run-time.
2. To report the status of a variable.
We’ll now use the Log() function to send a message to the Unity Console when the user
clicks the fire button.
- Open the Create script and add the following line after the ‘Instantiate’ code inside the
‘if’ block:
Debug.Log("Cube created");
- Run the game and click the fire button, you should see a line appear at the bottom of
the Unity GUI saying “Cube created”, you can click on this to examine the Unity
Console.
Watch
Another useful feature for debugging is exposing a private variable. This makes the
variable visible in the Inspector View when the Debug mode is selected, but it cannot be
edited.
To demonstrate this, we’ll expose a private variable to count the number of cubes that we
instantiate.
- Open the Create script again and add two lines:
(1) Add a private variable called cubeCount
(2) Increment this variable whenever a cube is instantiated.
The complete code is a follows (Create.js):
var newObject : Transform;
private var cubeCount = 0;
function Update () {
if (Input.GetButtonDown("Fire1")) {
Instantiate(newObject, transform.position, transform.rotation);
Debug.Log("Cube created");
cubeCount++;
}
}
8
9. - Run the game and click the fire button to create some cubes. Notice in the Inspector
View how the cubeCount variable is incremented whenever a new cube is instantiated.
Notice also how the number appears greyed out, this denotes that it’s a read-only
variable (cannot be edited).
9. Common script types
Whenever a new Javascript is created, by default it contains an Update() function. This
section will discuss other common options available, simply replace the name of the
Update() function with one from the list below.
FixedUpdate()
Code placed inside this function is executed at regular intervals (a fixed framerate). It is
common to use this function type when applying forces to a Rigidbody.
// Apply a upwards force to the rigid body every frame
function FixedUpdate () {
rigidbody.AddForce (Vector3.up);
}
Awake()
Code inside here is called when the script is initialized.
Start()
This is called before any Update() function, but after Awake(). The difference between the
Start () and Awake() functions is that the Start() function is only called if the script is
enabled (if its checkbox is enabled in the Inspector View).
OnCollisionEnter()
Code inside here is executed when the game object the script belongs to collides with
another game object.
OnMouseDown()
Code inside here is executed when the mouse hovers over a game object which contains
a GUIElement or a Collider.
// Loads the level named "SomeLevel" as a response
// to the user clicking on the object
function OnMouseDown () {
Application.LoadLevel ("SomeLevel");
}
9
10. OnMouseOver()
Code inside here is executed when the mouse hovers over a game object which contains
a GUIElement or a Collider.
// Fades the red component of the material to zero
// while the mouse is over the mesh
function OnMouseOver () {
renderer.material.color.r -= 0.1 * Time.deltaTime;
}
Check the Unity API for more information on all of these functions.
Summary
This tutorial has introduced the essential scripting concepts in Unity. You
should now read other Unity tutorials or try experimenting yourself!
10