【发布时间】:2020-06-06 15:47:15
【问题描述】:
我正在尝试实例化多个名为 Stars 的对象。在我的 Simulation 类中,我有一个方法,我在其中创建一个名为 newStar 的对象并附加 Star 类。
这是我的游戏对象层次结构:
具有模拟类的模拟脚本附加到模拟游戏对象。具有 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++;
}
}
这里是 Star 类:
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 没有被克隆。)
编辑:我在编辑器中添加了 Star 预制件的屏幕截图, 注意 Star 类是如何附加到这个预制件上的。 (请忽略Star Manager这个名字,我做了几个测试,问题仍然存在,它叫Star)
【问题讨论】:
-
错误信息表示哪一行代码?似乎您的 prefabStar 设置不正确并指向空/空。你能在实例化之前 Debug.Log 看看它是否指向任何有意义的东西吗?
-
@Rixment,在 Star 类中显示“var newStar = Instantiate(...)”的行
-
在实例化之前Debug.Log它的prefabStar指向什么?
-
Debug Logging prefabStar 返回 null,这很奇怪,因为我已经通过编辑器将 prefab 附加到了这个变量
-
我发现在没有更多信息的情况下调试您的案例有点困难。将您在星类上分配 prefabStar 的字段保留为公共字段,使附加到 prefabStar 的组件可序列化,并在启动游戏时查看它是否为空。请注意,AddComponent 将对其他组件的任何引用创建为 null。顺便说一句,在你的场景中,我可能会使用 Zenject 之类的东西创建一个对象池,这样我就可以创建启动时需要的所有对象。
标签: c# unity3d instantiation gameobject