Reader small image

You're reading from  Unity for Architectural Visualization

Product typeBook
Published inSep 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781783559060
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Stefan Boeykens
Stefan Boeykens
author image
Stefan Boeykens

Stefan Boeykens is a Belgian architect-engineer. Starting out as a professional architect in several offices, he returned to KU Leuven in 2000, at the Department of Architecture, for teaching and research, completing his PhD on Building Information Modelling in 2007. Stefan is an experienced researcher with a variety of IT skills. Aside from teaching BIM, he is mainly working as senior Innovation and BIM manager for the Belgian D-Studio, focusing on BIM middleware and consultancy. He is a frequent speaker at BIM-related events and is actively involved in BIM standardization groups, including CEN/TC 442 (Europe) and Belgian Technical Committees. He is father of three boys and enjoys musical composition, reading, cycling and life-long-learning.
Read more about Stefan Boeykens

Right arrow

Chapter 7. Full Control with Scripting

Architects often express that they are visual artists and not programmers. While you can get reasonably far without resorting to scripting, it's almost impossible to finish a project that way. This chapter presents a few easy and reusable scripts that can be applied in most projects. This chapter is enough to get you started. We advise you to type all examples from scratch. It'll take a bit longer and you may encounter errors. It is easier to elaborate something you wrote and understand, than it is to extend somebody else's code.

In this chapter, we will discuss:

  • Scripting crash course

  • Triggering doors and elevators

  • Basic heads-up-display with a custom GUI to toggle objects or display info

  • Switching between cameras and materials

  • Further interactions: resetting the player, loading other scenes/levels

Scripting crash course


Right now, you already used scripts. They are at the heart of Unity. To add behaviors to objects, Unity uses components. If you need lighting behavior, add a Light component. If you need physics behavior, add a RigidBody component. If you need custom behavior, add a Script component.

A script has particular entry points, which define the flow of execution. Some functions are automatically called when the game runs, others every time the display is refreshed, possibly several hundred times per second. You enter the code into one of these functions or call custom functions from these entry points. In the background, scripts are compiled and bundled into your final application, so they run as fast as built-in functions and behaviors.

Internally, Unity uses the Mono framework, an Open Source implementation of the .NET framework, which was designed and developed by Microsoft as a modern and extensible framework. It works independently from the high level programming code...

Triggering doors and elevators


We will now write a simple script that is directly applicable in our example project and extend it afterwards to be more generic and reusable, using parameters.

