首页 文章

为什么我的JS脚本工作但不是同一个C#?

提问于
浏览
2

我最近开始在unity3d中工作,我在教程后遇到了以下问题 .

本教程使用了unity-javascript,但我更喜欢使用C# .

我在Javascript中获得了以下代码

function Shoot() {
    var bullet = Instantiate(bulletPrefab, 
                             transform.Find("BulletSpawn").position,
                             transform.Find("BulletSpawn").rotation);
    bullet.rigidbody.AddForce(transform.forward * bulletSpeed);                      
}

并用C#编码重写为

void Shoot() {
    GameObject bullet;
    bullet = Instantiate(bulletPrefab, 
                         transform.Find("BulletSpawn").position,
                         transform.Find("BulletSpawn").rotation) as GameObject;
    bullet.rigidbody.AddForce(transform.forward * bulletSpeed); 
}

我的问题是JS脚本有效,但我得到了我的C#代码

NullReferenceException:未将对象引用设置为对象的实例

在线 bullet.rigidbody.AddForce(transform.forward * bulletSpeed);

我可能做错什么的任何建议?

1 回答

  • 4

    Instantiate 的返回类型是 Transform ,无法直接转换为 GameObjectas GameObject

    你的代码应该是:

    void Shoot() {
        Transform bullet;
        bullet = Instantiate(bulletPrefab, 
                             transform.Find("BulletSpawn").position,
                             transform.Find("BulletSpawn").rotation);
        bullet.rigidbody.AddForce(transform.forward * bulletSpeed); 
    }
    

相关问题