Game Development Reference
In-Depth Information
By setting isKinematic property of rigidbody to true , the script tells the physics simulator that
no external force can alter the position or rotation of the door. Nevertheless, the door must
still be able to collide and block other objects. The script starts by calling Lock() function,
which in turn sets rigidbody.isKinematic value to true . Anyone tries to unlock the door must
provide a collection of strings (keys) that he has. If one of these keys matches unlockKey ,
the door is unlocked. Notice that we use ICollection generic list, which is the most generic
type of collections available. As a result, the function can be called using List<string> or
string[] without problems. The value of rigidbody.isKinematic determines whether the door is
locked or not. If the door is already unlocked, the value is false . If the door has not yet been
unlocked, every key in the provided keys collection is compared with unlockKey . If a match
is found, the door is unlocked by resetting rigidbody.isKinematic back to false . Before that,
the script informs other scripts about unlock by sending OnUnlock message. However, if
none of the provided keys matches unlockKey , the function returns without unlocking the
door and sends OnUnlockFail .
All we have to do now is to attach the script to the physics door we've made and set its
unlockKey to “door1”, so that it matches key value of the collectable key. The final step is
to initialize unlock attempt. One of the options is to try to unlock the door when the player
character touches it. To implement this option, we have to write a script that handles colli-
sion between player character and the door and eventually try to unlock the door. This
script is TouchUnlocker shown in Listing 65.
1. using UnityEngine;
2. using System.Collections; 3.
4. public class TouchUnlocker : MonoBehaviour { 5.
6.
void Start () { 7.
8.
}
9.
10.
void Update () { 11.
12.
}
13.
14.
//Send unlock message to colliding object
15.
void OnCollisionEnter(Collision col){
16.
//Get the inventory box
17.
InventoryBox box = GetComponent<InventoryBox>();
Search WWH ::




Custom Search