c# - 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
}
}
解决方案
这实际上与动画事件有关。由于某种原因,实际事件在将它们相互复制的过程中变为空。
推荐阅读
- react-native - Reactnative TypeError 中未显示特定页面的 Json 数据:
- r - R 中的 plotly 包如何从没有人脸信息的顶点信息创建实体 3D 网格
- php - 如何从指定文件夹中获取多个单独的旋转随机图像
- android - 在回收站视图中,如何确定单击的单选按钮来自 Android 中的同一个单选组
- .net-core - OData 日期过滤器返回损坏的 json
- java - 如何读取资源文件夹中的文件
- regex - 如何通过正则表达式从头到尾搜索字符串
- scala - 为什么 Java HashMap put 在 Spark Scala 中不起作用?
- jmeter - 无法在 JMeter 中使用 SSH SFTP 采样器获取文件
- firebase - Firebase 查询未按预期工作 React native