- Home /
How should one give a gameobject to a prefab?
I have a prefab, and I have a gameobject in the scene which contains a script which I would like the prefab to access. As one cannot drag the gameobject in the scene on to a slot in the prefabs inspector what is the best way to go about this?
Answer by getyour411 · Feb 07, 2014 at 03:50 AM
C# in Start()
go = GameObject.FindObjectWithTag("theTag").GetComponent<theScript>();
where theTag is the tag of the GameObject, use transform.Find or whatever else is needed if the tag isn't unique. Assuming you want to access a script on the GameObject, replace theScript with the script name; get rid of that bit if you don't care.
I was under the impression that findwithtag was very slow and that it should generally be avoided. Is there a better way to do this or am I wrong in my belief?
$$anonymous$$y sugggestion said in Start() to begin with. $$anonymous$$ore importantly though, "very slow" is a misconception. It's a tool, and used correctly it's fine. Now if you are putting that into Update() or something that's being executed non-stop, ok. But you don't specify how you are using this. You could setup the instantiator to pass a reference to a method in the prefab and bypass a Find. There's lot of tools.
Thank you for responding... I didn't notice that you specified that it should be put in start.
Your answer
Follow this Question
Related Questions
Instantiate question 1 Answer
Passing More Then One Int Into Another Script As A GUI 0 Answers