- Home /
Getting the Player in a Script!
So what I am trying to do is that player = (Person with the tag "Player") Instead of a GameObject!
And this should be done in the Start Method. If you do not understand this it should be like this..
public Transform player;
void Start()
{
player = tag("Player")
}
This is my script if this helps!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyChase : MonoBehaviour {
public float distanceToPlayer;
public Transform player;
public Animator anim;
public float rotationSpeed = 2f;
void Start ()
{
anim = GetComponent<Animator>();
player = tag("Player"); // Doesnt work
}
void Update ()
{
Vector3 direction = player.position - this.transform.position;
float angle = Vector3.Angle(direction, this.transform.forward);
if (Vector3.Distance(player.position, this.transform.position) < 15 && angle < 280)
{
direction.y = 0;
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
anim.SetBool("IsIdle", false);
if(direction.magnitude > distanceToPlayer)
{
this.transform.Translate(0, 0, 0.16f);
anim.SetBool("IsWalking", true);
anim.SetBool("IsAttacking", false);
}
else
{
anim.SetBool("IsAttacking", true);
anim.SetBool("IsWalking", false);
}
}
else
{
anim.SetBool("IsIdle", true);
anim.SetBool("IsWalking", false);
anim.SetBool("IsAttacking", false);
}
}
}
Thanks for the Help!
Answer by Commoble · Apr 21, 2017 at 10:21 PM
GameObject.tag
is a member variable, not a function. Do this instead:
this.player = GameObject.FindWithTag("Player").transform;
You can read the documentation for FindWithTag() here.
I wanna Thank you a lot! Because this is currently working perfectly fine!
Thanks!
Answer by Razputin · Apr 22, 2017 at 01:57 AM
player = GameObject.FindWithTag("Player").transform;
Why do you want your players transform though? Might be easier to just grab the whole thing instead.
Public GameObject player;
player = GameObject.FindWithTag("Player");
Then if you want to call the transform anywhere just call
player.transform;