- Home /
Instantiate a prefab and initialise some of its properties?
Hi all,
I'm a noob and have be learning about prefabs today. I have a prefab to which I have attached a script that exposes three public properties (and I can see these in the property inspector of the prefab).
I know how to instantiate a prefab in code, and I was kind of hoping I could access the three public properties via the GameObject that is returned from my prefab instantiaion call, but that doesn't seem to work.
Whats the cleanest way for me to initialise those three properties of the prefab after it is instantiated?
Answer by simubrett · Mar 15, 2012 at 12:48 PM
All you need to do is typecast your instantiated GameObject, so that your script knows the thing you instantiated isn't just a normal GameObject:
MyNiftyObject mno = (MyNiftyObject)GameObject.Instantiate(MyNiftyPrefab);
mno.AwesomeProperty = 3.0f;
I've had bad experiences doing it that way... better to just use GetComponent.
This will work fine if ´$$anonymous$$yNiftyPrefab´ is of type ´$$anonymous$$yNiftyObject´.
GetComponent's a completely valid way to do it, too. This was just the first way I'd learned to do it, and it's never caused me any problems. Are there any major problems I should be aware of?
Your answer
Follow this Question
Related Questions
When is Awake called on an inactive gameobject 3 Answers
Instantiating Child - Prefabs 1 Answer
Access Child of instantiated UI-Prefab using C# in Unity Beta 4.6 1 Answer
Instantiating a prefab through C# script 0 Answers
prefab question 1 Answer