简体   繁体   中英

shoot to mouse click direction unity3D

Im learning unity3D Im creating a simple game where the player needs to shoot the enemies that are falling from the sky. I already made everything but when I try to shoot where the player clicks on screen I get this error NullReferenceException: Object reference not set to an instance of an object. The funny thing is that is shooting the ball towards the click but the game abruptly quits because of the exception. I have this code attached to my player:

if(Input.GetMouseButtonDown(0)){

        shootDirection = Input.mousePosition;
        shootDirection.z = 0.0f;
        shootDirection = Camera.main.ScreenToWorldPoint (shootDirection);
        shootDirection = shootDirection - transform.position;

        Rigidbody2D bulletInstance = Instantiate(bulletPrefab, transform.position, Quaternion.Euler(new Vector3(0,0,0))) as Rigidbody2D;
        bulletInstance.velocity = new Vector2(shootDirection.x * speed, shootDirection.y * speed);

The error is pointing me in the console is this line:

bulletInstance.velocity = new Vector2(shootDirection.x * speed, shootDirection.y * speed);

It would be very helpful if someone can point me out where is my error or what's going on.

I think the problem is that you want to say that bulletInstance is a GameObject that has a Rigidbody2D, not that it is one.

Untested code:

GameObject bulletInstance = Instantiate(...) as GameObject;
Rigidbody2D rb2d = bulletInstance.getComponent<Rigidbody2D>();
rb2d.velocity = new Vector2(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM