Search code examples
unity-game-engineunityscript

Unity 5 // when enemy spawns , Enemy target is none?


I've got a basic AI script where I'll assign an object for the enemy to chase. The problem is, when I turn the enemy into a prefab, the target assignment becomes blank and I cannot alter it while it's a prefab. I've tried to assign the object within the code itself but I'm not completely sure how to do so (I've tried a number of things but nothing has panned out).

Any tips on how to fix the first problem, or just how to assign a target within code would be very helpful. JavaScript would be the preferred language for code.

enter image description here


Solution

  • It's the intended behaviours of prefabs.

    You can't link a gameobject which belongs to the scene, to a field of a prefab in your assets since it must be completely independant from any instance of your scene. Prefabs are intended to be instantiated, and then, you will be able to assign (through code) the public field you want to your instantiated enemy. See a prefab as a file in your HDD you can instantiate from.

    Without any code it's hard to help, but I guess you can do something similar to this :

     var newEnemy : EnemyAI = Instantiate(enemyPrefab);
     newEnemy.target = GameObject.FindWithTag ("Player").GetComponent.<Transform>();
    

    I'm not fluent at all with Unity script.


    You are still able to "instantiate" the enemies directly in the scene by dragging and dropping the prefab into your scene, and you will be able to assign the Target of your instantiated prefab.