1
votes

I'm just starting out with Unity and for my first game I'm trying to make these enemy cubes chase the player. The enemies are spawned at a random position and I'm trying to make them move towards the position of the player cube. But when I try to reference the player's Transform, it won't let me drag it on top, any fixes?

using UnityEngine;

public class enemyFollow : MonoBehaviour {
    public Transform player;
    public Rigidbody rb;
    public float movementForce;

    // Update is called once per frame
    void FixedUpdate()
    {
        if (player.position.x > transform.position.x){
            rb.AddForce(movementForce * Time.deltaTime,0,0);
        }
        if (player.position.x < transform.position.x){
            rb.AddForce(-movementForce * Time.deltaTime,0,0);
        }
        if (player.position.z > transform.position.z){
            rb.AddForce(0,0,movementForce * Time.deltaTime);
        }
        if (player.position.z < transform.position.z){
            rb.AddForce(0,0,-movementForce * Time.deltaTime);
        }
    }
 }

Unity won't let me drag the player from the gameobjects window onto the script on the prefab. The error says "the variable player of enemyFollow has not been assigned" It won't let me assign Player.

2
Is this question about UnityScript (a deprecated programming language derived from Javascript and created for Unity) or about C# (a completely different programming language)? To me it looks like C#, so I've removed the [unityscript] tag. - Llama
Are you dragging the player object that is on the scene view or the player prefab file? - Samuel

2 Answers

1
votes

You can add this in a void Start() method:

player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
1
votes

If I'm understanding correctly, you're trying to assign the player to the enemy in the prefab configuration. That won't work because the prefab isn't in the scene. Since the prefab could be instantiate in any scene, you can't reference scene objects. You need to do it during playtime, unless all the enemies are already in the scene when you're setting it up (in which case you'd need to do it to an instantiated enemy and then copy paste it).

You can use FindGameObjectWithTag() as in Jeff's answer, but make sure to assign a "Player" tag to the player GameObject or prefab.

Another method which I'd recommend would be to have whatever is instantiating the enemies assign their target, that way you don't need to search for a tag with a string you could mistype, and you can just change the reference in one place when you need to change something.