如何引用Unity3D monobehaviour中由类组成的类?

时间:2016-04-29 21:09:40

标签: c# class unity3d subclass nullreferenceexception

我创建了一个类来组织一些数据,一个类由几个类组成(Subclass?),所以我可以做类似......

classA.classB.value = 1;

但是我无法弄清楚如何引用我的课程。如果有人知道我应该如何去做那件事会很棒!

using UnityEngine;
using System.Collections.Generic;
using System.Collections;

class Gene {
    public string name;
    public float value;
    public float complexity;

    public Gene() {
        name = "";
        value = 0;
        complexity = 0;
    }

    public Gene(string Name, float Value, float Complexity) {
        name = Name;
        value = Value;
        complexity = Complexity;
    }
}

class Genome {
    public Gene agility;
    public Gene intelligence;
    public Gene strength;

    public Genome(){
        agility = new Gene();
        intelligence = new Gene();
        strength = new Gene();
    }

    public Genome(Gene Agility, Gene Intelligence, Gene Strength) {
        agility = Agility;
        intelligence = Intelligence;
        strength = Strength;
    }
    public IEnumerator GetEnumerator() {
        return (IEnumerator)this;
    }
}

public class Life : MonoBehaviour {
    Genome genome;      //Warning Life.genome is never assigned to, and will always have its default value null
    Quantity quantity;  //Warning Life.quantity is never assigned to, and will always have its default value null

    void OnEnable() {
        genome = /*???*/;   //How do I add the reference?
        quantity = /*???*/; //How do I add the reference?

        genome.agility.name = "Agility"; //On Runtime: NullReferenceException: Object reference not set to an instance of an object
        genome.agility.complexity = 100;

        genome.intelligence.name = "Intelligence";
        genome.intelligence.complexity = 1000;

        genome.strength.name = "Strength";
        genome.strength.complexity = 100;
    }
}

1 个答案:

答案 0 :(得分:2)

您必须使用new关键字初始化genomequantity。当您尝试初始化的类不是从new派生时,可以使用MonoBehaviour关键字进行初始化。您的GenomeQuantity类并非来自MonoBehaviour,因此新关键字是初始化它们的正确方法。

Genome genome = null;
Quantity quantity = null;

void Start()
{
    //initialize
    genome = new Genome(new Gene("", 0, 0), new Gene("", 0, 0), new Gene("", 0, 0));
    quantity = new Quantity ();

    //Now you can use both references
    genome.agility.name = "Agility"; 
    genome.agility.complexity = 100;

    genome.intelligence.name = "Intelligence";
    genome.intelligence.complexity = 1000;

    genome.strength.name = "Strength";
    genome.strength.complexity = 100;


}

现在,如果您的GenomeQuantity类都来自MonoBehaviour。您永远不应该使用new关键字来初始化它们。

例如:

class Gene :MonoBehaviour{

}

您没有使用新关键字,您可以使用附加脚本的addComponentInstantiate GameObject。如果它来自MonoBehaviour,你应该永远不会在类中有一个构造函数。

void Start()
{
  genome = gameObject.AddComponent<Gene>();
}