Search Unity

How to activate a function when bullet hits a collider?

Discussion in 'Scripting' started by GameDevAcademyy, Jun 22, 2020.

  1. GameDevAcademyy

    GameDevAcademyy

    Joined:
    Jan 11, 2019
    Posts:
    34
    Hello world, someone can help me with a function for my script? , I have 3 bullets UI, one player, one enemy, in my scene, ex function 1 - if bullet hit the enemy {StartCoroutine(win())}, for function 2 I use this - if bullets == 0 { StartCoroutine(lose()), but I did not find a function when bullet hit the enemy...
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    If you are using physics and colliders, implement one of the OnCollision family of functions or OnCollision2D family of functions, which ever applies in your case.

    If you're not using physics, then use raycast to find the collider ahead of your bullet, or check coordinates yourself directly with a distance check.
     
  3. GameDevAcademyy

    GameDevAcademyy

    Joined:
    Jan 11, 2019
    Posts:
    34
    I tried with OnTriggerEnter2D but same problem, I mean if hiting the enemy and bullets == 0, the scene shows me [ lose dialog( so for so good) . but if i hit the enemy with bullet 1 and bullet 2 ( the scene shows me win, because last bullet remained, but if i try with bullet 3 ( the scene shows me lose..)
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    I recommend liberally inserting Debug.Log() statements before every decision point that involves the variables you say are different, in order to find out why the decision is happening.
     
    GameDevAcademyy likes this.
  5. GameDevAcademyy

    GameDevAcademyy

    Joined:
    Jan 11, 2019
    Posts:
    34
    Hmm, i used Time.timeScale = 0 and it's works but i can't use my retry button now..
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    if timescale is zero and you yield return a new WaitForSeconds() that will never continue.
     
    GameDevAcademyy likes this.
  7. GameDevAcademyy

    GameDevAcademyy

    Joined:
    Jan 11, 2019
    Posts:
    34
    And what can I do?
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    You haven't really stated what you're trying to do. If you're trying to implement a win and lose state, going to a new scene at that point is almost always the easiest way to go because then you don't have to hassle with anything else that might still be running from the game.

    I only ever set timeScale to zero when I want an in-game pause.
     
  9. GameDevAcademyy

    GameDevAcademyy

    Joined:
    Jan 11, 2019
    Posts:
    34
    See my problem bro?


    I use OnTriggerEnter2D(Collider2D col) for WIN and for LOSE - function if (bullets == 0)