- Home /
Enemy targeting player in different scene
Hi . How do i make enemy from another scene to target the player. My scene is like this, the player will destroy all enemy and when all enemies are destroyed the portal will open and the player will be transported to scene 2 and my enemies in scene 2 is supposed to look at the player which is not because i deleted the camera and the player in scene2 and used DontDestroyOnLoad(gameObject) so that the player in scene 1 will not be destroyed when entering to scene 2. I tried searching but i didn't find any.
Here's my script to my enemy:
var distance;
var target : Transform;
var lookAtDistance = 45.0;
var attackRange = 25.0;
var moveSpeed = 3.0;
var damping = 6.0;
var bullitPrefab:Transform;
var savedTime = 0;
private var isItAttacking = false;
function Update ()
{
if(transform.rotation.x!=0){
transform.rotation.x=0;
}if(transform.rotation.z!=0){
transform.rotation.z=0;
}
distance = Vector3.Distance(target.position, transform.position);
if(distance < lookAtDistance)
{
isItAttacking = false;
lookAt ();
}
if(distance > lookAtDistance)
{
}
if(distance < attackRange)
{
attack ();
}
if(isItAttacking)
{
}
}
function lookAt ()
{
isAttacking = true;
var rotate = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damping);
var seconds : int = Time.time;
var oddeven = (seconds % 2);
if(oddeven)
{
Shoot(seconds);
}
}
function attack ()
{
isItAttacking = true;
moveDirection = transform.forward * moveSpeed;
GetComponent(CharacterController).SimpleMove(moveDirection);
}
function Shoot(seconds)
{
if(seconds!=savedTime)
{
var bullit = Instantiate(bullitPrefab ,transform.Find("spawnPoint").transform.position ,
Quaternion.identity);
bullit.gameObject.tag = "enemyProjectile";
bullit.rigidbody.AddForce(transform.forward * 3000);
savedTime = seconds;
}
}
Any help would be appreciate.
Answer by Baste · Oct 24, 2014 at 02:24 PM
In the enemy's Start, use the Find method to find the player - either through the player object's name, tag or script Type. Assign the player as the enemy's target.
So, if your main character object is named "Player", you do this:
function Start() {
target = Find("Player");
}
That should fix your problem.
i got an error Assets/Script/Js/PA_DroneCrontrol.js(13,18): BCE0005: $$anonymous$$ identifier: 'Find'.
Its a GameObject Static Function. GameObject.Find("Player");
i tried to change the var target to GameObject and change the code at start target = GameObject.FindWithTag("shooter"); but i got a null reference at line 19. Everytime i enter scene 2
Your answer
Follow this Question
Related Questions
enemy targeting player in different scene 1 Answer
How can I load a scene when the enemy hits the player? 5 Answers
Enemy spawn then select target? 1 Answer
Enemy does not look the player 2D platformer. 1 Answer
Kill the Player? 1 Answer