Bullet Prefab Script

雨燕双飞 提交于 2019-12-20 06:05:00

问题


I am getting an error in this script?

UnityEngine does not contain a definition for rigid body (Lines: 22,24)

public class GunShoot : MonoBehaviour
{
    public GameObject BulletPrefab;
    public float BulletSpeed;
    public int BulletsInClip;
    public AudioClip GunshotSound;

    void Update () {

        if (Input.GetButtonDown("Shoot")){

            Shoot();
        }
    }

    void Shoot() {

        var bullet = Instantiate(BulletPrefab, transform.Find("BulletSpawn").position, transform.Find("BulletSpawn").rotation);
        bullet.rigidbody.AddForce(transform.forward * BulletSpeed);
        audio.PlayOneShot(GunshotSound);
        BulletsInClip--;
    }
}

回答1:


A var in this case means that the created instance is of type UnityEngine.Object. You need to specify a type cast explicitly:

var bullet = Instantiate(BulletPrefab) as GameObject;

or

var bullet = (GameObject) Instantiate(BulletPrefab);

In general it is preferrable to use an explicit type as it increases readability (my oppinion) like:

GameObject bullet = Instantiate(BulletPrefab) as GameObject;



回答2:


In Unity you need to grab the rigidbody like thisbullet.GetComponent<Rigidbody >().AddForce(...) -- this is c# btw I'm not sure how different it is in JavaScript.




回答3:


Use GetComponent to get the RigidBody something like this.

gameObject.GetComponent<Rigidbody>().AddForce(transform.forward * BulletSpeed);


来源:https://stackoverflow.com/questions/23538680/bullet-prefab-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!