Try our game PORTAL GALAXY for Android here: bit.ly/PG_WCG
ZOMBIE BARREL BLAST signups here: bit.ly/WCG_ZBB
In this video we're going to be taking a look at how to use GameObject.FindObjectOfType(), as well as GameObject.Find() and GameObject.FindGameObjectWithTag()...
As well as all of the array versions!
This is a big subject and there's a lot to cover. These methods can easily get mixed up, intertangled, and it can be super confusing to know when it's better to use one of these over another.
Fortunately, I'm going to clearly demonstrate the differences between all three of these methods (with examples) as well as their various downsides.
You can check out the slides shared in this video by clicking this link: bit.ly/2XzP6VV
Three Types of Find Methods:
Find methods are ways of attaching variables to scripts through code, instead of by dragging and dropping in the Unity editor.
FIRST TYPE:
- GameObject.Find () - finds a single object by its name
SECOND TYPE
- GameObject.FindObjectOfType () - Finds a unique GameObject/Script
- GameObject.FindObjectsOfType () - Finds multiple GameObjects/Script
THIRD TYPE
- GameObject.FindGameObjectWithTag () - Finds a unique GameObject/Script
- GameObject.FindGameObjectsWithTag () - Finds multiple GameObjects/Script
GameObject.Find()
- Looks for GameObjects of the requested name and returns the first one found
- Is a fast way to get a reference to a specific GameObject
- DOWNSIDE: Will not work if you change the GameObject’s name or if there is a spelling error
- DOWNSIDE: Can slow down your game, (especially on mobile), if used too often.
GameObject.FindObjectOfType()
- Looks for scripts or other objects of the requested type and returns the first one found
- Is a fast way to get a reference to a unique script or other object without dragging and dropping
- Use FindObjectsOfType() to return ALL scripts or objects of the requested type into an array.
- DOWNSIDE: Potential for mix-up if trying to attach a specific object with multiple objects of the same type in the scene.
- DOWNSIDE: Can slow down your game, (especially on mobile), if used too often.
GameObject.FindObjectWithTag()
- Looks for GameObjects via the requested tag
- Is a fast way to get a reference to a unique GameObject without dragging and dropping (or needing a script attached at all)
- Use FindObjectsOfType() to return ALL GameObjects with the requested tag, into an array.
- DOWNSIDE: Same downsides as GameObject.Find(). It relies on making sure requested tags are spelt properly.
- DOWNSIDE: You might forget to tag GameObjects
- DOWNSIDE: It can only search for and add GameObjects - not scripts
- DOWNSIDE: Can slow down your game, (especially on mobile), if used too often.
Try our game PORTAL GALAXY for Android here: bit.ly/PG_WCG
ZOMBIE BARREL BLAST signups here: bit.ly/WCG_ZBB
5 сен 2024