- Home /
Get .prefab (object from unity) with component from assets.
Hello. I have a object with script components on it and put in Assets/Ingame Models folder. And i need to access his scripts in another script on object that is in unity not in assets folder. How can i do that? here is what i tried to do i found it on the internet:
enemyinfo = Resources.LoadAssetAtPath ("Assets/Ingame Models/Enemy.prefab", typeof(GameObject)).GetComponent<EnemyHealth> ();
But getcomponent is red that means it does not work. How do i access it then? i am using unity 5 beta pro.
And gameobject.find does not work its only for ingame objects.
Resource.Load will work only if your prefab is under Resources folder. If you don't have a Resources folder, create one, name it Resources and move the prefabs there.
var enemyInfo = Resources.Load("$$anonymous$$odels/Enemy") as GameObject;
var script = enemyInfo.GetComponent<YourScript>();
Note that you don't have to add the extension after the prefab name.
Neamtzu is correct; if you are loading an asset using Resources.LoadAssetAtPath your files need to live at Assets/Resources/ and you must exclude the file name.
However, if you ins$$anonymous$$d create a public GameObject or public Transform property as written below, you can simply drag the desired GameObject into the script which is spawning new instances. I$$anonymous$$HO this is better, because the Assets/Resources folder is always included in your project, regardless of if items in it are referenced or not.
Answer by tigertrussell · Mar 17, 2015 at 04:21 PM
You need to create a Prefab, which you can do by right-clicking in the folder that you want, hovering over Create and selecting Prefab. Then, drag-and-drop the GameObject from your scene directly onto this new Prefab and give it a name.
Then check out the Instantiate documentation to see how to create an instance of that Prefab. So long as your Prefab has a Transform component, you can use a public Transform property of a class and drag the Prefab directly from the file browser onto the property of the script which will be spawning your prefab, and do something like on the example page:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Transform prefab;
void Example() {
int i = 0;
while (i < 10) {
Instantiate(prefab, new Vector3(i * 2.0F, 0, 0), Quaternion.identity) as Transform;
i++;
}
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
"Save As..." Saving level assets at Runtime 0 Answers
Low FPS in android game if using MK glow free asset 0 Answers
Create 3d hexagonal terrain 1 Answer