- Home /
Acces a component on an instantiated object
Well here ou have my problem, I have an instantiated Prefab (BodyPart) by script that appears when i hit the play. This prefab it's instantiated by a Manager script attached to an empty GameObject who has all the game inside. Now, this Prefab (BodyPart) has a script attached call "Follow" as component and it's a C# script similar to "SmoothFollow". I know for sure that this script begins when i instantiate the prefab because y put a Debug.Log on start and works grate. What i need it's to tell this Script who has to Follow, in other words, the Target. But when i'm on Manager script with the instantiated prefab y make GetComponent and then try to access a public function on the script and i can't. HELPE ME PLEEEASE!!
Here you have my code
Manager Script
public class Manager : MonoBehaviour {
void Start () {
prefabTail = GameObject.Instantiate (Resources.Load("BodyPart",typeof(GameObject)))as GameObject;
prefabTail.transform.parent = this.transform;
prefabTail.GetComponent<Follow>();
prefabTail.FunctionIWantToAcces("Bodypart2");// It says NullReference
}
}
Follow Scrpt
public class Follow : MonoBehaviour { void Start() {
}
public void FunctionIWantToAcces(string targetName) { GameObject targetLoaded = GameObject.Find(targetName); target = targetLoaded.transform;
}
}
PD: sory if i have english problems i'm From Argentina we speak spanish :p
are you instantiating multiple objects? or just the one?
english protip: access is usually written with a double s :)
i'll instantiate multiple objects in the future, but now i just need one
for the love of all that is good, please fix the spelling of acces to access so this comes up trumps in a search. I stumbled on this, but later will need it.
Answer by KvanteTore · Mar 24, 2010 at 07:34 PM
It looks like you want to call the FunctionIWantToAcces method on the Follow component, but you are trying to call FunctionIWantToAcces on the Manger component. You should get an instance of the Follow object and call FunctionIWantToAcces on that instance.
void Start () {
prefabTail = GameObject.Instantiate (Resources.Load("BodyPart",typeof(GameObject)))as GameObject;
prefabTail.transform.parent = this.transform;
Follow tailComponent = prefabTail.GetComponent<Follow>();
tailComponent.FunctionIWantToAcces("Bodypart2");
}
HEYYY!!! this was perfect thanks!!! i understood how GetComponent works now XD
Your answer
Follow this Question
Related Questions
Not understanding GetComponent with prefabs 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Determine if an external prefab exists within the project 's assets folder (not in scene) 2 Answers
cloned game object wont call script right... 2 Answers
How to make sprites instantiate based on randomly generated integer? 1 Answer