WoShiNiBaBa
WoShiNiBaBa

Reputation: 267

How to attach a prefab to a GameObject programmatically?

I'm new to Unity. Trying to load/attach an .obj file (downloaded and saved in my file system) to a game object in Unity. I've tried using the following code but I have got an error.

Resources.Load(My_File_Path).transform.parent = targetGameObject;

The error I got:

error CS1061: Type UnityEngine.Object' does not contain a definition fortransform' and no extension method transform' of typeUnityEngine.Object' could be found. Are you missing an assembly reference?

Upvotes: 0

Views: 7617

Answers (3)

Technivorous
Technivorous

Reputation: 1712

creating a game object from a prefab at run-time requires you to instantiate the object.

first, to instantiate a prefab you dont need to worry about the transform just yet....

when using Resources.Load -you are going to need to make sure you have a Resources folder in your project. if not make one.

note that i then make a sub folder in the resources folder called Prefabs. you dont have to though.

in your resources folder, you can place your prefab item. (drag and drop the finished item from your scene) once you have the prefab its safe to delete if from your scene.

now the code is:

GameObject yourobject = Instantiate(Resources.Load("thenameofprefab") )as GameObject;

you now have your prefab item in the gameobject yourobject, and can manipulate its transform and rotation freely.

if you make a prefab folder in your resources folder, the method would be

GameObject yourobject = Instantiate(Resources.Load("Prefabs/thenameofprefab") )as GameObject;

hope this helps.

p.s. you can set the transform and rotation on that instantiation line, you just need to check the overloads to see how to use it!

Upvotes: 1

Boga
Boga

Reputation: 13

If I understand the question correctly, you first need to create a prefab from your object. Drag to the scene and then put created GameObject in your assetes. You can create public GameObject prefab; in your class. Then instantiate it like that: GameObject obj =Instantiate(prefab, Vector3.zero), Quaternion.identity);
And then you can attach it like you did it before: obj.transform.parent = targetGameObject;

Upvotes: 0

Serlite
Serlite

Reputation: 12258

You seem to have loaded your prefab correctly, but the problem is that you're not handling an instance of the prefab - you're handling the prefab itself, which is an Object and not a GameObject.

Before you can access GameObject-specific members such as transform, you need to Instantiate() your prefab. This method accepts an argument of type Object, so pass in your prefab reference and assign the resultant GameObject instance as a child of targetGameObject:

Object prefabReference = Resources.Load(My_File_Path);
GameObject gameObjectReference = Instantiate(prefabReference) as GameObject;
gameObjectReference.transform.parent = targetGameObject;

Upvotes: 4

Related Questions