将自定义类附加到新实例化的对象上

问题描述 投票:0回答:1

我正在尝试实例化多个称为Stars的对象。在我的Simulation类中,我有一个方法,其中将创建一个名为newStar的对象并附加Star类。

这是我的GameObject层次结构:

GameObject hierarchy

具有Simulation类的Simulation脚本已附加到Simulation游戏对象。具有Star类的Star脚本已附加到StarObject游戏对象。在Star脚本中,我已经将星星的预制件附加到prefabStar上,并且StarObject游戏对象已通过Unity编辑器附加到StarObject变量中。]

这是我的模拟类:(ObjectStar是一个GameObject,它是prefabStar的父级。

void listStars()
{
    int i = 0;
    while (i < (StarDataBank.Instance.NumOfStars))
    {
        int primaryID = int.Parse(StarDataBank.Instance.StarIDID[i]);
        string properName = StarDataBank.Instance.StarName[i];
        string HIPID = StarDataBank.Instance.StarIDHIP[i];
        string HDID = StarDataBank.Instance.StarIDHD[i];
        string HRID = StarDataBank.Instance.StarIDHR[i];
        string GLID = StarDataBank.Instance.StarIDGL[i];
        string BFID = StarDataBank.Instance.StarIDBF[i];
        decimal rightAscension = Convert.ToDecimal(StarDataBank.Instance.StarRA[i]);
        decimal declination = Convert.ToDecimal(StarDataBank.Instance.StarDec[i]);
        decimal Mag = Convert.ToDecimal(StarDataBank.Instance.StarMag[i]);
        decimal CI = Convert.ToDecimal(StarDataBank.Instance.StarCI[i]);
        int scale = 0;
        int r = 0;
        int g = 0;
        int b = 0;
        Star newStar = ObjectStar.AddComponent<Star>();
        newStar.Instantiate(primaryID, properName, HIPID, HDID, HRID, GLID, BFID, rightAscension, declination, Mag, CI);
        i++;
    }
}

这里是星级课程:

public void Instantiate(int primaryID, string properName, string HIPID, string HDID, string HRID, string GLID, string BFID, decimal rightAscension, decimal declination, decimal magnitude, decimal colourIndex)
{
    this.primaryID = primaryID;
    this.properName = properName;
    this.HIPID = HIPID;
    this.HDID = HDID;
    this.HRID = HRID;
    this.GLID = GLID;
    this.BFID = BFID;
    this.rightAscension = rightAscension;
    this.declination = declination;
    this.magnitude = magnitude;
    this.colourIndex = colourIndex;
    var newStar = Instantiate(prefabStar, transform.position + getVector(Convert.ToDecimal(rightAscension), Convert.ToDecimal(declination)), Quaternion.identity);
    newStar.name = (primaryID).ToString();
    newStar.transform.parent = StarObject.transform;
    newStar.transform.localScale = new Vector3(20, 20, 20);
}

[我期望的目的是创建一个prefabStar的克隆,每个克隆都附加到Star类,因此我可以检索prefabStar的每个克隆的变量。]​​>

相反,正在发生的错误是显示“您要实例化的对象为空。”并且没有新的游戏对象(prefabStar未被克隆。)

我正在尝试实例化多个称为Stars的对象。在我的Simulation类中,我有一个方法,其中将创建一个名为newStar的对象并附加Star类。这是我的GameObject ...

c# unity3d instantiation gameobject
1个回答
0
投票

再次检查编辑器,并尝试查看您启动的预制件在启动游戏后在游戏编辑器中是否仍然可见。处于游戏模式时,可能错误地将其附加到了编辑器中

© www.soinside.com 2019 - 2024. All rights reserved.