- Home /
Enemy behavior is not working after the enemy has spawned.
Hi
When I spawn my enemies using Instantiate function, they work as "normal". They are attacking, but not me. They are attacking the point where my player spawned. I do not have any GameObject that is there (that is related to the player). They work as usual otherways. I setted the Prefab up, and everything in it could work. And the original enemy works normal (if that is helpful for any reason). How can I fix this?
Is the target set to the same GameObject as the original enemy?
Yes. It is set to the player Prefab. And the player I am using is that Prefab.
Answer by Berenger · Feb 03, 2012 at 09:00 PM
It's going to be hard to fix without more information about the way you're doing your AI, but I can guess : When the enemy spawn, does he get a reference to Transform of player, or just a Vector3 ? Because the second one won't be updated over time.
[Edit after reading your comment] You are confusing your player's prefab, which is a file on your computer, and it's instantiation, (is that a word ?) which is some memory space depending on the scene, based on that prefab file. So when you move your player, the prefab remain the same. Conclusion, you must reference the instantiated player, not the prefab one.
First I have a Transfrom variable. Then one Transfrom inside the Update function. I use Quaternion.Slerp, so it says that it could rotate towards the target. And when the player comes close enough. The target equals the player (target = player;).
Well, I had it like this before. And it worked... But you mean that I have to put so the target is a "player = player.transfrom" or "player = GameObject.Find("Player")". But that will cause an error. Because the player is a Transform. But it will check after the active player, not the player Prefab. Or is there a better way?
Funny thing about components, if you have Transform player; and if player != null, player.transform won't give an error, but player.transform.transform.transform.transform.transform won't either, it's just going to perform the GetComponent several times.
With that said : You need to find the player's game object, then acces it's Transform. Here is some code, to get rid of all that name confusion :
GameObject playerGameObject = FindObjectWithTag( "Player" ); Transform playerTransform = playerGameObject.transform;
Note that I'm not used to javascript, you might have some mistakes. Find an object with tag is much faster than by name, so make sure your player game object has the right tag. And don't do this in Update, but in Start/Awake.
Your answer
Follow this Question
Related Questions
Creating basic enemy animation and attacking 4 Answers
Enemy AI help. 0 Answers
enemy ai going to player 2 Answers