简体   繁体   English

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

[英]Unity C# script throws “object you're trying to instantiate is null” error, but only when the script is on a prefab object

I have a script set up to be called by an animation event to instantiate an object.我有一个脚本设置为由 animation 事件调用以实例化 object。 This works just fine when the script is placed on a GameObject that is already in the scene;当脚本放置在场景中已经存在的游戏对象上时,这工作得很好; however, it does not work when the script is placed on an object that has been instantiated into the scene.但是,当脚本放置在已实例化到场景中的 object 上时,它不起作用。

ex: coffee brewer instantiates a coffee cup using the script (this works) --> that coffee cup then instantiates a cup sleeve (this throws error ArgumentException: The Object you want to instantiate is null.).例如:咖啡机使用脚本实例化咖啡杯(这有效)-> 咖啡杯然后实例化杯套(这会引发错误 ArgumentException:您要实例化的 Object 是 null。)。 The script is as follows:脚本如下:

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
        
    }

}

This actually had to do with the animation events.这实际上与 animation 事件有关。 For some reason, the actual events had become null during the process of copying them over to one another.由于某种原因,实际事件在相互复制的过程中变成了 null。

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

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