Unity:在GameObject上实例化预制 - 错误对象为空

时间:2018-04-13 00:07:11

标签: unity3d instantiation gameobject

在我的Unity游戏中,我使用车辆预制件与Edy的车辆物理资产合作。我试图在GameObject的位置和旋转上实例化一个选定的车辆预制件。

在我的场景中运行我的代码以生成车辆时,我收到此错误

  

ArgumentException:要实例化的Object为null

     

ArgumentException:要实例化的Object为null。   UnityEngine.Object.CheckNullArgument(System.Object arg,System.String message)(在C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:239)   UnityEngine.Object.Instantiate(UnityEngine.Object original,Vector3 position,Quaternion rotation)(at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:151)   UnityEngine.Object.Instantiate [VehicleController](EVP.VehicleController原始,Vector3位置,四元数旋转)(在C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:206)   VehicleSpawner.spawnVehiclesInFirstGarage()(在Assets / Scripts / VehicleSpawner.cs:44)   HandleGarage.Start()(在Assets / Scripts / HandleGarage.cs:59)

script

车辆预制件是空的,因为用户将在游戏中选择车辆。 (即使我选择了车辆预制件,我仍然会得到相同的错误)

我在游戏对象上实例化车辆预制件的代码

public EVP.VehicleTelemetry telemetryComponent;
public EVP.VehicleController vehiclePrefab;
public GameObject spawnObject;

public void spawnVehiclesInFirstGarage ()
{
    // Load saved JSON
    string jsonData = SecurePlayerPrefs.GetString ("vehicleNames");

    // Convert to Class
    Database loadedData = JsonUtility.FromJson<Database> (jsonData);

    // Loop through Owned Vehicles Garage
    for (int i = 0; i < loadedData.vehicleNames.Count; i++) {

        // Set up instantiate
        var vehicle = Resources.Load("Prefabs/" + (loadedData.vehicleNames [i]));
        vehiclePrefab = vehicle as EVP.VehicleController;

        // Spawn vehicle on game object
        EVP.VehicleController newVehicle = Instantiate(vehiclePrefab, spawnObject.transform.position, spawnObject.transform.rotation) as EVP.VehicleController;
        telemetryComponent.target = newVehicle;
    }
}

1 个答案:

答案 0 :(得分:1)

可能的解决方案

  1. vehiclePrefab = vehicle as EVP.VehicleController;可能会导致问题,因为记录var vehicle = Resources.Load("Prefabs/" + (loadedData.vehicleNames [i]));已经提供Sport Coupe (UnityEngine.GameObject),这是正确的类型。

    不要使用as EVP.VehicleController,请尝试:

    // Set up instantiate
    var vehiclePrefab = Resources.Load("Prefabs/" + (loadedData.vehicleNames [i])) as GameObject;
    
    // Spawn vehicle on game object
    GameObject newVehicle = Instantiate(vehiclePrefab, spawnObject.transform.position, spawnObject.transform.rotation);
    EVP.VehicleController controller = newVehicle.GetComponent<EVP.VehicleController>();
    telemetryComponent.target = newVehicle;
    

    这是Unity's documentation for loading prefabs via scripting

  2. 从错误消息中,似乎spawnVehiclesInFirstGarage()中正在调用void Start()。如果是,请尝试将其放入void Update(),并添加if( prefab != null && !isInstantiated)支票。

  3. 其他故障排除(如果解决方案不起作用)

    • 尝试通过检查员分配预制件,看看是否遇到同样的问题。
    • 在现有代码上,尝试Debug.Log(vehiclePrefab)