[英]Unity Trouble with Lists
因此,我現在正在Unity中工作,並且使用列表來保留我的值,但遇到了一些麻煩。 以下是相關功能:
List<DNA> generation;
// Use this for initialization
void Start () {
generation = new List<DNA> ();
generation.Add (new DNA ());
generation [0].init ();
Debug.Log (generation[0].Chromosone);
}
該調試發出Null。
在我的DNA課中:
public void init(){
this.Chromosone = new BitArray (36);
for(int i = 0; i < this.Chromosone.Length; i++){
if(Random.Range(0,2) == 1)
this.Chromosone.Set(i,true);
else
this.Chromosone.Set(i,false);
}
lifeTime = Random.Range (1, 3);
Debug.Log (Chromosone);
}
該調試發出它是一個BitArray。
編輯:如果我返回Chromosone,我將BitArray作為返回。 但是第二次我丟失了鏈接(下一行),色胺酮就不復存在了。
編輯:將列表更改為DNA數組可解決此問題,但我需要可修改的長度。 所以那沒有太大幫助...
我使用bool []而不是BitArray在Unity中重新創建了這些腳本,因為這更加常見。 您將使用的代碼為:
主類:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MainClass : MonoBehaviour {
private List<DNA> generation = new List<DNA>();
// Use this for initialization
void Start () {
generation.Add(new DNA());
generation[0].init();
for(int i = 0; i < generation[0].boolLength; i++)
{
Debug.Log(generation[0].chromosone[i]);
}
}
// Update is called once per frame
void Update () {
}
}
DNA類別:
using UnityEngine;
using System.Collections;
public class DNA : MonoBehaviour {
public bool[] chromosone;
public int boolLength = 36;
public int lifeTime;
public void init()
{
this.chromosone = new bool[boolLength];
for(int i = 0; i < boolLength; i++)
{
if(Random.Range (0,2) == 1)
this.chromosone[i] = true;
else
this.chromosone[i] = false;
}
lifeTime = Random.Range(1,3);
}
}
當然,我假設您僅將相關代碼粘貼到了問題中,因此請確保將其余部分重新添加。 但是要注意的一件事是,在MainClass中,請確保using System.Collections.Generic
包含該行,以便可以訪問List類型。
編輯:
如果萬一您必須使用BitArray,則只需將DNA類更改為:
using UnityEngine;
using System.Collections;
public class DNA : MonoBehaviour {
public BitArray chromosone;
public int boolLength = 36;
public int lifeTime;
public void init()
{
this.chromosone = new BitArray(boolLength);
for(int i = 0; i < boolLength; i++)
{
if(Random.Range (0,2) == 1)
this.chromosone.Set(i, true);
else
this.chromosone.Set(i, false);
}
lifeTime = Random.Range(1,3);
}
}
我猜您的問題是,您不是正確地遍歷了chromosone變量以對其進行調試,因為它不是null,或者...您不包括using System.Collections.Generic
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.