Game Development Reference
In-Depth Information
There are several ways to accomplish the communication, but for this example, you will be using
SendMessage() . It sends a message to (or calls) a function on another script and can take an
argument to send on as well.
For the function it calls, you will make a user-defined function that will change the value of a new flag
in the UpdateTests script.
1.
In the script editor, switch to the UpdateTests script.
2.
Create a new variable beneath the existing variable declarations:
public bool stopIt = false; // flag to stop translate after object is underway
Below the Update function, just above the closing curly bracket for the class,
add the following:
3.
void ToggleStopIt (bool newState) {
stopIt = newState; // update the variable's state
}
Function naming conventions are similar to variable naming conventions except that, in Unity, you
should always capitalize the first character of the name. As with variable names, you cannot use
a number or most special characters for its first character, and you cannot have any spaces in
the name.
Add the new variable as another condition to the Translate conditional:
4.
// Move the object forward along its z axis 1 unit/second.
if (allClear && !stopIt) {
transform.Translate(-Vector3.right * Time.deltaTime * speed);
}
The && means “and,” so each condition must be true for the entire expression to evaluate as true.
The exclamation point negates the value of the variable it precedes. In this conditional, allClear
must be true and stopIt must be false (which makes !stopIt true). Conditionals can also use the
or operator, || . The statements in between the && and || are always evaluated first.
5.
Save the script.
6.
Return to the ColliderTests script.
7. Search for SendMessage in the Scripting Reference.
The description says “Calls the method named methodName on every MonoBehaviour in this game
object.” Method is another name for function , and a MonoBehaviour is a script. (Remember the
default name of newly created scripts.) Both of the scripts are on the bench, so you won't have to
specify a different gameObject than the one the script is on.
 
Search WWH ::




Custom Search