AddComponent(“Rigidbody”)或其他组件不起作用

时间:2016-08-12 18:52:55

标签: unity3d components unityscript

我正在尝试编写一个非常简单的FPS游戏,并且我达到了需要创建拾取武器系统的程度。为了完成该系统,我陷入了需要AddComponent("Rigidbody")AddComponent("BoxCollider")的点,Unity3D抛出了这个错误:

  

'AddComponent不是'WeaponPickUp'的成员

WeaponPickUp是我的Javascript脚本文件。

以下是我的代码:

 #pragma strict

 var pickup = false;
 var check = 2;

 function Update () {
     if (Input.GetButtonDown("pickup") && check % 2 == 0){
         GetObject();
         pickup = true;
         check = check + 1;
     }
     else if (Input.GetButtonDown("pickup") && (check % 2 == 1)){
         pickup = false;
         check = check - 1;
         this.AddComponent("Rigidbody") as Rigidbody;
         this.AddComponent("BoxCollider") as BoxCollider;
         this.GetComponent(BoxCollider).enabled = true;
     }
 }

 function GetObject(){
     var position : GameObject = GameObject.Find("weaponPosition");
     this.transform.position = position.transform.position;
     Destroy(GetComponent(Rigidbody));
     Destroy(GetComponent(BoxCollider));
     this.transform.parent = GameObject.Find("FPSController").transform;
     this.transform.parent = GameObject.Find("FirstPersonCharacter").transform;
     //    this.transform.parentposition
 }

我不知道为什么会这样。任何人都愿意帮助我,我将一如既往地欣赏它!

2 个答案:

答案 0 :(得分:1)

this.AddComponent("Rigidbody") as Rigidbody;
this.AddComponent("BoxCollider") as BoxCollider;
this.GetComponent(BoxCollider).enabled = true;

需要

gameObject.AddComponent("Rigidbody") as Rigidbody;
gameObject.AddComponent("BoxCollider") as BoxCollider;
gameObject.GetComponent(BoxCollider).enabled = true;

Destroy

相同

AddComponentGameObject的一部分,而非WeaponPickUp

答案 1 :(得分:0)

使用this删除gameObject个关键字,然后移除as Rigidbodyas BoxCollider

这应该是这样的:

gameObject.AddComponent("Rigidbody");
gameObject.AddComponent("BoxCollider");
gameObject.GetComponent("BoxCollider").enabled = true;

上面的语法应该有效,但它已经过时了。它在Unity 5中发生了变化。 如果这样做会导致错误。下面是新的语法和现在正确的方法。

GetComponent.<Rigidbody>();
GetComponent.<BoxCollider>();
GetComponent.<BoxCollider>().enabled = true;

您的整个代码:

#pragma strict

var pickup = false;
var check = 2;

function Update () {
    if (Input.GetButtonDown("pickup") && check % 2 == 0){
        GetObject();
        pickup = true;
        check = check + 1;
    }
    else if (Input.GetButtonDown("pickup") && (check % 2 == 1)){
        pickup = false;
        check = check - 1;
        GetComponent.<Rigidbody>();
        GetComponent.<BoxCollider>();
        GetComponent.<BoxCollider>().enabled = true;
    }
}

function GetObject(){
    var position : GameObject = GameObject.Find("weaponPosition");
    this.transform.position = position.transform.position;
    Destroy(GetComponent(Rigidbody));
    Destroy(GetComponent(BoxCollider));
    this.transform.parent = GameObject.Find("FPSController").transform;
    this.transform.parent = GameObject.Find("FirstPersonCharacter").transform;
    //    this.transform.parentposition
}
相关问题