We need to create two prefabs. The names aren't too important because we'll be using tags in our code. The tag names are important, which are GoodOrb
and BadOrb
.
GoodOrb
and BadOrb.
GoodOrb.
BadOrb.
We now have the ability to increase our Score or lose Lives
All it takes to win is for the value in the variable score
to be 2.
To increase score
, Player will collide with a GoodOrb which increases score
by 1, and GoodOrb will disappear from the Scene.
An analysis of the code we saw in the preceding code screenshot is as follows:
Line 38: void OnTriggerEnter(Collider other)
OnTriggerEnter()
methodother
now stores a reference to the Collider that Player ran intoLine 40: if(other.gameObject.tag == "GoodOr
b")
other
Collider is attached to has a tag named GoodOrb
Line 42: gameDataRef.score +=
1;C
score
is increased by 1Line 43: Destroy(other.gameObjec
t);
Destroy()
method is removing GoodOrb from the SceneAll it takes to lose is for the value in the variable playerLives
to be 0.
To decrease playerLives
, Player will collide with a BadOrb. The playerLives
variable will decrease by 1, and the BadOrb will disappear from the Scene.
An analysis of the code we saw in the preceding code screenshot is as follows:
This code is similar to OnTriggerEnter()
. However, since we are using OnCollisionEnter()
, we have to use a Collider that does not have Is Trigger checked. The child object of Player is the Sphere which has a Box Collider. When this Collider crashes into a BadOrb, Player will lose a life.
Line 47: void OnCollisionEnter(Collision collidedWith)
OnCollisionEnter()
collidedWith
variable now stores a reference to the other
Collider that Player ran intocollidedWith
is a Collision
type, not a ColliderCollisions
, as opposed to triggers, require using the Collision
classLine 49: if(collidedWith.gameObject.tag == "BadOrb")
BadOrb
Line 51: gameDataRef.playerLives -= 1;
playerLives
is decreased by 1Line 52: Destroy(collidedWith.gameObject);
Destroy()
method removes BadOrb from the SceneThere is a way to increase Player Lives. By shooting a BadOrb, the variable playerLives
will be increased by 1. It also turns a BadOrb into a GoodOrb.
18.119.106.237