- Home /
How to respawn an object when collision happens with a different object?
If the player either collides with block 1 or collides with block 2, block 1 respawns. But that doesn't work with my "or" statement in there. Block 1 only respawns when player collides with block 1.
Something in those lines are messing up.
The debug line I have does read "collided with block 1", "collided with block 2" depending on which one I hit. Block 2 does the respawning when I hit it, not block 1. Block 1 is supposed to respawn when I hit block 2, block 2 shouldn't be respawning.
//BLOCK 1 RESPAWN [SerializeField] Transform Respawn1; //block1 respawn
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name.Equals("Block 1") || col.gameObject.name.Equals("Block 2"))
{
col.transform.position = Respawn1.position; //respawn block 1
Answer by endasil_unity · Jun 24, 2021 at 03:31 PM
If this thing collided with anything with the exact name "Block 1" OR "Block 2" it will put that object at Respawn1.position; If that is your intention and Block 2 is not moved to Respawn1.position, then your most likely cause is that Block 2 is not spelled exactly "Block 2".
Add a Debug.Log("Collided with " + col.name);
above your row with
if (col.gameObject.name.Equals("Block 1") || col.gameObject.name.Equals("Block 2"))
and check what the name of the thing it collides with is. If it does not print this message at all when you run into Block 2, something is wrong with the collider on block two.
If this information does not solve your problem, you can get back to me with a screenshot of Unity with Block 2 selected in the inspector. Also copy paste that Debug.Log message from the console.
alright so something in those lines are messing up.
The debug does read "collided with block 1" , "collided with block 2" depending on which one I hit. Block 2 does the respawning when I hit it, not block 1. Block 1 is supposed to respawn when I hit block 2, block 2 shouldn't be respawning.
I found a fix.
I put a public game object, then I dragged block 1 into it in the inspector, so when player hits block 1 or block 2, block 1 respawns.
private void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name.Equals("Block 1") || col.gameObject.name.Equals("Block 2"))
{
col.transform.position = Respawn1.position; //respawn block 1
then in this line here, "col.transform.position = Respawn1.position; //respawn block 1" I replaced "col" to whatever I named my game object
Your answer
Follow this Question
Related Questions
2D C# destroy a GameObject on collision 2 Answers
Coding Help 0 Answers
Destroy by Tag isnt working,Can't Destroy By Specific Tags 2 Answers
Distribute terrain in zones 3 Answers