Learn C# Scripting for Unity 15 Minutes - Part 4 - Foreach Loop, Array, Find Tags
Summary
TLDRIn this Unity tutorial, Raja from Charger Games walks through C# scripting for object manipulation. The video focuses on finding game objects by tag, specifically cubes and spheres, and demonstrates how to destroy or interact with them. The tutorial covers using arrays to store multiple objects, utilizing loops for bulk operations, and implementing actions via input keys. Additionally, Raja explores how to selectively destroy objects by tags and customize interactions, such as color changes upon clicking. This video is a practical guide for game developers looking to enhance their Unity projects with C# scripting.
Takeaways
- 😀 Learn how to find and manipulate game objects in Unity using C# scripting.
- 📦 A 3D cube object is created, positioned, and a material is applied to it.
- 🔍 Game objects can be located by tag using the method `GameObject.FindWithTag` in Unity scripts.
- 🧠 Tags can be added to game objects for easier identification and interaction through scripts.
- 💥 Game objects, like the cube, can be destroyed using the `Destroy()` method after being found by tag.
- 💡 Multiple game objects can be stored in an array and managed together using `FindGameObjectsWithTag`.
- 🔄 The `foreach` loop is used to iterate through arrays of game objects, applying actions such as destruction.
- 🕹 Actions like destroying objects can be triggered by user input, such as pressing the spacebar or specific keys.
- 🎮 A new script can allow the destruction of objects when clicked, filtering based on their tag (e.g., only cubes or spheres).
- 🎨 Scripts can be applied to multiple game objects, enabling different actions depending on the object's tag, like changing color or destruction.
Q & A
What is the purpose of the video tutorial?
-The purpose of the video tutorial is to teach how to script in C# for Unity, specifically focusing on how to search for and manipulate game objects within a Unity scene.
How does the script find a specific game object in the scene?
-The script finds a specific game object by using `GameObject.FindWithTag` and specifying the tag of the game object, like 'cube' or 'sphere'. This allows the script to locate and interact with the object.
Why do you need to use tags for game objects in Unity?
-Tags are used to categorize game objects, making it easier to identify and find multiple objects of the same type, such as all cubes or spheres. This approach is useful when you need to perform actions on a group of objects.
How can you assign a tag to a game object in Unity?
-To assign a tag, select the game object, go to the 'Tag' drop-down menu, and either choose an existing tag or create a new one by clicking on 'Add Tag' and saving it.
What is the benefit of using arrays in the script when finding multiple game objects?
-Arrays are useful for storing multiple game objects with the same tag. This allows the script to reference and manipulate all of them collectively, such as destroying all cubes or spheres in a scene.
How does the script destroy multiple game objects at once?
-The script uses a `for each` loop to iterate through the array of game objects found with a specific tag, such as cubes, and destroys each one sequentially using the `Destroy()` function.
What is the purpose of using the `Input.GetKeyDown` method in the script?
-The `Input.GetKeyDown` method is used to detect key presses. In the tutorial, pressing specific keys like 'space' or 'S' triggers the destruction of either cubes or spheres in the scene.
What is the difference between `GameObject.FindWithTag` and `GameObject.FindGameObjectsWithTag`?
-`GameObject.FindWithTag` finds and returns a single game object with the specified tag, while `GameObject.FindGameObjectsWithTag` returns an array of all game objects with that tag, allowing for batch operations like destroying or modifying them.
How does the script differentiate between game objects when destroying them?
-The script differentiates between game objects based on their tags. It checks the tag of the object and only destroys those with a specific tag, such as 'cube' or 'sphere'.
How can the `OnMouseDown` method be used in Unity scripting?
-The `OnMouseDown` method is called when the user clicks on a game object. In the tutorial, it is used to destroy an object when clicked, but only if the object's tag matches a specified condition, such as 'cube' or 'sphere'.
Outlines
🎮 Introduction to C# Scripting in Unity
In this introductory section, Raja from Charger Games introduces the video, part of a tutorial series on learning C# scripting for Unity. The goal is to teach how to search and find objects in a scene. The example focuses on creating a cube, applying a material, and then manipulating it through C# scripts. Raja demonstrates how to find and interact with objects in a Unity scene, such as changing the cube's color or destroying it.
🧩 Using Tags to Identify and Find Game Objects
This section focuses on tagging game objects to easily locate them within the scene. Raja explains how to create and assign tags to objects like cubes and spheres. He demonstrates how to find game objects using the 'FindGameObjectsWithTag' method, store them in an array, and then manipulate or destroy them through a loop. The tutorial covers the usage of arrays to store multiple game objects and how to traverse through them using a foreach loop to apply actions like destruction.
🌀 Destroying Game Objects by Pressing Keys
In this section, Raja introduces how to destroy game objects by pressing specific keys. Using Unity’s Input system, the script detects key presses (like the spacebar for cubes and the 'S' key for spheres) and destroys the respective objects. The tutorial showcases how to set up different key bindings to control various actions on objects, allowing users to selectively interact with different groups of game objects based on their tags.
🖱️ Destroying Game Objects with Mouse Clicks
Raja explains how to destroy game objects through mouse clicks. A new script called 'Destroyer' is introduced, which uses the 'OnMouseDown' method to detect clicks on objects. Based on their tags (either 'cube' or 'sphere'), the script destroys the clicked object. This method demonstrates how to interact with objects individually while ensuring that only certain tagged objects are affected.
🎨 Performing Different Actions on Multiple Objects with a Single Script
The final section of the video showcases how to perform various actions on different objects using the same script. Raja describes how the 'Destroyer' script can be modified to apply different behaviors depending on the tag of the object. For example, clicking on cubes could turn them red, while clicking on spheres could turn them green. This flexibility allows for dynamic interactions with multiple objects using a unified code structure. The video concludes with a call to action for viewers to apply the learned concepts in their own projects.
Mindmap
Keywords
💡GameObject
💡Tag
💡FindGameObjectsWithTag
💡Script
💡Destroy
💡Array
💡ForEach Loop
💡Material
💡Input.GetKeyDown
💡Empty GameObject
Highlights
Introduction to Learn C# Scripting for Unity tutorial series.
Learning how to search and find different objects from a scene.
Creating a new 3D object named 'cube' and resetting its position.
Applying a black material to the cube for visual enhancement.
Creating a new C# script named 'game manager'.
Attaching the script to a new empty game object named 'game manager'.
Using 'GameObject.FindWithTag' to find objects with a specific tag.
Adding a 'cube' tag to the cube object for identification.
Writing code to find and destroy the cube object with the 'cube' tag.
Duplicating and positioning multiple cube objects in the scene.
Creating a new sphere object and applying a red material.
Adding a 'sphere' tag to the sphere object.
Duplicating and distributing sphere objects across the scene.
Finding and storing references to multiple objects with tags.
Using a for-each loop to destroy all objects with a specific tag.
Destroying all cubes when the space key is pressed.
Destroying all spheres when the 's' key is pressed.
Creating a 'destroyer' script to handle object destruction on mouse click.
Attaching the 'destroyer' script to all game objects for conditional destruction.
Changing the script to destroy spheres instead of cubes by altering the tag check.
Conclusion and call to action for feedback and suggestions for future tutorials.
Transcripts
hey there this is raja from charger
games and welcome back to another video
this is another part of my learn c sharp
scripting for unity tutorial
so in this video as well within short
time we're gonna learn a lot of new
things
so let's get started learning without
wasting any time
so first of all in this video we're
going to learn how we can search and
find
different objects from our scene all
right so as you can see here i can
simply go ahead and create a new 3d
object
and we're going to name it a cube i'm
gonna reset its position
and then i'm gonna position it right so
that i can see it in the scene
now i'm gonna go to my materials folder
and as you can see i already have
created this materials from previous
tutorials
so i can simply drag and drop this black
material right here on the cube
to make it look good and if you don't
have materials created you can simply go
ahead and right click
create and from here you can go to this
material to create a new material
all right so now that we have this cube
now
let's say we want to create a script and
from the script if we want to find the
cube
and do then do something with the cube
let's say we want to change its color or
we want to destroy it
so it doesn't matter wherever we have
this cube
we want to find it from our script and
then do something with it
so for that first of all we're gonna go
ahead and create a new script
i'm gonna create this new c sharp script
and i'm gonna name this one
game manager
okay now i'm gonna create a new
empty game object where we gonna attach
our script so
because this script is the is a generic
script that will
work on our whole game that's why we're
not gonna attach it to any particular
game object
okay so we're gonna create an empty game
object and we're gonna name this one
game manager or game controller anything
that you want
and then i'm gonna drag and drop the
game manager script onto our game
controller
then simply double click to open it in
visual studio
alright now let's try to find out how we
are going to
find the cube so we are going to use a
method called
object dot search or game object
find game objects with tag okay so
let's say in this seed we can add a tag
called cube to this cube and then from
our script we're gonna
find the game object which has this cube
tag
attached and that's how we're gonna find
this game object all right
so in order to add a tag you can select
your cube
and from the tag as you can see
currently it doesn't have any tag
so from here you can select this cube
tag now in my case this cube tag is
already created but in your case you can
go to add tag
and suppose you didn't have this text so
you can simply remove them
and then you can simply click on plus
and from here
select cube and click on save so now as
you can see i have a new tag
created now i can select my cube and
from the tag
select the cube tag okay so now it has
the cube tag attached so now let's go
back to our script
and your script here we gonna say
game object cube
equals game object dot find with
tag and for the tag we're gonna say q
and this is what you need to write
exactly same as it is written in your
tag otherwise this is not gonna work
so this code will find the game object
which has the cube tag attached and give
us access to it
inside this cube variable so now let's
say i want to destroy the cube
so for that i'm going to simply say
destroy
cube all right so this
is what it will do whenever our game
runs this will simply destroy the cube
and as you can see here we have the cube
tag attached now when i click on play
you will see immediately the key will
get destroyed
but you will probably say that we can
already do it
using destroy function we can simply add
a destroy function to this cube and
destroy directly
why do we need to add tag and all these
things so for that i want to say that
let's say there are a lot of objects in
the scene and all of them have different
tag attached
let's say there we have cubes spheres
and cylinders
from there you can simply select all the
cubes because they have the cube tag
attached
and from there you can simply go ahead
and delete them okay so let's see how we
can do that with a better example
so in this case first of all here we
have the cube so i'm going to simply
duplicate the cube
and position it here here somewhere like
this
duplicate it another time position it
here here
so now we have three cubes the same way
we're going to create a new sphere game
object
3d game object sphere all right
and now i'm going to simply go to my
materials tab
and add this red material to the sphere
okay just to make it look a little bit
pretty so here we have our sphere we can
position it
somewhere like this all right now we're
gonna go to our tags
click on add tag from here we're gonna
create a new tag
called sphere all right now we're gonna
select our sphere
and select the sphere tag from here so
now we have a sphere with the sphere tag
attached
and cube with the cube tag attached now
the same way i'm gonna simply duplicate
my sphere and move it around the scene
so that we can distribute it at
different places on the scene
and use them or destroy them or do
anything that you want with them
so now as you can see we have three
cubes and three spheres on the scene
now we need to find out a way so that we
can find out all the cubes
and do something with them and then to
find out a way so that we can find all
the spheres
and do something with them so till now
we have learned how we can only find
one single game object now we're gonna
learn how we can find
multiple different game objects with tag
and how we can store them
so let's say i want to find all the
cubes in the scene
and then store them somewhere for that
we need to create an array
okay so here we are creating a single
variable to store a single object
but if we want to store multiple game
objects then we need to create something
called an
array to create an array of game objects
here we can write game object then a
pair of square brackets
and then we're gonna say cubes okay so
this is an array which will store our
cubes
the same way we're gonna say game object
period of square brackets
and then spheres okay so this is an
array that will store
our spheres so now inside the start
function
instead of writing this what you're
gonna do is we're gonna write
cubes equals game object
dot find game objects with tag
so here we're not going to use the game
object we're going to say
find game objects with text so that we
can find
multiple game objects alright and here
we can write
cube so now what we'll do is
it will simply go to the scene and find
all the game objects
that have this cube tag attached it will
find them
and it will store them inside these
cubes array
and then we can destroy them using a for
each loop
okay so this destroy function will not
work here here we need to use something
called
a for each loop okay so what this will
do is
this will go to the array and search for
each of the game objects
and destroy all of them one by one by
one
so let's see how we can use the forage
loop to use the forage loop we need to
write
for each need to write
game object g in
cubes okay now you can
rename this d to anything you can name
it c you can name it a you can name it
uh cube or anything it doesn't really
matter
so what this will do is this will search
for
all the elements in the cube okay or
this will traverse through all the
elements of this cubes array
let's say we have three cubes on the
scene so this array contains
reference to three of those cubes now
this
forage loop will refer or traverse to
three of those cubes and every time it
finds the
first second and third cube it will
store its reference inside this g
variable
and then we can do anything that we want
using the g variable
so in this case we simply want to say
destroy
g dot game object okay so let's say
it finds the first element in the cube's
array
then it will store the first element
inside g and then it will destroy the g
that is the first element then it will
traverse the second element
store it inside g then destroy secondary
limit
and this way it will keep on going so
here what we are doing is
we are traversing through all the
elements
that are stored inside this cubes array
and destroying them
one by one by one all right now instead
of doing this in the start let's see how
we can do it
when we press a key so inside the update
we're gonna say
if input dot get
key down here we're going to say key
code
dot space now you have used these things
a lot of times in the previous tutorial
so
you should not face any problems here so
whenever we press the space key
let's cut this code
and paste it here so whenever we press
the space button on our keyboard
we want to travel through all the cubes
that we have in the scene
and destroy all of them one by one by
one
so this is it let's save this go back to
unity
and see how our code is working
so as you can see our code is uh
attached to the manager
and now if i click on play you will see
here we have all the different things
and only the cubes will get destroyed
when i press the space key
so three two one space and as you can
see all the cubes got destroyed
because all the cubes had this cube
tag attached okay now let's see how we
can do the same thing for the spheres
so let's go to our game manager
and now we're going to say
here the same way first of all we need
to store the reference of the spheres
so here we're gonna say spheres
equals game object not game controller
game object dot find
game objects with tag and make sure to
write
objects and not object i'm saying it
again and again
and here we're going to say spheres
sphere actually so now we have access to
all the spheres inside this sphere array
now the same way we need to use a
foreign loop
and do the same thing so inside the
update we're going to say if
input dot get key down
input the get key down key code dot
let's say i'm gonna say s
so whenever we press the s key on our
keyboard we're going to do the same
thing so let's copy the forage loop
paste it here and instead of writing
cubes
here we're going to simply write spheres
all right so now what we'll do is it
will
get access to each and every sphere that
is
stored inside this spheres array and
then it will destroy all of them
one by one by one whenever we press the
s
key on our keyboard so let's see how
that works let's go back to unity
and now whenever we're gonna press the s
key on our keyboard
the spheres will get destroyed and
whenever we press the
space button the cubes will get
destroyed so maximize and play
click on play and now i'm going to press
the
s key and as you can see all the spheres
got destroyed
i'm going to press the space key and all
the cubes got destroyed
so this way you can use these features
to
find and search multiple game objects on
the scene
and destroy any of them that you want
anytime
now let's see how we can do some more
cool things using this tag functionality
so let's say we have already learned how
we can simply click on any object and
destroy it
now let's say i want to destroy certain
object
and i want to simply save other objects
and
don't destroy them so let's say i click
on the cubes
and i want to i want to destroy the
cubes but i click on the spheres
but i don't want to destroy the spheres
and we want to actually
write the same code and do the do both
of things together
all right so to do that here i'm gonna
create a new script
and i'm gonna name this one destroyer
and inside the destroyer script what
you're gonna do is we're gonna first of
all check
void on mouse down
so this function will be called whenever
our mouse will be clicked
over this object then we're gonna check
if
this dot gameobject.tag
equals cube
only then we gonna say destroy
gameobject
otherwise we're not gonna destroy the
game object all right so let's see how
that works
so now we're gonna select all of our
game objects and we're gonna add the
destroyer
script to all of them so let's say here
i'm gonna select my cubes
and my spheres all of them together by
pressing the shift key so select the
first one
press the shift key select the last one
and then drag and drop the destroyer
script here
and as you can see all of them will have
the destroyer script attached
all right and we're gonna attach it to
our first cube as well so it has a
description script to it
now let me click on play
and you will see whenever i click on the
spheres nothing happens but whenever i
click on the
cubes they get destroyed all right so
the same script is attached to all of
the game objects
but only the cubes are getting destroyed
the spheres are not
now we can also go ahead and change the
script anytime
so let's say i simply change this to
sphere
and as soon as i do that and go back to
unity
now you will see it will completely be
changed now whenever i go ahead and
click on it
you will see now i can click on the
cubes but they will not get destroyed
but if i click on the spheres they will
get destroyed
okay so just by writing this simple code
and this simple
tag test we can do a lot more things so
we can attach the same script to
multiple game objects
and let's say we click on we run the
game and whenever we click on the cubes
we want to turn them red and whenever we
click on the spheres
we return them green so we can write one
single script
attach them to all the game objects and
perform different actions on them
depending on the different things that
you do
so this is it this is all i wanted to
show you in this video i hope you really
enjoyed and learned a lot of new things
so go ahead and use these skills in your
new projects
so let me know in the comments if you
like this video and what do you want to
see in the next tutorial
and if you if this video helped you
please hit the like button so that i can
make more videos like this
so thank you so much for watching this
is raja from charger games
and i'm gonna see you in this next video
soon
5.0 / 5 (0 votes)