Micnasr
Micnasr

Reputation: 31

Unity - Shoot a bullet at last position of player

using System.Collections.Generic;
using UnityEngine;

public class enemybullet : MonoBehaviour
{
    Transform player;

    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;

        Vector3 lastpos = player.position;

        Destroy(gameObject, 4f);
    }
gets last pos of player

 void Update()
 {
    transform.position = Vector3.MoveTowards(transform.position, player.position, 10f);
 }


go towards player

I want it to shoot the direction of player and its not letting me use lastpos in the movetowards function

Upvotes: 1

Views: 556

Answers (1)

Jay
Jay

Reputation: 2946

The problem here is the scope of your variables.

void Start()
{
    player = GameObject.FindGameObjectWithTag("Player").transform;

    Vector3 lastpos = player.position;

    Destroy(gameObject, 4f);
}

As you can see here, you have Declared your variable within a {...} (scope) which means the variable will only be visible within the scope it was created in (and will actually be destroyed as soon as execution leaves the {...}

To fix this you need to declare your variable in scope of the whole class

public Vector3 lastpos;

void Start()
{
    player = GameObject.FindGameObjectWithTag("Player").transform;

    lastpos = player.position;

    Destroy(gameObject, 4f);
}

You will now be able to access lastpos from anywhere within your class (or even outside your class)

Upvotes: 1

Related Questions