Game Advanced Prototype 4
GCC Academy
Hi
I'm Youngho Lee, a shooting game development course instructor
In this chapter
We will go over Object collision processing
enemy auto generation
and DestroyZone for memory management
Also, learn how to set requirements
for processing collision in Unity
and between object groups
You will learn how to manage memory using this
we will create a manager object
to automatically generate enemies
Object collision processing
The 4th prototype
Let's learn about object collision processing
You need two conditions for object collision processing
The collision between objects in Unity,
when such objects are colliding each other
two conditions are required
First, look closely
let's say in a certain space
there is this object
Then, in this space
Let's make it 3d
Let's also say this player moves to the right
in this space, to the right in our perspective of looking at the screen
This side is blocked by a wall
So, this player runs in this direction
Then, what would happen to this player?
Will it go through the wall? or collide and bounce off?
The player will collide and bounce off
with bloody nose of course, generally
But in certain cases
the player could pass through the wall
So, what about the case where this object hits the wall
and can't pass through?
The first condition comes into play here
If the player is materialized like this
When it runs this way, it will definitely hit the wall and bounce off
But what if it's a ghost?
What would it be like if it's was ghost?
If it runs towards this wall, will it hit the wall and bounce off?
Nope, it will pass through and move out of this space
What kind of difference is there
for the player to be blocked by the wall
and for the ghost to be able to pass through?
That's where the first condition comes into play
The first condition is
this player has a body
that is made of bones and flesh
But how about ghosts? They do not have a body
Therefore, first, body, we call this
Collider in a physics engine
The Collider
We call this Collider in English
Collider
Then, what is the second condition that is required?
When we apply this to the player object
if the player runs to the right
left
up, or down, then what happens?
All these walls, walls that form this cube
it can collide with these walls
But then this wall on the left
and then this wall on the right
can these walls collide?
In the space this player is in
can the ceiling and the floor collide?
We are not considering collapse
In a normal case, it can't collide
Then, there's one thing we want to know here
How can the player here
collide with the floor
ceiling, or left wall
but these walls can't collide with each other?
The distinction here is
walls cannot move
but the player can move
Therefore
it should be able to move around
When other things cannot move
This object, at least one object should be able to move
That moving object can collide
even with fixed object
Therefore, we need the object to be able to move
and we call it Rigidbody in Unity
These are all related to components
Each game object needs to have a collider
as the first condition in order to be able to collide
The second condition, between objects
there should be
at least one of what?
One should be able to move at least
And that's the Rigidbody
With this concept, let's work on object collision processing
Now in Unity
Let's go to unity editor
Let's look at an Enemy first
You can see a Box Collider attached
In the Inspector window
you can see the first condition
collider is already attached
but the Rigidbody is missing among components
Let's look at the Player, too
So, Player also has
Box Collider by default
However, there isn't any Rigidbody here as well
Therefore, if we wanted to have this enemy
collide with Player
when we press play button, would they collide?
No, they wouldn't
Why? because the second condition, Rigidbody is missing
Therefore, let's attach Rigidbody to this Enemy
go to Add Component
If you search Rigidbody here
Rigidbody, add into the component like this
Then you can see that the Rigidbody component is attached here
Now this object can collide
By default here, among properties
things like Use Gravity are enabled
So if we turn off the script for now
if we drag it down
and movement related components are disabled
Unchecking this box means it will be disabled
So the script here is not working
If we set it like this, basic physics will be applied
The physics function for movement will take effect
Since Rigidbody will be under effect of gravity, it will fall
Now let's see
I will move this so they would align a bit
Let's see what happens when this object falls
Let's press the play button
when we play it, it approaches the object
and bounce off the object
n the Unity engine, there is content
that automatically applies physics like this
From collision to physics phenomenon to occur
For this to be possible, the first condition
a Box Collider, or collider must be attached
Both Player and Enemy need a collider attached
And then, one of the objects
must have what attached?
Rigidbody
Rigidbody must be attached as proof that it is a moving object
This allows us to create the action
where objects physically collide
So, in our case, we check the Enemy again and open it
and for Enemy and Player to be able to collide
they need Rigidbody
However, in Enemy Script
it is moving Enemy
We'll turn off the effects applied
by Use Gravity
The physics part here
we will have it turned off
Now then, we'll process the event
that occurs when two objects collide
In other words, we will implement
how to handle the situation when two objects collide
Now, in terms of collision, here we have the Enemy
Objects are to collide with each other
and we have Player here
and then we have Bullet
We've created these three objects
Then, shall we take a look at how they collide
with each other?
First, can the Player and Enemy collide?
Can these two objects collide with each other, or not?
They can, ding!
Then can Enemy and Bullet
collide with each other, or not?
They must be able to
Only then, when Player and Enemy collide
we can make Player die or
Enemy die
and also to hit Enemy with Bullets
That's the logic behind this
But Player and Bullet
should they able to collide with each other?
Of course, in reality, it would be natural for them to collide
Also, depending on the design of the game, it’s possible to make them collide or not collide
But in our game, we won't have situations
where Player dying when hit by
its own Bullet
Therefore, we will forbid the collision between the two
Then, we have a common denominator here
When they collide, in the end, both the Enemy
and either the Player or Bullet will be destroyed
we will have them destroyed
Then, ideally, each of them should
handle this on their own, but
In reality, doesn't matter which
if one object handles the collision
it will apply to the other objects as well
Then, the common denominator
would be the Enemy part here
So, let's add the logic in the Enemy part
to remove both the object
that collided with it and itself
So, let's go to the script of Enemy
Let's go to the Enemy script
In the visual studio
come to Enemy.cs file
What we want to do here is
When Enemy here collide with other object
Let's add the logic to say, I want both you and me to die when we collide
then it means to destroy both the object
that collided with this object and itself
So, how do we handle this part then?
the lifecycle function for spawning is Start
and the function for living is Update
Then for dying? It's OnDestroy
Why do we have the On there?
The 'On' prefix is a convention in Unity used for functions
that are triggered by events
Similarly, we can't know
when this object will collide
with another object
That's why we use prefixes like On for such functions
So, when we look at OnCollisionEnter
there are Enter, Exit
and Stay
When making a 2D game, you just need to add 2D at the end
Now, OnCollisionEnter refers to
the exact moment when a collision happens
Exit refers to the moment when the collision happens
Stay refers to the state where the objects remain in collision
So, when an object collides with another
you can use OnCollisionEnter right at that moment
By doing this, you'll have void OnCollisionEnter
I will set this Collision
the name of this variable parameter
as other for the Collision
Then, it will become the name of the object that collided with me
So say, You will be destroyed, I will be destroyed
Let's implement this part
and add it here
So, for You will be destroyed
we can use the Destroy function
Instead of just destroying other
if you look here, this Collision object comes in
What I want to destroy is
the other object's game object
So, if you look at other, there is gameObject
why? you are not trying to destroy just parts of an object
then what do you want to destroy?
We need to destroy the game object itself, including everything
in order to destroy our object
So if we set up like this, we achieve, you will be destroyed
and then for I will be destroyed
If we use just gameObject without other
then it becomes I
There is gameObject that
this Enemy.cs component
we destroy it by using Destroy(gameObject)
Shall we check what happens when colliding with other objects?
In Unity, press play, we can see both objects get destroyed
When it collides with Player, it gets destroyed
Bang, bang, bang! When we fire Bullets, it can also destroy like this
So, we can see how processing of the collision
between two objects are like
Now let's learn about
enemy auto generation
Right now we are using simply one enemy
like this
But the goal of the game wouldn't be
to destroy only this one enemy
For multiple enemies to spawn
let's create multiple enemies
We already know the theoretical concept here
Bullets are
created in Bullet Factory
Then, where are Enemies created?
We can create them from an enemy factory
If there is a drop item in the world, for example
Where should they be created?
Also, we can create them from an item factory
It's the same method for everything
The only difference is the name
you can create them all using the same method
So, we need the Enemy factory for Enemies
Remember how to make a factory?
We called this factory prefabs
A prefab is called a prefab when
a gameObject becomes an asset file
Then we can make this gameObject
the Enemy gameObject into a file
drag and drop it
into the project window that manages files
if you drag and drop
it will be added into this window like this
Then we don't need the Enemy here
We will have Enemies created
one by one whenever we need one
Let's erase an Enemy here
Then, who will create this Enemy when it's needed?
Bullets are made by a Player
Whenever we press fire button
We need someone creating Enemies for us
So, the object responsible for that role
We will call it the Enemy Manager
So, in Hierarchy window
press plus button and Create Empty
Enemy Manager is as the name suggests
we use it just for management purposes
We don't need it to be visible
Just like God
So by pressing Create Empty button
we can make it invisible
and name it EnemyManager
For Transform, Z value is set to minus 10
press reset button to set them to 0, 0, 0
We'll create it like this and place it at the top
but it won't be easily visible, right?
So, for invisible empty objects like this
if you look on the right side
there's the Inspector window
This part in the Inspector window
If you open it
you can select it as an icon here instead
I'll just choose any icon
something like a diamond shape
As you can see, the diamond icon is assigned here
and we can actually see the diamond icon with our eyes as well
But in a real screen in game
and we can actually see the diamond icon with our eyes as well
So, what you can do is
just select the Gizmo
and you'll see the Gizmo in the game view
if you press this button
We can make the Gizmos, which we previously saw in the Scene view
visible in the Game view as well
Then, when it appears in the Game view
what do we do next?
If we make the Enemy appear here
the Enemy will suddenly
pop up at this location
Little awkward, right?
It would be better if it were created outside the screen
and then came in, making it look more natural
So, to make it leave the screen
I'll place it like this and move it upwards
Now, it's positioned outside the screen
And we can see this by selecting the Main Camera
he area of the Main Camera is
displayed as a white box
You can see this in the preview window here
Right now, the position of the EnemyManager we are creating
is outside the Main Camera's area
Then, we can tell that it's placed outside the screen
Let's handle it so that the Enemy is created outside
and then comes into the screen
Let's create the EnemyManager
and then make a script
to handle the tasks
in the Scripts folder, press plus button for C#
Let's name it EnemyManager
EnemyManager
In the gameObject, place EnemyManager C# script
The name doesn't have to be exactly the same, though
I've named them this way for convenience
just to make it easier to recognize the game object
and the script
Now, let's open the EnemyManager script
if you look, the script names are all cut off right now
Beyond the size
you'll see a scrollbar at the bottom here
in the Unity editor
If you grab the scrollbar and move it all the way to the left
the full names will be displayed correctly
We are adjusting the preview size
Here, we will double-click
on EnemyManager to open it
what we will do in the EnemyManager
is this
Want to create Ememies at regular intervals
This is what we will use EnemyManager for
So, what properties are needed here?
To implement that sentence
what information do we need
to get from the designer?
We'll need a factory that can create enemies
and if you look here
We need to know how long the interval is
The regular interval refers to the spawn time
So, we need to get the spawn time information from the designer
And although it's hidden in this sentence
we also need the elapsed time
To know how long has passed
Since we need these three properties for this reason
Let's declare these three properties
Shall we look at Enemy factory now?
we will use public GameObject enemyFactory
since the spawn time needs to be editable by the designer
making it public will expose it to the outside
Next, let's add float createTime like so
and set 2 seconds for the amount of time
so that Enemies are created every 2 seconds
Next, we need the elapsed time
The name of the elapsed time doesn't need to be exposed to the outside
The designer doesn't have to define it
Why so? It's because time continues to flow
I'll name it currentTime
since it flows according to current time
So, we have declared the three necessary properties like this
Now, our ultimate goal is
to create enemies at regular intervals
Where should this be implemented?
You can Update
From Start or Update
We will have it keep creating
What we ultimately want to
achieve at this point is
Wanting to create an enemy
that is our ultimate goal
The second thing is, we ultimately want to create the enemy
Now we need to ask some questions
Why do we make Enemies so suddenly?
Since the specified time has passed, or since the spawn time has arrived
That's why we want the Enemies to be created
Up to this point, this is something you might
generally consider when coding
However, for those who are not familiar with coding
they might only come up with designs only to this point
However, there is a hidden parts
the logical aspect that is hidden
specific to computer languages
What it is, is this, creating Enemy
then it needs to reach the spawn time
Then lastly, we need one more sentence
to be formed
to complete this entire section
Time needs to flow
It may seem obvious, but this part is
actually very important in programming
It's very common to overlook these things
These conditions need to be met for the time to pass
and for the spawn time to be reached
which completes the three logic of creating enemies
So, the first thing we ultimately want to do is
following this flow, which is once the time passes
and the spawn time is reached, we create the enemy
Now, let's implement the part where time passes
By time passing, we mean the elapsed time
When curretTime flows, it means the time is accumulating
currentTime will flow like this
but we can reduce it like this
This accumulates
but about time, we learned this one thing
What is being used when the Enemy is moving?
deltaTime, what is it about?
The interval between frames
The time it takes to draw a picture on the screen
or this Update here
The time it takes for Update to draw a picture on the screen
I said Update is done once per frame
Therefore, you can think of it as
the time it takes for an Update to be called
Then what is going on?
Time taken for a single update call
Time taken to process a single update call
the interval should be very short
So, how about we continuously accumulate this time?
If we keep accumulating 0.03 seconds and 0.01 seconds
eventually it will add up to 1 second
So this is what happens
If we keep adding 1/30th of a second
it means we're aiming to match
30 frames per second
So when this is activated 30 times
currentTime will become 1 second
That's the magic we are trying to make happen
And then, the Generation time came means
If we slightly modify this into coding language
it will look like this
If the elapsed time exceeds the generation time
It’s the same content, but we could rephrase the sentence
So we use if for this sentence
the elapsed time, currentTime is bigger than what?
if it's bigger than createTime
If it exceeds, it means it's greater
That is, it's a simple translation
If the elapsed time exceeds
what? the createTime
You can create it like this with a simple translation
What do you want to do at this point?
We want to make the Enemy
To create the object, we can simply produce it at the object factory
What is this? It’s called instantiate
You've used it when creating Bullet object
If we place EnemyFactory here
we can immediately create Enemy
and the gameObjects created here
GameObject enemy
Like this, we can store this instance
into variables to use them
Now, when we place the Factory
Like this, an instance is created
What are we doing here at the end?
We place Enemies
Then, the position of the enemy's transform
enemy and a dot
We're accessing the transform among the properties or functions
transform and a dot
Among your properties, give me your position
To place it means inserting the position value
I will insert the position of the EnemyManager here
Use transform dot position
It's own location goes in
We are not finished with this sentence yet
In this sentence, it happens once every certain amount of time
After creating it once, the currentTime keeps accumulating
so once it exceeds CreateTime
it will keep increasing
and be created continuously without waiting
After creating it once, you would need to wait again
Need to wait, then create it again, wait again, and then create it again
This process should repeat
So, a process to reset the elapsed time is necessary
So, as the final step, you need to reset the elapsed time
If you reset currentTime to 0
the timer will be reset to 0 and start counting up again
Once saved like this, let's go to Unity
When you come here, you’ll see that in Unity
the Enemy Manager is now there
Here, the Create Time is set to 2
I will drag and drop the Enemy from Prefabs
into the Enemy Factory section
EnemyFactory
Shall we press the play button now?
If we let it play
You will be able to notice that a problem has occurred
The reason for this is that we need to look at the console window here
You can see an UnassignedReferenceException here
In the console window, the error message is displayed in red
It says 'Unassigned', meaning it hasn't been assigned
And then if you look here
The target variable of the Enemy has not been assigned any value
that is what we have here
So, if you double-click on it
to see where the problem is
by clicking on it in the console window
it will show that this part is not assigned
meaning it has no value
It clearly shows here that the target value is missing
But we did insert target right there?
The target value
You can think of it this way
But there is no Enemy here
If you go to the Enemy and check
does the target have a value? No, it doesn't
Ah, I see. So, I need to assign the player again
You can think of it like that
Shall we try? I tried to put the Player here
but does it go in or not?
It doesn't go in and the reason is that
these are instances, which are
in memory right now
They disappear when you turn off the computer, in short
Only the things that are here get stored into the hard drive
So, the physical space is different
That's why you can't put it here
So, how do you assign a value to the target?
One could ask
So, you need to find it dynamically and assign the value
By dynamic, it is when you press the play button
the moment the game is running, the runtime moment
we call it dynamic
So, instead of directly assigning the target here
what should we do
right before it starts living just before it is created?
We should let it find the target
Who's the target then?
It would be Player in this world
If you have pressed the play button
Then Enemy will spawn
Since the EnemyManager will create the Enemy
Then, at that moment, is the Player there in that space or not?
Yes, because both are alive in the same space at that point
Therefore, you can find it here
So, this part where you need to find the target
can be placed like this
Currently, does the target have a value? No, it doesn't
So, since it's an empty value, null is entered here
Let's find a value and assign it to this null part
How do we find it? Look closely
Which property or function of GameObject dot?
we use a function called Find
It says string name right there
It is the name of the GameObject
What was the name? Player
We find Player
Then what role does Find play?
It will find and pass
the GameObject named Player
if it exists in the world
as what type?
Since it's a GameObject, it will pass the GameObject
But here, if it's found, we should pass the GameObject
but what is its data type? It's Transform
It won't work because we are trying to put a GameObject into a Transform
So, let's first process it before proceeding
Let's input player in lowercase for the GameObject
Then, there should be no issue at all, right?
Then, what if the Player dies?
when colliding with an Enemy?
When there is a Player
when it is what? put a value into the target
or it shouldn't have any values
put a value into the target
Therefore, if Player is there
minus null, you could do this
or put it in like this
Here, you can put a value into the target
player dot transform
we can insert transform into player
Then there wouldn't be any problems
But then, what if Player dies?
Then what would happen?
There won't be any values inside the target
So, we need to calculate this probability
and at this point we need to handle one more thing
By adding to the probability, there is a target
Right? it's there
And if the probability falls within 30%
then let's move toward the target direction
This is how it works, right? You understand?
So, the project plan needs to be
a bit more detailed
How do we know there is a target?
Just like before, we have the target, and then we can add ampersand
You can insert the relational operator like this
So, if there is a target and
the percent falls within 30%
then where does it go if there is no target?
else, it just goes down
Let's go and check it like this
Now when we press the play button
It comes over and then goes down
You can see that an enemy comes every 2 seconds
You can confirm that it continues to appear properly
Shall we increase the probability?
In ours, it's this Player
So we made it to find the target when player is present
Then I will set the probability
as 10 to see what happens
Let's save it and see what we've got
Then it will come to the player unconditionally
Right? Towards the player
You can see that it's working properly
Let's change percent value back to 3 now
and get back to work
if Player ceases to exist
Enemy will, there, it died
From then on, it will continue to move down
Because there's no target
Then, you can see that enemies were
automatically respawning
Like this, there is an EnemyManager
Let's have multiple EnemyManagers
not just one EnemyManager
Let's press Ctrl and D on the keyboard
How? press Ctrl key
and then D at the same time to duplicate
You will see it being duplicated
So, just simply select EnemyManager
Ctrl and D, you will get another one
Place the new guy beside here
Let's do it one more time
Do the same and then this time move it to this side
This will happen with just a click of Ctrl and D
There shall be five spots that enemies will come out when we play it
You can see enemies showing up like this
Some of them moves down
And others move toward the player
This is what we get
But you see that the enemies collide with each other
Let's work with this later
Let's move things a bit
so that it comes with in the border
The main Camera is indicated here like this
Some of enemies were out of the camera because they're all spread out
Let's gather them closer
Like this
They all line up inside the Main Camera area
So we have the main EnemyManager like this
But the CreateTime for all of them are
the same with 2 seconds, having them all come out at the same time
Therefore, let's play around the time here
One would have 2.3 seconds, some others with different time
like 2.6 seconds, let's change little by little
If you play it, this is what happens
Enemies don't just come out all at once
They spawn like this
So, we've created EnemyManager
Here, we still have a problem, so let's take a look
Enemies keep coming out, and I'll keep firing
The problem here is, let me die here
And go to Hierarchy window
You will see Bullets and Enemies piling up like this
I'm not even playing anymore but they are keep
accumulating like this
This way, the memory will keep piling up
Eventually
this Unity editor can turn itself off
because it doesn't have any free memory left
So, we need to address this problem
To fix this, there are several ways to do it
To solve this problem, right here
Let's place an invisible area outside the camera like this
We can have objects
come to this area and collide with each other to make it disappear
or we can count the screen to remove them
we can solve it like so
and another one is
The EnemyManager we made, is automatically
and frequently processing CreateTime
We can have them create randomly
Simply, have these objects
The leftover enemies or bullets, before having these game objects
disappear automatically as we so desire
First, in the EnemyManager
let's implement random spawn
processing mechanism here
If you want to make EnemyManger to spawn randomly
what you want to do is, from this interval to that interval, create object
So you decide certain time
creating some kind of random number
How? from 1 second to 5 seconds
during that interval, create objects one by one
something like this is what we want to make happen
Therefore, let's create minimum time and
Maximum time
For minimum time, put float minTime
I'll have it as 1 second
and then for maximum time, maxTime
I'll have it as 5 seconds
we want to process it so that objects to be created between this interval
Then, our initial createTime is set to 2 seconds right now
what we want to do is that we want this value
to become randomly picked among the times within the interval
then we will add something called
Random dot Range in createTime
Remember when we were getting probability
if we put minTime and maxTime in there like this
it will pick a value out of the interval
and pass it to createTime
Then this createTime will keep
changing within 1 seconds to 5 seconds interval
this createTime will only create objects at the beginning, so
How? we need it when we create the next enemy again
so let's make another line to get
a createTime value randomly
again and again
So, for this createTime
the designer doesn't need to have it set to 2 seconds
Since the value will be set randomly within the interval
let's take out public from there
now, save it and let's check it out
EnemyManger won't be in CreateTime anymore
Now, if you play, from second 1 to 5
we can see that Enemies are spawning randomly
DestryZone and collide detection
Like we talked about earlier
we will make a DestroyZone
when objects get out of the play area
in order to process the game
to destroy objects inside
The theory is simple as this, there is this area
Play area
if you select the Main Camera here, do you see the area?
for objects move out this area
when it touches the border
let's have them destroyed
Let's name this a DestroyZone
So let's press plus button in Hierarchy
Find Cube of 3D Object
and name it DestryZone
In the Transform, click reset to have them 0, 0, 0
I will have this located up here like this
If I place it at the bottom like this
Enemies will collide with this DestroyZone
right away, so
I'd like to make the area outside of the enemy spawn area
Shall we have the X value as
maximum of 30? For the maximum size?
You can reduce it if you want
because the Main Camera area is this big
You can have them smaller size like this
If in the screen you are seeing
Player looks too big
Both enemies and the Player are too big
the Main Camera
we want to have bigger area for the main camera to capture
Then how do we change this?
This camera area, the rectangular area
Select the Main Camera on the right
There is a property called Size
this is set to 5 by default
let's change this value from 5
to 10 just to see what happens?
what happens?
The rectangular area that camera is capturing got bigger
It means, now it covers bigger area in the screen
Since others are inside this area
Let's have this DestroyZone
move out of this Camera area
It's still visible in the game screen
So, let's move it away from the area
So, with the Main Camera
we can see that it is selected out of the area
Therefore, this is the DestroyZone
The ones below are the EnemyManagers
We had them inside the area
If you think the DestroyZone is way too big
for me, it'd be enough with just value of 20
How does it look like then?
It comes inside the Main Camera
But for this one as well, let's make it longer in length
Therefore, that's it for setting Main Camera area
We also need it somewhere else
We need one down here as well
But first, I'll attach a script to this
and then proceed with the task
First, in the Scripts folder, press plus button
to add the C# script
and name it the same as DestroyZone
So now we have the DestroyZone
In this DestroyZone
Drag and drop this DestoryZone
we have it created
now let's proceed to implementing scripts
and see if it works well
This DestroyZone will be used in this way
You guys are in front of a door
There is a door like this
When you try to open the door by turning the door knob
Your hand and the door must touch each other
But unlike doors like this
let's say there is a door like this
The two doors are attached like this
and the question is, what's attached above them?
There is a sensor
so then what happens if I go into this area?
This door automatically opens
it followed
these two doors opens
then I can go through this space
Why so? I haven't even touched anything
Why did this door open now?
And what that is, is that you entered
this sensor area and were detected
So, the second type of collide
This is where area detection, a collision is necessary
So, when we create a game
we can define a virtual area within a certain range
and if another player enters this area
we can make it trigger an attack or similar actions
It's like detecting an event when someone enters the area
If you go to DestroyZone and see
There is this Box Collider on the right side
There, you can see Is Trigger
Please enable this by checking the box
This is Is Trigger
first of all, it has a Collider, the first condition for collision
Among them, it will be used for detecting certain events
This is what it's about
and then, the second condition
what do you also need for collision?
We need a rigid body
We have Enemy but do we have Bullet?
No we don't
of course you would want to add rigid body in Bullet
But for us, we want to process Player and Enemy at the same time
So, we will add Rigidbody in the DestroyZone itself
And for this one, we won't need to enable
physical properties
like bouncing off or pulled by gravity
So, we are going to disable physical movement
We we enable collision event
what kind of event?
Event that triggers
Instead, physical movement of bouncing off for example, will be disabled
For that, you will find something called Is Kinematic
If we enable this option
We can disable physical movement of an object
In DestroyZone, enable Is Trigger
and then, Is Kinematic
In Rigidbody, enable Kinematic
We've enabled two options
Now back in DestroyZone
let's write some scripts
For the event that occurs when objects collide
we used OnCollisionEnter
But in here, we need a trigger event to occur
So, we will be using OnTriggerEnter this time
Just like the previous one, you can also see Exit and Stay
What we want to do is
this, destroy whichever that collided
The zone itself won't be affected because then
it will only be one time use thing
So add in Destroy, write other dot gameOject
Then this function will destroy other objects coming into contact
Let's save and go play the game
if I fire my bullets
in the Scene window
Bullets don't accumulate anymore
You can see them disappear right when colliding with that zone
There, we have made ourselves a DestroyZone
Now, let's not have the zone be up here only
let's duplicate it by pressing Ctrl and D on our keyboard down here
Do you see the zone in the game window?
Let's move it further down so it's not visible
how does it look?
DestroyZone and Enemy will be here in this hierarchy window
If you click play button
Bullets will be destroyed
by the DestroyZone
Enemies that went down will be destroyed at the bottom zone
However, enemies that slip through
They won't be able to collide with destroyZone
Therefore, we need to add more zones
So, select this and then
We will duplicate
another DestroyZone using Ctrl and D key
Let's place this at 0, 0, 0 first
and then from the
Now elongate it along the Y axis
have the X axis as 1 and Y axis as 20
then it still will have some gap
So let's increase the number by 10
It doesn't matter if they overlap
I will place it like this
place it so it just gets out of the screen
and then Ctrl and D
For another duplicate for the opposite side
This is how I placed them
Now, let's play and see
Tada, they are all gone
Why? when collided in the DestroyZone
we coded so that everything in there to be destroyed
But we need to address one problem here
So, in Unity
we can set objects
in groups
and can enable or disable collision between certain groups
We can make such physical process
To do that
We can pick any objects
select gameObject
On the right side, there is layer feature
open the drop down list of the layer
you will have 0 to 5 as default
Let's click Add Layer
Then in the Inspector window
We get Tags and Layers
We can register our layers here
It will act as a group
Here, we add a layer of DestroyZone
Just like so
Let's set up so that objects inside this DestroyZone layer
do not collide with each other
So, we've added DestroyZone layer, right?
If you select again, they are not selected yet
Let's select all of these
Select DestroyZone
And if you go to layer, we have
that DestoryZone layer we've made in the list
select that
These objects are all included in the layer
Now let's make an option
for these objects not to collide with each other
Where do you do that?
Go to Edit menu
we have the project Settings
and if you open it
there is a category called Physics
there, you will see many options on the right side
We then see the collision matrix
Right? In there
The DestoryZone we've created is here
and then where again?
Also here in horizontal axis
So, at which point do they meet?
This overlapping part, exactly this part here
between these objects, what does it mean?
If the box is checked, they can collide
So if you disable it
we do not let them collide with each other
That's what it means
I will disable it
then, the objects inside this layer
What happens? They do not collide
Let's click the play button
Then, the zones don't collide with each other
Player spawns
Even if it fires
Bullets gets destroyed by the zone
Enemies, no matter where Player is
They move towards the walls and collide
colliding with the zone at the bottom
They are all in here
And if you take a look at Hierarchy window
even if they appear, when they gets out of the screen
you can see them destroyed like this
This way, we can stop memories
being wasted piling up
Here, additionally
we need to see what's going on the Enemies
Did you see Enemies colliding each other destroying each other?
They collide with each other and destroyed each other
So, things like enemies colliding and dying
or the player and bullets colliding and dying
needs to be prevented
So, select any objects
add it to a layer
In the layer section
Below DestroyZone layer
register Player
and then Bullet as well?
Also of course, add an Enemy layer in there
Now let's prevent collision between objects within each layers
Just like before, in the Edit menu, go to Project settings
and in the Physics
We also can see the layer we've just added
Enemy and Enemy, should they collide with each other? No
Bullet and Bullet or Player
Do they collide with each other?
There is only one Player
So we don't need to worry about it here
So let's finish setting up and then play again
Enemies never collide with each other
But they collide with the Player and Bullets
Why? the Enemy or the Player
Haven't had been set up with the layers
Now select the Player first
In the layer list, check 7th Player layer
If you choose yes, all the child objects
will also be assigned to the Player layer
and then, if you go to Prefabs folder, there is Bullet
Select Bullet first
In the Inspector window on the right, change the layer into which?
into Bullet
And For Enemy, which layer? To Enemy
If you switch things up like this
officially we are all done
To summarize
To make groups that we want
We add layers
And then we set each object’s layer values like this
Next, for collision checks among objects on each layer
We go to Edit to Project Settings then, Physics
which is called Physics Matrix, and configure the collision settings
for the overlapping sections
That concludes the concept of collisions so far
Let me summarize what we’ve covered in this chapter
As the first topic
we learned about handling object collisions
We explored colliders
and rigidBody as the prerequisites for collisions
and learned how to use event handling functions
to detect those collisions
Secondly, we covered how to automatically spawn enemies
We created an enemy prefab
and added logic through the EnemyManager object
and script to spawn enemies
at set intervals and at random times
Lastly, we learned about the DestroyZone and collision detection
From the accumulation of objects
we learned that it can lead to memory issues
To address this issue, we created a DestroyZone object
and utilized trigger events
to remove any off screen objects
That concludes everything so far and great work
Object Collision Handling Requirements for collision Collider, serving as the physical body of the object Rigidbody, handling the physics aspects
Colliding Between Objects The default collider attached to the Enemy GameObject is a BoxCollider
Add a Rigidbody component to the Enemy GameObject by selecting Rigidbody under the Physics category Uncheck the Use Gravity property to disable gravity
Destroying Colliding Objects The function that detects collisions is OnCollisionEnter() By using OnCollisionEnter(), you can destroy both the object
Automatic Enemy Spawning Creating and Removing Enemy Prefabs Drag, drop Enemy GameObject from Hierarchy window into Prefabs in the project for prefab
Delete the Enemy GameObject in the Hierarchy by selecting it and pressing the Delete key
Creating an EnemyManager GameObject Configure the EnemyManager to spawn enemies at regular intervals, and have them at the EnemyManager’s location
In the Hierarchy window, select plus, Create Empty to rename it, EnemyManager Set the icon gizmo so that it is visible after placing it in an appropriate location in the scene
Create an EnemyManager script in the Scripts folder of the Project window, then assign it to the EnemyManager GameObject in the Hierarchy
Implementing the Enemy-Spawning Script Declare the necessary properties in EnemyManager.cs, then assign the Enemy prefab to the Enemy Factory property
Enemy Spawning Flow, time passes, spawn time arrives, spawns enemy By resetting the elapsed time, we solved the issue of continuously spawning enemies
Duplicate the EnemyManager GameObject and place it appropriately In EnemyManager.cs, add properties for minTime and maxTime, and apply a random time
DestroyZone and Collision Detection Create a Destroy Zone object and script Remove objects that go off-screen to prevent memory waste
To create an object that will detect the area, click the plus button in the hierarchy tool bar,
then select 3D Object, Cube. Rename the cube to DestroyZoneU
Set the Trigger option for event detection Add the necessary Rigidbody component to the object for collision detection
Create a C# script in the Assets Scripts folder in the Project window, then name it DestroyZone
Add the DestroyZone script as a component to the DestroyZoneU object in the Hierarchy In the OnTriggerEnter function, write the code to remove objects
Prevent collision between DestroyZone objects When DestroyZone objects overlap, they collide with each other and get destroyed
To prevent collision between layers, select the Layer drop down menu in the Inspector window, open the Add Layer window, and add a DestroyZone layer
Select all DestroyZone objects in the Hierarchy, then change the layer to DestroyZone from drop down list in the Inspector window
Select Edit, Project settings, open the Project settings window
Select the Physics section, scroll down to the Matrix at the bottom, and uncheck the box where DestroyZone layers overlap to disable collisions
Add three layers under the Layers section: Player, Bullet, and Enemy
Select Edit, Project Settings to open the window of Physics, check Layer Collision Matrix