Tuesday, August 26, 2014

Unity Tutorial: Instantiating a Building on a Lot - JS


Here's a quick guide to how to Instantiate a Prefab to a specific position and rotation. The example I'll be using is calling a pre-made building (prefab) onto a lot, but the scripting operation can be used for any location-specific Instantiation.


______________________________________________________________

Object and Target

The key to this technique is to have a target-object that will represent the position and rotation you would like your object to take. For the sake of this tutorial, we'll use a Lot. This is a square with the scale dimensions of  40, 1, 40 and given a dirt material.

This is a Cube Game Object flattened in a large square set in a terrain. It is serving as my lot, but you can use anything as your position-base.
Model Street Lot
Now here's the script in Unity's very own JavaScript. This script has been tested and should work if you

  • Assign "lot" to your target Game Object in the scene
    • drag object from Hierarchy into "lot" slot in the Inspector
  • Store your Building prefab in your Resources folder
    • drag building object into Project to save it as a Prefab
  • set "resourceLoadString" as the path to your prefab in your Resources folder
    • ex: Bakery is in Assets/Resources/Buildings
    • resourceLoadString = "Buildings/Bakery"
______________________________________________________________

The Script

#pragma strict

var building : GameObject;
var lot : GameObject;
var buildHere : GameObject;

var resourceLoadString : String;

var thisPos : Vector3 = new Vector3();
var thisRot : Quaternion = new Quaternion();

function Start () {
//sets your building's position to the same coordinates as your lot
thisPos = lot.transform.position;
//this raises your building up a bit above the lot so you don't get z-fighting flickers
thisPos[1] = thisPos[1] + 0.45f;

thisRot = lot.transform.rotation;

//this string should be your path through your Resources folder
//if you want the building to build on some kind of condition, use these lines inside your condition {}
resourceLoadString = "Buildings/Bakery";
buildHere = Instantiate(Resources.Load(resourceLoadString), thisPos, thisRot) as GameObject;
}

______________________________________________________________



 

Visual Guides



______________________________________________________________


See It In Action

Apply the script to one of the GameObjects in the scene. I use the Main Camera because it's not going anywhere.

This same premise can be applied to creating any prefab at a GameObject determined position and/or rotation. ^_^
______________________________________________________________

All blog posts by UnityGirl are inspired by my work with Brunelleschi: Age of Architects on the Aesop Games team. Check out our Crowd Funding page(s)!

No comments:

Post a Comment