Day 4 of Getting Started with Unity: The Response of a Bullet Touching an Object
This article tells about the different situations when bullets encounter players, bases, brick walls and iron walls.
~~I can’t keep up my spirits these days, but when I continued to learn Unity yesterday, I encountered a bottleneck. The bullet didn’t have the effect of touching the object, which made it worse. Fortunately, after checking for a long time today, I finally saw it, and I wrote it later, hoping to take this as a warning. ~~
Player death handling
In the tank battle, both the player and the enemy can fire bullets. In order to~~ the player can die~~ distinguish different bullets, we set a boolean value: public bool isPlayerBullet;//default false, and take the switch before In the statementframe add:
1 | case "Tank": |
In the player (tank) script, the Die method is as follows (⚠️The method name must be the same or it cannot be called!):
1 | //Explode the prefab prefab: |
Base attacked
Our expectation is that when the base is attacked, the eagle flag will become a battle-scarred flag, and again, the call to the defeat method is made in the switch condition:
1 | case "Heart": |
And after creating a new Heart script, we load the prefab and set the prefab to be called after calling the Die method:
1 | public class Heart : MonoBehaviour |
Brick and iron walls are attacked
When a brick wall is hit by a bullet, both the bullet and the brick wall should disappear; when an iron wall and an air wall are hit, only the bullet disappears:
1 | case "Wall": |
ridiculous problem
- The first problem is that when I wrote OnTriggerEnter2D, the system did not allow me to write private. At first, I thought it was a version problem and didn’t care. Later, when I actually ran it, I found that this method was not called at all, and it was set to private void and an error was reported. After repeated comparisons, I found that I wrote this method in
Update(), which is really speechless… - The second thing is that my bullet can still pass through the wall after writing the above code. After confirming that the code is correct, after a long, long investigation, I found out that it was because I installed a
Box on the objects in thehierarchyCollider 2D,Rigidbody 2D, but not installed inprefab, nor update the picture ofSprite Rendererin theprefabscript, even if Ioverridemany times, but these few places It hasn’t been updated, I don’t know if it’s the wrong way for me to open it… - The experience is that things updated in
hierarchyin the future should remember to check inprefabto see if they are synchronized!