Doors and elevators are typical interactive elements in buildings. Most buildings have no other moving parts. To rotate a door manually or to use scripting is not that different. However, there are a few tricks to get it correct. These are as follows:

  1. Create a plane GameObject, positioned in the origin. Add a simple Cube, and name it DoorLeaf. Set its position to X=1, Y=1.5, Z=0 and scale to X=2, Y=3, Z=0.1. This ensures that the lower side corner of the door leaf is sitting in the center or our scene.

  2. Load the local documentation from the menu by navigating to Help | Scripting Reference, which opens your default browser on the starting page of the locally installed Unity documentation, which is also accessible offline. On the first page there is a small menu to choose the language of all examples (JavaScript...

Basic heads-up-display with a custom GUI


When we explained the use of GUIText and GUITexture components in Chapter 4, Promenade Architecturale, they were static. This is fine for a fixed logo, but not when you need dynamic information. You can script these components, but they are not the most efficient ones to use. This is shown in the following code:

public Texture2D someTexture;
...
guiText.text = "Hello";
guiTexture.texture = someTexture;

An alternative is the use of the Unity Graphical User Interface (GUI) classes. To display a GUI inside a script in Unity, use the OnGUI() event. This runs independently of the regular Update() cycle. Inside this event, you can display buttons, text labels, sliders, panels, scroll areas, textures, and toggle switches.

We illustrate this with a simple GUI script that displays the name of the trigger we enter, as shown in the following screenshot, which also displays some feedback in the console.

The following steps will show how to set up a simple scene...

Switching between cameras


While previous examples always used a single camera, apart from the mini-map, you can dynamically change cameras using scripts. You could modify their Depth parameters, so another camera is drawn above the others, but you could also toggle their state. In a more elaborate setup, you could switch between different cameras, for example from first person to third person perspective or to a dedicated Point-of-View (POV) camera to display a particular viewpoint. It is also a way to toggle between user-driven navigation and a pre-animated camera. The following steps show how to perform this:

  1. Prepare your scene with a few camera objects created and positioned in different places. Ensure that only one camera has an active Audio Listener component, to avoid warnings in the console log.

  2. Create a new C# script and name it switchCamera. Add a public variable, cameraList, to contain a list of available cameras, using an array. An index variable is used to keep track of which camera...

Switching between materials


An interesting interactive option you can provide to clients is choosing between different material finishes. A good example of such a system can be found in Autodesk Showcase at http://www.autodesk.com/products/showcase/overview, which displays a popup list of material thumbnails in a very realistic real-time view of a design.

We follow a similar approach as the camera switcher, by setting up a list of alternative textures and using the OnGUI() method to display a button to switch between alternative materials. It is important to prepare the list of textures on beforehand. This is shown in the following code:

using UnityEngine;
using System.Collections;
public class switchMaterials : MonoBehaviour {
  public Material[] materialList;
  public GameObject target;
  private int index = 0;
  void OnGUI(){
    if (GUI.Button(new Rect(5,5,100,24), "Next Material")){
      index = (index + 1) % materialList.Length;
        target.renderer.material = materialList[index...

Further interactions


We finish this chapter with some more useful techniques.

Resetting the player

What if, at one point, the user reaches the edge of the terrain or world you created and falls off? Instead of expecting the user to quit and restart, you should solve the problem elegantly. We place a large, invisible plane underneath our world, as a trigger to reset the player.

  1. Add a Plane GameObject and set its Mesh Collider to Is Trigger. Make it large enough to extend to all sides of the scene and move it down underneath all other objects, as in the setup in the next screenshot.

  2. Disable its Mesh Renderer, to make it invisible.

  3. Create a new C# script called resetPlayer and add the following code. It takes three private variables: one for the player's position (pos), one for its rotation (rot), and then the actual reference to the player (thePlayer). This is shown in the following code:

    using UnityEngine;
    using System.Collections;
    public class resetPlayer : MonoBehaviour {
      private Vector3 pos...

Some additional Asset Store tips


It might feel strange to talk about "Scripting without scripting," but there are a few systems that help you generate scripts without having to actually write code yourself.

Summary


Scripting is a necessary evil when you need to go beyond the included assets installed with Unity. It might be beneficial to look around the Asset Store to add other tools and scripts to your arsenal, but a decent understanding of scripts is a valuable competence to gain in the long run.

Always strive for short, simple, understandable, and reusable scripts. If you need two unrelated behaviors, they might be better off being split into two scripts. To make scripts reusable for different contexts, give them a rather generic name. RotateObject is more versatile than RotateDoor. If variables need to be adjusted, provide them as public variables, so they become parameters of the scripts. Reusable scripts never need to be edited during usage, but mainly tweaked by their parameters.

Add easing and tweening to improve smoothness and to obtain a visual, modern animation style. If you are pressed in time, you might cut some corners here, but they do provide an overall professional feel to your...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity for Architectural Visualization
Published in: Sep 2013Publisher: PacktISBN-13: 9781783559060
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Stefan Boeykens

Stefan Boeykens is a Belgian architect-engineer. Starting out as a professional architect in several offices, he returned to KU Leuven in 2000, at the Department of Architecture, for teaching and research, completing his PhD on Building Information Modelling in 2007. Stefan is an experienced researcher with a variety of IT skills. Aside from teaching BIM, he is mainly working as senior Innovation and BIM manager for the Belgian D-Studio, focusing on BIM middleware and consultancy. He is a frequent speaker at BIM-related events and is actively involved in BIM standardization groups, including CEN/TC 442 (Europe) and Belgian Technical Committees. He is father of three boys and enjoys musical composition, reading, cycling and life-long-learning.
Read more about Stefan Boeykens