Search Unity

Instantiating prefab as it's script gives Invalid Cast Exception

Discussion in 'Prefabs' started by Raali_Oloth, Jun 30, 2018.

  1. Raali_Oloth

    Raali_Oloth

    Joined:
    Jul 29, 2013
    Posts:
    22
    Hi all!
    if i instantiate prefab with specific parent it will give an Invalid Cast Exception, why?
    Is something changed with new prefab system?

    Code (CSharp):
    1. // assuming that pUnit is Unit prefab from project folder
    2. // and world is some already set Transform
    3. public Unit pUnit;
    4. public Transform world;
    5.  
    6. void Start()
    7. {
    8.     Instantiate(pUnit, Vector3.zero, Quaternion.identity, world);
    9. }
    workaround for now is SetParent after instantiating without initial parent
     
    Last edited: Jun 30, 2018
  2. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    443
    The exception should give you a little more information about which parameter can't be cast.
    What is Unit derived from? and what do you assign to it and how?

    Need a little more information to help or to determine if it is a bug.
     
  3. Raali_Oloth

    Raali_Oloth

    Joined:
    Jul 29, 2013
    Posts:
    22
    It can be any class, even Camera (for example i can drag n drop camera to public Camera variable then instantiate it same way and it will throw an exception)

    Unit is just a class derived from MonoBehaviour and saved as prefab, then assigned to pUnit variable in Gameplay object on test scene

    can't get any info about cast from console window (

    InvalidCastException: Specified cast is not valid.
    UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation, UnityEngine.Transform parent) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.bindings.cs:226)
    UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation, UnityEngine.Transform parent) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.bindings.cs:293)
    Gameplay.spawnUnit (Unit pUnit, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at Assets/Scripts/Scenes/Gameplay.cs:14)
    Gameplay.Start () (at Assets/Scripts/Scenes/Gameplay.cs:32)
     
    Last edited: Jul 2, 2018
  4. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    443
    Do you have a small project that reproduces the issue which you can share?
     
  5. Raali_Oloth

    Raali_Oloth

    Joined:
    Jul 29, 2013
    Posts:
    22
    Yeah, you can launch SampleScene, unity 2018.2.0x
     

    Attached Files:

  6. JakubSmaga

    JakubSmaga

    Joined:
    Aug 5, 2015
    Posts:
    416
    Same problem here.
     
  7. rbisso

    rbisso

    Joined:
    Jul 13, 2011
    Posts:
    26
    Did we ever get a resolution here? It'd be cool to see the follow-up!