Unity ArgumentException:要实例化的Object为null

时间:2018-04-09 10:00:36

标签: c# unity3d

过去三天我一直在讨论这个问题。我试图实例化一个Unity预制件。我收到以下错误:

ArgumentException: The Object you want to instantiate is null.

我更改了GameObject(Sphere),但我得到了同样的错误。这是我的代码。

public class SEMCell : MonoBehaviour, IAbstractCell{
    SCE[] arrayOfSCEs;
    public SCE scePrefab;
    void IAbstractCell.setMecaModel(AbstractCellMechanicsModel model){
        this.arrayOfSCEs = new SCE[10];
        SCE sce;
        for (int i = 0; i < 10; i++) {
        sce = Instantiate(scePrefab);
        this.arrayOfSCEs[i] = sce;
    }
}

我还将我的GameObject链接到预制属性。任何人都有解决方案的线索?提前谢谢。

enter image description here

3 个答案:

答案 0 :(得分:0)

您的预制件应为GameObject类型,而不是SCE

public SCE scePrefab;更改为public GameObject scePrefab;

sce = Instantiate(scePrefab);sce = Instantiate(scePrefab).GetComponent<SCE>();

答案 1 :(得分:0)

您发布的代码很好。无论处理IAbstractCell是什么,都将scePrefab字段设置为空。

尝试将您的SCE字段设为私有和序列化:

[SerializeField] private SCE scePrefab;

这将向您显示编译器错误,其中您在其他代码中无意中将scePrefab设置为null。否则,您可能会在SEMCell内的任何位置将其设置为null,例如AwaitStart。尝试在代码中搜索scePrefab = null

答案 2 :(得分:0)

您发布的代码很好。两种可能性:

无论处理IAbstractCell是什么,都将scePrefab字段设置为空。

尝试将您的SCE字段设为私有和序列化:

[SerializeField] private SCE scePrefab;

这将向您显示编译器错误,其中您在其他代码中无意中将scePrefab设置为null。否则,您可能会在SEMCell内的任何位置将其设置为null,例如AwaitStart。尝试在代码中搜索scePrefab = null

或者,您正在销毁附加SCE脚本的对象。将该对象设为预制件,然后将预制件拖放到编辑器的插槽中。