- Home /
Get Component from Instantiated Prefab
I need to instantiate a target and player then get the camera mouse control script and set its target to the player. In the code below, the Get Component script returns null. Is there a way to get a component from an instantiated prefab? Any help is appreciated.
SceneObjectData.CurrentSceneObjects.MainCamera = Instantiate(SceneObjectData.SceneObjectPrefab.MainCamera_Prefab) as GameObject;
SceneObjectData.CurrentSceneObjects.adventurer = Instantiate(SceneObjectData.SceneObjectPrefab.Adventurer_Prefab) as GameObject;
//Target the Adventurer with the point camera script CameraMouseControl CameraMouseControlScript;
CameraMouseControlScript = SceneObjectData.CurrentSceneObjects.MainCamera.GetComponent("CameraMouseControl") as CameraMouseControl; CameraMouseControlScript.target = SceneObjectData.CurrentSceneObjects.adventurer;
Answer by doug__ · Nov 25, 2012 at 03:07 PM
I do this when ever I try to get a component, and I'm not sure if it exists, perhaps it's what you're looking for:
public MyScript GetScript(GameObject i) {
var c = i.GetComponent<MyScript>();
if (c == null) {
i.AddComponent<MyScript>();
c = i.GetComponent<MyScript>();
}
return c;
}
Thanks Doug. The thing is I can see the script attached in the prefab (in the assets folder). I can do something similar in the Start function of the Camera$$anonymous$$ouseControl script attached to the instantiated object. But I have to use GameObject.Find (like below) which I've heard is slow.
void Start () {
if (target == null) { GameObject adventurer = GameObject.Find("adventurer"); target = adventurer; } }
Your answer
Follow this Question
Related Questions
Accesing script from newly instantiated game object 1 Answer
Change assigned prefab from script 3 Answers
How to access script variables attached to a prefab at runtime in Javascript? 2 Answers
How to reduce usage of GetComponent()? (instantiate, prefabs) 0 Answers
Instantiating Prefab from Javascript - BCE0005: Unknown identifier: 'Prefab' 2 Answers