Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Gun Script not working

Discussion in 'Scripting' started by wishingchain, May 20, 2018.

  1. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Hi, I recently made this script to shoot bullets when the user clicks the Fire button but it doesnt seem to destroy anything :/ Any help would be greatly appreciated. Thanks
    I am using 2 Scripts for this

    This one is attached to the bullet itself

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BulletCtrl : MonoBehaviour {
    6.  
    7.     public Vector2 speed;
    8.  
    9.     public float delay;
    10.  
    11.     Rigidbody2D rb;
    12.  
    13.     // Use this for initialization
    14.     void Start () {
    15.         rb = GetComponent<Rigidbody2D>();
    16.         rb.velocity = speed;
    17.         Destroy(gameObject, delay);
    18.     }
    19.    
    20.     // Update is called once per frame
    21.     void Update () {
    22.         rb.velocity = speed;
    23.     }
    24.     void OnCollisionEnter2D(Collision2D other)
    25.     {
    26.         if(other.gameObject.name == "Enemy")
    27.         {
    28.             Destroy(other.gameObject);
    29.             Destroy(gameObject);
    30.         }
    31.     }
    32. }
    33.  
    and this one is attached to the player.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerController : MonoBehaviour
    6. {
    7.  
    8.     private Animator anim;
    9.     public Transform groundCheck;
    10.     public bool isGrounded;
    11.     public float jumpForce;
    12.     public float speed;
    13.     Rigidbody2D rb;
    14.     private float moveInput;
    15.     public float checkRadius;
    16.     public LayerMask whatIsGround;
    17.     public string startPoint;
    18.     private static bool playerExists;
    19.     public GameObject leftBullet, rightBullet;
    20.     Transform firepos;
    21.     private bool facingRight = true;
    22.  
    23.     void Start()
    24.     {
    25.         anim = GetComponent<Animator>();
    26.         rb = GetComponent<Rigidbody2D>();
    27.         if (!playerExists)
    28.         {
    29.             playerExists = true;
    30.             DontDestroyOnLoad(transform.gameObject);
    31.         }
    32.         else
    33.         {
    34.             Destroy(gameObject);
    35.         }
    36.  
    37.         firepos = transform.FindChild("firepos");
    38.  
    39.     }
    40.  
    41.     void Update()
    42.     {
    43.         if (Input.GetButtonDown("Jump") && isGrounded)
    44.         {
    45.             rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    46.             isGrounded = false;
    47.         }
    48.         anim.SetFloat("MoveX", Input.GetAxisRaw("Horizontal"));
    49.         if(Input.GetButtonDown("Fire1"))
    50.         {
    51.             Fire();
    52.         }
    53.     }
    54.  
    55.     void FixedUpdate()
    56.     {
    57.         isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
    58.  
    59.         float x = Input.GetAxis("Horizontal");
    60.         Vector3 move = new Vector3(x * speed, rb.velocity.y, 0f);
    61.         rb.velocity = move;
    62.  
    63.         if(facingRight == false && moveInput > 0)
    64.         {
    65.             Flip();
    66.         } else if(facingRight == true && moveInput < 0)
    67.         {
    68.             Flip();
    69.         }
    70.     }
    71.  
    72.     void Flip()
    73.     {
    74.  
    75.         facingRight = !facingRight;
    76.         Vector3 Scaler = transform.localScale;
    77.         Scaler.x *= -1;
    78.         transform.localScale = Scaler;
    79.     }
    80.  
    81.     void Fire()
    82.     {
    83.         if (facingRight)
    84.         {
    85.             Instantiate(rightBullet, firepos.position, Quaternion.identity);
    86.         }
    87.         if (!facingRight)
    88.         {
    89.             Instantiate(leftBullet, firepos.position, Quaternion.identity);
    90.         }
    91.     }
    92. }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    If you put a debug log in your OnCollisionEnter2D can you see a message in the console? In other words, checking to see that it gets called, for enemy or anything at all, even?
     
  3. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Just tried this and got nothing at all.
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    If you tried to print something before checking the enemy tag, I guess that means it hit nothing.
    Is the delay long enough, before it's destroyed? Can you slow the bullet down, increase the destroy delay and see if it gets there properly?
    Just some things to try..
     
  5. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    that could be the problem. I will try it now
     
  6. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    If you spawn the enemies during run time they'll be called"Enemy(clone)" or something like that, maybe that's throwing you off?
     
    Joe-Censored likes this.
  7. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    This ^^^

    It is best not to use the name of gameobjects as identifiers if possible, since Unity will change them under certain circumstances. For something like this I'd set all your enemies with the tag "Enemy" and then use CompareTag to check for that tag.

    https://docs.unity3d.com/ScriptReference/Component.CompareTag.html
     
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    It's good this was pointed out. I don't remember if I noticed the .name instead of .tag which is usually used. I am sure I was deliberate to ask if the method was called at all, though, to rule out one issue at a time. :)

    Tag is good, or if the name.Contains or you get a component that only the enemy would have. :)
     
    Joe-Censored likes this.
  9. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    So I changed the script and now it destroys the player on click. I probably need to chance the location that it shoots from now.

    Script on player
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Bulletcontroller : MonoBehaviour
    5. {
    6.     public float bulletSpeed = 10f;
    7.     public Rigidbody2D bullet;
    8.  
    9.  
    10.     void Fire()
    11.     {
    12.         Rigidbody2D bulletClone = (Rigidbody2D)Instantiate(bullet, transform.position, transform.rotation);
    13.         bulletClone.velocity = transform.forward * bulletSpeed;
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         if (Input.GetButtonDown("Fire1"))
    19.             Fire();
    20.     }
    21. }
    22.  
    23. script on bullet
    24.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Bullet : MonoBehaviour {
    6.  
    7.     // Use this for initialization
    8.     void Start () {
    9.        
    10.     }
    11.    
    12.     // Update is called once per frame
    13.     void Update () {
    14.        
    15.     }
    16.  
    17.     void OnCollisionEnter2D(Collision2D collision)
    18.     {
    19.         Destroy(collision.collider.gameObject);
    20.         Destroy(gameObject);
    21.     }
    22.  
    23. }
    24.  
     
  10. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Update:
    Just changed the script. it now destroys the enemy only(using tree for testing) but spawns inside the player :/
     
  11. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    with a few lines of code I managed to fix it. But the bullet just falls to the ground, how do I fix this? Is there also a way to destroy the bullet after 2 seconds?
     
    Last edited: May 23, 2018
  12. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    I fixed the
    destroying thing but now I need to add velocity
     
  13. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You can disable gravity on the bullet.
    For the 2 secs 'til destruction, just add this after you instantiate it:
    Code (csharp):
    1. Destroy(bulletClone.gameObject , 2);
     
  14. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Thank you it works perfectly. How would I add velocity to it so it doesnt just fall?
     
  15. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I thought you already had that in the Fire method. As for not just falling, as I was saying you can disable gravity.
    If it's just falling and gravity is off, then maybe you shot it downwards? Not sure.
     
  16. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Bullet : MonoBehaviour {
    6.  
    7.     public Rigidbody2D rb2D;
    8.     public float velocity;
    9.  
    10.     // Use this for initialization
    11.     void Start() {
    12.         rb2D = GetComponent<Rigidbody2D>();
    13.         StartCoroutine(Fire());
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update() {
    18.  
    19.     }
    20.  
    21.     void OnCollisionEnter2D(Collision2D collision)
    22.     {
    23.         if (collision.gameObject.tag == "enemy")
    24.         {
    25.             Destroy(collision.collider.gameObject);
    26.             Destroy(gameObject);
    27.         }
    28.     }
    29.    
    30.     IEnumerator Fire()
    31.     {
    32.         yield return new WaitForSeconds(2);
    33.         Destroy(gameObject);
    34.     }
    35.  
    36. }
    this is the script thats on the bullet right now. I changed it as the first one wasnt working.
     
  17. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I see. So, is there supposed to be a 2 second delay when you fire?
    Does the bullet just go straight forward, based on its rotation?

    If it's just straight forward, you could use (assuming facing right means facing forward):
    Code (csharp):
    1. rb2D.velocity = transform.right * bulletSpeed;
    If it's suppose to fire right away, just put that code in Start(), add get rid of the coroutine.

    Just put: Destroy(gameObject, 2); it will take care of the 2 second wait before it destroys it.
     
  18. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    Forget about ^ I fixed it but It keeps firing to the right but not to the left when im facing left.
     
  19. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    So, do you have a bool that says which way you're facing, maybe?
    if it's not right, use:
    Code (csharp):
    1. rb2D.velocity = -transform.right * bulletSpeed;
     
  20. wishingchain

    wishingchain

    Joined:
    Oct 5, 2016
    Posts:
    25
    I had a bool that said it but its not working properly. I am working on fixing it now