Instantiating from project folder

Hi, I read about the Resources.Load method, to instantiate prefabs that do not exist in the game view yet.

The idea is to instantiate a vehicle:

var prefab : GameObject; 
prefab = Resources.Load("vehicle");
Instantiate(prefab);

On the root folder of my project, inside Unity, I have created a folder called ‘Resources’, and moved the prefab named ‘vehicle’ to this folder, but I get the error: “Cannot cast source type to destination type” on line 2. What am I doing wrong?


Further; when I drag a prefab from Project view to scene view, that has the following hierarchy:

  • truck
    ---- truck_front
    ---- truck_back

…my prefab is ‘flattened’ in the hierarchy and displayed as:

  • truck_front
  • truck_back

Now being two seperate objects, how can I target my script to the parent? I want to instantiate the whole “truck”, but I since it is flattened, I can only refer to the “truck_front” object or “truck_back” object.

Thank you.

try specifying the type:
prefab = Resources.Load(“vehicle”, GameObject);

Do you have a screenshot of your hierarch, both project view and hierarchy

Hi there!

As you can see my Prefab has a hierarchy.
But when dragging this Prefab “vehiclePrefab” onto the Scene View, it ‘flattens’ and I can’t refer to its original name.

But let’s discuss the other situation, instantiating from the project folder:

Your suggestion (specifing the type) worked. But, only the Front of my truck is spawned, not ‘vehiclePrefab’ which contains both the front and back.

The front b.t.w is the small cube, the back is the large cube.

When you uploaded the prefab you added two seperate game objects to the prefab, but no common root around it.

So just add a empty game object containing the two game objects in the hierarchy and drag that on the prefab to upload it.

I never came across this problem since my prefabs only contained 1 element until now.

Seems logic…as soon as you know this.
Perhaps this is something to add in the documentation? Because visually, my prefab seemed to be okay (hierarchy wise).