简体   繁体   English

C#/Unity 实例化 class 创建具有相同实例 ID 0 的副本

[英]C#/Unity Instantiating class creating copies with same instance ID of 0

The function below is supposed to create a new instance of SolarSystem_Manager and add it to a list however when var clone = Instantiate(_solar) is run, it returns a nullreference error.下面的 function 应该创建SolarSystem_Manager的新实例并将其添加到列表中,但是当运行var clone = Instantiate(_solar)时,它返回nullreference错误。 All instances of _solar have the same ID when I created multiple and this was 0 and changing the variables of one also changes the variables of the others.当我创建多个时, _solar的所有实例都具有相同的 ID,这是 0,更改一个的变量也会更改其他的变量。 Do you know what I am doing wrong?你知道我做错了什么吗?

private void createSolarSystem()
         {
             SolarSystem_Manager _solar = new SolarSystem_Manager();
             _solar.solarSystem = new SolarSystem(transform.GetComponent<Galaxy>(), Random.Range(9, 10), new List<LQPlanetManager>(), new SunManager());
             var clone = Instantiate(_solar);
             solarSystems.Add(clone);
         }

You shouldn't instantiate a Unity object with the new keyword.您不应使用new关键字实例化 Unity object。 You should rather make a prefab of SolarSystem_Manager inside the editor and store it inside some variable:您应该在编辑器中制作 SolarSystem_Manager 的预制件并将其存储在某个变量中:

  1. Add this to your class:将此添加到您的 class 中:

    [SerializeField] private GameObject _solarSystemManagerPrefab;

  2. Inside the editor, create a prefab and drag and drop it into _solarSystemManagerPrefab .在编辑器中,创建一个预制件并将其拖放到_solarSystemManagerPrefab中。

  3. Now you can instantiate your prefab like this:现在您可以像这样实例化您的预制件:

    GameObject clone = Instantiate(_solarSystemManagerPrefab)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM