Game Development Reference
In-Depth Information
block of code that they are declared in. Keeping track of what parts of a script
(or project) have access to what information is important to understanding
what values are floating around, and to keeping the script tidy.
This AC_ToolFunctionalityScript script is getting quite powerful, but also quite
long and has some inefficiencies when it comes to reading the document.
Perhaps expert scripters are able to construct script flawlessly from the get-go,
but for most of us mere mortals, scripts tend to evolve quite organically and
thus sometimes need a little bit of trimming.
The main trimming for us at this point will entail a few important things. First,
we can strip the Debug functions. They were a valuable instrument when trying
to understand concepts like raycasting, but for now they are just visual clutter. If
we need them later to figure out a problem, it's easy to add them back.
Second, we can look at certain objects or components that we are
accessing again and again within a function and create a local variable
(a variable that is only available within the function in which they were
declared) to house the object, and just call on that variable. So for instance,
if you look at the code right now we are accessing hit.collider.gameObject
a lot. In nearly every block of code this particular chunk of script appears.
Right after we cast the ray (which creates the hit), if we declare a variable
that houses the object that the ray hits (which is what hit.collider
.gameObject is), we can save a lot of typing and make the code much
easier to read. So add the following line (surrounding code included):
function Update () {
var hit : RaycastHit;
if (Physics.Raycast (transform.position, transform
.forward, hit, 100)){
var hitObj = hit.collider.gameObject;
if (hitObj.name == “Hallway_PowerPanel_Switch”){
Then, everywhere in the code (except for line that defines hitObj) where hit.
collider.gameObject appears, just swap out hitObj . This can quickly be
done with the search and replace function of the editor.
Similarly, in the if(pistolActive) block of code, we create a local variable for a
LookRotation (the rotation of an object we instantiate). Unfortunately, this
means we tie that variable into that block of code, and it would be nice to
access it throughout the function. And in fact, we want access to it as we
work toward setting up the EMP Mines functionality. However, with it nested
down inside the pistolActive block of code, it can be tough to track it down
later when we're bug squashing, and really annoying for someone else who
inherits the script and has to try and figure out what's going on. For these
reasons, it makes sense to lift this particular variable declaration up to the top
of the function as well. So . . .
Search WWH ::




Custom Search