我创建了一个类来组织一些数据,一个类由其中的几个类组成(子类?)这样我就能做些像..。
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;
}
}发布于 2016-04-29 21:17:50
您必须使用new关键字来初始化genome和quantity。当要初始化的类不从new派生时,可以使用MonoBehaviour关键字进行初始化。您的Genome和Quantity类不是从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;
}现在,如果您的Genome和Quantity类都是从MonoBehaviour派生的。您永远不应该使用新的关键字来初始化它们。
例如:
class Gene :MonoBehaviour{
}如果不使用新关键字,则使用脚本附加的addComponent或Instantiate GameObject。如果类将从MonoBehaviour派生,则类中永远不应该有构造函数。
void Start()
{
genome = gameObject.AddComponent<Gene>();
}https://stackoverflow.com/questions/36947479
复制相似问题