That doesn’t compile for me. I suspect you are thinking of something more like:
MyComponent prefab;
MyComponent comp = Instantiate(prefab) as MyComponent;
(I changed the type of the “prefab” variable.) This second version works because the Instantiate() function has a generic version, public static T Instantiate(T original)
which lets you use a component-type variable as the thing you want to clone and then returns the same component-type. In fact, the “as MyComponent” part is redundant and doesn’t do anything, because the return type is already MyComponent before the cast.
Because it’s not the same type, you are try to make an Box into an Apple.
GameObject = Box
Componnent = Apple
//a blueprint of a Box with an Apple attached to it
GameObject prefab;
//GameObject obj is an empty Box no identity
//so I create a new Box with an Apple out of the blueprint and make obj become the new box i just created
GameObject obj = Instantiate(prefab);
//MyComponent comp is an empty Apple also no identity so I get the Apple from obj box and give an identity to comp
MyComponent comp = obj.GetComponent<MyComponent>();
//if obj box doesnt have an apple, MyComponent comp will never have identity
//a blueprint of a box with an Apple attached to it
GameObject prefab;
//MyComponent comp doesn't have identity so I create a box out of the blueprint and
//magically turn into an apple now MyComponent comp is a Apple? hm....... that doesnt seem right.... say the debugger
MyComponent comp = Instantiate(prefab) as MyComponent;
//turn an empty apple into a empty box that has been turn to an apple. Angry error messenger
MyComponent comp = obj as MyComponent;
This is reason why I asked this question. Because it doesnt seem right but it should work. This is what they do in this tutorial…or is it? I just noticed that second example should have been this:
MyComponent prefab;
MyComponent comp = Instantiate(prefab) as MyComponent;
Now Im super cofused. They make prefab and put it into Maze type field in the inspector? Maze is supposed to be component type, no?