Home>

I am making a 2D shooting game with Unity.
I now go to the player position with vector3.
I would like to make a specification where the enemy automatically hits the bullet, gets the player's location once, and goes to the player.

Error message

When enemies hit bullets, they will gather in the middle without going to the player.

Applicable source code

Language used
c #
Source code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemybullet: MonoBehaviour
{
GameObject Player;
// public Transform Enemybullet;

public float speed = 3.0f;// movement speed]

public Vector3 PlayerPos {get;private set;}

// Start is called before the first frame update
void Start ()
{
// get player object
this.Player = GameObject.Find ("Player");
GetComponent(). Velocity
= new Vector2 (0, speed);

Destroy (gameObject, 3.0f);

Vector3 PlayerPos = this.Player.transform.position;

}

// Update is called once per frame
void Update ()
{

// float step = speed * Time.deltaTime;
//Enemybullet.transform.position = Vector3.MoveTowards (Enemybullet.transform.position, Player.transform.position, step);

float ENEMY_MOVE_SPEED = 0.05f;

// Move in the direction of the player
transform.position = Vector3.MoveTowards (transform.position, PlayerPos, ENEMY_MOVE_SPEED);

}
}

When I put vector3 player pos in updete, it always came to me.

Supplemental information (FW/tool version etc.)

unity2019.2.9f1

  • Answer # 1

    Isn't this because the

    Start method has been declared and assigned asVector3 PlayerPosas a local variable and the member variable PlayerPos has not been initialized?

    // Start is called before the first frame update
    void Start ()
    {
    // get player object
    this.Player = GameObject.Find ("Player");
    GetComponent(). Velocity
    = new Vector2 (0, speed);
    Destroy (gameObject, 3.0f);
    // ❌
    // Vector3 PlayerPos = this.Player.transform.position;
    // ⭕
    PlayerPos = this.Player.transform.position;
    }

  • Answer # 2

    I think this should be done

    public Vector3 PlayerPos {get {return Player.transform.position;}}