- Home /
Instanitate Object with predefined script transforms
I know of no other way to word this question, then how i have. When instantiate a object, i want it to instantiate with it's scripts, and to have the Transforms i set in the script to be already set. By this, i mean i want to be able to spawn a enemy who, as soon as spawning, will know his target is the player. So any help would be appreciated.
Answer by Ashkan_gc · Feb 16, 2010 at 05:06 AM
simply create a GameObject and add all scripts that you want to it and set all values to what you want. then create a prefab in menu assets/create/prefab. drag your gameObject to the prefab and delete the gameObject. now use this prefab for instantiation. in the script that you want to instantiate the enamy define a variable like
var enamy:GameObject;
in the inspector drag the prefab to this variable in the GameObject that has this script attached. then use the Instantiate method to spawn the enamy where you want. if the initial position should be defined in code you ca do that in Awake or Start functions.
So you are saying i should define them as GameObject rather then Transform?
you can use the second argument of instantiate to tell where to create the objet and also you can set the position in code of Start function. you can only set scripts of gameObjects and transforms don't have scripts becausee they are components themselves. use prefabs! they are great reusable components and help you when you want to change all instances of an object.
I already use prefabs. The code i use now is: var target : Transform; I was wondering if you mean to change it from Transform to GameObject.
there is no difference because all gameObjects has transforms and you can not drag any transform that is not a gameObject. the difference comes in when you use another component type that is not available in all gameObjects. for example you might use WheelCollider or Rigidbody in the inspector to force yourself and other users to drag a gameObject that has a WheelCollider attached.