- Home /
C# Extending Script causes InvalidCastException on Instantiate
This line works in the original script, but bugs(InvalidCastException) when run on the extended script.
Transform obj = (Transform) Instantiate(projectile,loc,transform.rotation);
Any ideas? Thanks in advance.
Digged around for a bit, restarting Unity does not solve the problem.
It is probably instantiating it as a gameobject, not a transform. Cast it as a gameobject, then set obj to the gameobject's transform property.
GameObject g = (GameObject)GameObject.Instantiate(); Transform obj = g.transform;
Thanks for the answer. I tried this before, but it didn't work for me.
Answer by aldonaletto · Dec 03, 2011 at 07:46 PM
Instantiate returns an object of the same type of the prefab variable. You can change the prefab variable type to Transform:
Transform projectile; // drag the projectile prefab here ... Transform obj = Instantiate(projectile,loc,transform.rotation);The prefab variable type may be equal to any component present in the prefab object, like Rigidbody, Collider, Transform, GameObject etc., thus using GameObject or Transform will work in any case, the only difference being the type returned by Instantiate.
Thanks, changing the projectile's type to Transform fixes the problem.
I seems that C# is much stricter on types and typecasting than UnityScript. I like it. :)
Yes, C# doesn't assume anything to easy your life - everything must be explicitly defined. I consider C# too cranky for a script language, but this helps to avoid some errors. If you know exactly what you're doing, Unityscprit is easier to use; if not, C# is safer - and you learn a lot, because everything is explicit: you can see that each script becomes a new type (a class) with variables and code defined inside, for instance, and many other things that Unityscript does behind the scenes.
In case anyone else searches for this. I ran into the same error for a different reason. I was Instantiating something from a loaded resource like this:
return (GameObject)GameObject.Instantiate((GameObject)Resources.Load(aIdentifier));
And I had I script and a Prefab named the same thing. So unity was defaulting to instantiating the script and (obviously) saying it was an invalid cast.
Your answer
![](https://koobas.hobune.stream/wayback/20220613061740im_/https://answers.unity.com/themes/thub/images/avi.jpg)