- Home /
Assign Transform from Hierarchy to Prefab script
Hey Everyone
I'm just getting started with Unity, right now I'm working on an iPhone project to learn the basics.
I am having some trouble with script variables though, and I'm sure it's just that I am learning as I stumble through each aspect. I have an enemy game object which has a script attached to it for the AI. This AI currently just tells it to chase a transform variable, which I then dragged my Player transform into. So everything seemed to be working great with the single enemy.
I then created an enemy prefab from the original, and setup a sphere collider to spawn a new prefab enemy when the player enters it. The problem is that the enemy prefab's AI script does not have the player transform assigned, so he just stands there after being created. I tried assigning the player transform as the default value, but this isn't allowed.
I know I must be missing something, and perhaps I'm going about this wrong. Any suggestions would be greatly appreciated.
Thanks!
Answer by Rennat · Dec 04, 2010 at 05:58 PM
After you instantiate a prefab you can save a reference to that instance, then get the enemy script component of the new instance (EnemyScript
in the example below) and access any public variables or methods.
Javascript:
var newEnemy : GameObject; newEnemy = Instantiate(prefab, position, rotation);
var enemyScript : EnemyScript; enemyScript = newEnemy.GetComponent(EnemyScript);
enemyScript.targetTransform = transform;
I'm having a little trouble implementing this code, as I'm pretty novice with Javascript.
I think I understand everything except what to do with the last line. I believe that I should be assigning the transform of the player, but I'm not sure exactly how to do this.
For example the transform I want to assign the "target" variable to is named on the gameObject "Player". Can't figure out how to do that through code.
Never$$anonymous$$d I think I figured it out, added another transform variable to the spawn object of type transform, and put my player there, then just assigned the enemy script target to it, and it works.
Thanks!