无法创建对象C#

时间:2016-05-08 11:22:52

标签: c# unity3d

我有两个相同的课程,一个用于主要武器,另一个用于辅助武器。这是我的课程:

public class weapon : MonoBehaviour {

public string Name { get; set; }
public float Damages { get; set; }
public float FireRate { get; set; }
public float Range { get; set; }
public float BulletSpeed { get; set; }
public bool isOn { get; set; }

public weapon(string name, float damages, float fireRate, float range, float bulletSpeed, bool ison) {

    this.Name = name;
    this.Damages = damages;
    this.FireRate = fireRate;
    this.Range = range;
    this.BulletSpeed = bulletSpeed;
    this.isOn = ison;
    }
}

public class weapon1 : MonoBehaviour {

public string Name { get; set; }
public float Damages { get; set; }
public float FireRate { get; set; }
public float Range { get; set; }
public float BulletSpeed { get; set; }
public bool isOn { get; set; }

public weapon1(string name, float damages, float fireRate, float range, float bulletSpeed, bool ison) {

    this.Name = name;
    this.Damages = damages;
    this.FireRate = fireRate;
    this.Range = range;
    this.BulletSpeed = bulletSpeed;
    this.isOn = ison;
    }
}

我希望在另一个剧本中,当我按下F' F'时,武器分别采用了他们的规格,但是在给第二个名称时它会被卡住,这是我的脚本给他们的规格:

    void Update () {

    if (Input.GetKeyDown (KeyCode.F)) {

        GetComponent<weapon> ().Name = "Rien";
        GetComponent<weapon> ().Damages = 0;
        GetComponent<weapon> ().FireRate = 0;
        GetComponent<weapon> ().Range = 0;
        GetComponent<weapon> ().BulletSpeed = 0;
        GetComponent<weapon> ().isOn = true;

        Debug.Log (GetComponent<weapon> ().Name);

        GetComponent<weapon1> ().Name = "Rien1"; //stuck here... :'(
        GetComponent<weapon1> ().Damages = 0;
        GetComponent<weapon1> ().FireRate = 0;
        GetComponent<weapon1> ().Range = 0;
        GetComponent<weapon1> ().BulletSpeed = 0;
        GetComponent<weapon1> ().isOn = false;

        Debug.Log(GetComponent<weapon1> ().Name);
    }

}

我得到的对象引用未设置为对象的实例&#39;我对两种武器都做了同样的事情 提前致谢

1 个答案:

答案 0 :(得分:1)

您正在制作一些基本的编程错误以及一些基本的Unity特定错误。正如评论中所说,你不应该有很多完全相同的课程。记得not repeat your self

然后您继承自MonoBehaviour,但正在定义一个构造函数方法来设置字段。不要团结一致。通过将它们公开或将[SerializeField]属性添加到私有成员变量,使检查器中的feild可用。如果在创建对象时有任何想要做的事情,请将其放在Start()方法中:

public Weapon : MonoBehviour
{
    public string name; //set these in the inspector for each weapon
    public float damage;
    //etc

    // in Unity you use the Start method for mono behaviours. NOT the constructor method
    void Start()
    {
        //Do things when the object is created
    }
}

现在,我们不清楚你是如何从你的问题中向你的玩家添加武器的,但你应该做的是将游戏对象作为孩子添加到层次结构中的玩家对象。为每个武器执行此操作,然后将武器脚本添加到每个武器。然后在检查器中更改您自己可用的字段。然后,您可以通过播放器上的脚本获取玩家当前拥有的武器的参考,并在按下某个键时按照您的值进行操作。