unity3d - 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
解决方案
这里的问题是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
从班内(甚至班外)的任何地方访问
推荐阅读
- go - golang 在函数结束后没有释放变量
- c# - 如何减少连续 Graphics.DrawImage() 使用的内存量
- java - Spring:收到来自另一个 REST API 的响应后调用 REST API
- javascript - 在 Mac 中,对于 codemirror 命令,Alt Key 指的是什么?
- reactjs - 打字稿不正确的空/从不检查反应参考
- javascript - 在 Ant Design 中的 Step 中嵌套下拉菜单
- ios - 当我点击 UIImagePicker galary 的图像按钮以在 iPad 中选择图像时,应用程序崩溃了,为什么?
- wordpress - 通过 WooCommerce 回调更新 WooCommerce 订单状态
- mongodb - Mongoose:始终如一地保存文档顺序
- amazon-web-services - 发布端口时,Swarm 中的 Docker 服务无法连接到 AWS RDS