![](/img/trans.png)
[英]Trouble instantiating prefab object by calling function in external script (Unity/C#)
[英]Unity C# script throws “object you're trying to instantiate is null” error, but only when the script is on a prefab object
我有一个脚本设置为由 animation 事件调用以实例化 object。 当脚本放置在场景中已经存在的游戏对象上时,这工作得很好; 但是,当脚本放置在已实例化到场景中的 object 上时,它不起作用。
例如:咖啡机使用脚本实例化咖啡杯(这有效)-> 咖啡杯然后实例化杯套(这会引发错误 ArgumentException:您要实例化的 Object 是 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
}
}
这实际上与 animation 事件有关。 由于某种原因,实际事件在相互复制的过程中变成了 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.