首页 > 解决方案 > Unity C# 脚本抛出“您尝试实例化的对象为空”错误,但仅当脚本位于预制对象上时

问题描述

我有一个脚本设置为由动画事件调用来实例化一个对象。当脚本放置在场景中已经存在的游戏对象上时,这工作得很好;但是,当脚本放置在已实例化到场景中的对象上时,它不起作用。

例如:咖啡机使用脚本实例化咖啡杯(这有效)-> 咖啡杯然后实例化杯套(这会引发错误 ArgumentException: The Object you want to instance is null.)。脚本如下:

public GameObject product;//this part is always assigned in the inspector
private GameObject leftHand;
private GameObject barista;
private GameObject rightHand;


private void Start()
{
    leftHand = GameObject.FindGameObjectWithTag("LeftHand");
    rightHand = GameObject.FindGameObjectWithTag("RightHand");
    barista = GameObject.FindGameObjectWithTag("Player");
}

public void instantiateItemInHand()
{
    
   
    if (!barista.GetComponent<BaristaController>().leftHandIsFull)//left hand isn't full
    {
        Instantiate(product, leftHand.transform) ;//put the object in the left hand
        
    }
    else if (!barista.GetComponent<BaristaController>().rightHandIsFull)//right hand isn't full
    {
        Instantiate(product, rightHand.transform);//put the object in the right hand
        
    }

}

标签: c#unity3dinstantiation

解决方案


这实际上与动画事件有关。由于某种原因,实际事件在将它们相互复制的过程中变为空。


推荐阅读