首页 > 解决方案 > Unity - 在玩家的最后一个位置射击子弹

问题描述

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);
 }


走向玩家

我希望它拍摄玩家的方向,并且它不让我在 movetowards 函数中使用 lastpos

标签: unity3d

解决方案


这里的问题是scope你的变量。

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

    Vector3 lastpos = player.position;

    Destroy(gameObject, 4f);
}

正如您在此处看到的,您已在(范围)内声明了变量,{...}这意味着该变量仅在创建它的范围内可见(并且实际上将在执行离开时立即销毁{...}

要解决此问题,您需要在整个类的范围内声明您的变量

public Vector3 lastpos;

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

    lastpos = player.position;

    Destroy(gameObject, 4f);
}

您现在可以lastpos从班内(甚至班外)的任何地方访问


推荐阅读