- Home /
How can I set a Transform Variable in a Prefab?
I have a prefab that is using transform.LookAt(target); and var target : Transform; So it will always look at the main character. My issue though is that I want to be able to instantiate this prefab during the game, and I can't find a way to set the target value to MainCharacter. I can do this after its in the scene through the GUI, but not through scripting. I've tried target = transform.Find(:mainCharacter"); and MainCharacter is the object I want my object looking at. I'm thinking I may have to try to declare a global variable from one script and call it up here but I don't really know how to approach that. If anyone can explain the correct way of doing this, thanks a bunch :)
transform.Find will only search in the childs of this transform. almo's way is what you want ;)
Answer by almo · Jun 17, 2011 at 05:53 PM
If you're sure you will only ever have one MainCharacter, you could use GameObject.Find, and use the name of it to find it.
http://unity3d.com/support/documentation/ScriptReference/GameObject.Find.html
This is a slow function, so you should get this result in Awake or Start, and save it in a variable.
it's worth noting that putting it in awake or start won't matter if you're instantiating the prefab. it'll still call GameObject.Find in the middle of gameplay since those built-ins aren't called until a gameObject exists. But yeah, in that situation you're SOL anyway, so you might as well have it in Awake or Start ;P
You want it in Awake or Start ins$$anonymous$$d of Update so it is not done every frame.