1
votes

hey guys im trying to shoot with simple code i have 2 C# Classes one for Player movements and one for Bullet

this is Bullet Collision Class

void Start () {
    source.clip = clip;
    bullet = GetComponent<GameObject>();
    rb = GetComponent<Rigidbody2D>();
    bulletPos = player.position;
}

// Update is called once per frame
private void OnTriggerEnter2D(Collider2D wallCol)
{
    if (wallCol.gameObject.tag == "Wall")
    {
        Debug.Log("Wall Hited!");
        source.Play();
        Destroy(bulletPrefab,clip.length);
        if (bullet == null)
            Instantiate(bulletPrefab, bulletPos, Quaternion.identity);
    }
}
public void shoot()
{
    rb.velocity = rb.transform.right * bulletSpeed;
}

this is Player Movement Class:

void Update()
{

    if (Input.GetKeyDown(KeyCode.Mouse0) && haveGlock == true)
    {
        bc.shoot();
        AudioSource.PlayOneShot(GlockClip);
    }

}

i did use shoot method on another class and when the method called its show me the object reference not set to instance of the object. also i drag and drop objects in required public variables in unity but why its not gonna work?

sorry for my bad English guys.

1
Does your bullet have a Rigidbody2D component ? It seems like it's the problem - Jichael
yes it does @Jichael - user6845869
Why " if (bullet == null) Instantiate(bulletPrefab, bulletPos, Quaternion.identity);" ?? you create an empty game object, its not even put into bullet, bullet is never null.. - BugFinder
Destroy(bulletPrefab,clip.length); - you're trying to destroy a prefab not an instance of it, this also wont work - BugFinder
thanks.. so have you any soultion? @BugFinder - user6845869

1 Answers

0
votes

Make sure "bc" is assigned in Player Movement Class.

I would do something like that on Player Movement Class.

void Update()
   {
    if (Input.GetKeyDown(KeyCode.Mouse0) && haveGlock == true)
    {
        BulletCollision bc = Instantiate(bulletPrefab, bulletPos, Quaternion.identity);
        bc.shoot();
        AudioSource.PlayOneShot(GlockClip);
    }