c# - unity在场景中寻找Transform对象
问题描述
我是游戏开发新手,我有疑问,我有敌人预制件和敌人脚本,包含
public Transform player;
因此,我不想每次都将我的播放器放入那个“插槽”,而是让脚本找到我的播放器,我尝试了
private Transform player = GameObject.Find("player")
但它显示错误这是完整的脚本
public class Enemies : MonoBehaviour
{
public Transform player = GameObject.Find("Player");
private Rigidbody2D rb;
private Vector2 movement;
public float speed = 5f;
public int health;
// Start is called before the first frame update
void Start()
{
rb = this.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector2 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb.rotation = angle;
direction.Normalize();
movement = direction;
}
private void FixedUpdate()
{
Move(movement);
}
void Move(Vector2 direction)
{
rb.MovePosition((Vector2)transform.position + (direction * speed * Time.deltaTime));
}
private void OnMouseDown()
{
health = health - 1;
if(health <= 0)
{
Destroy(gameObject);
}
}
}
解决方案
首先,您不能Find
在静态上下文中使用。(这可能是您所指的错误。)
它更深入地介绍了 c# 的工作原理,但简单来说:类字段甚至在构造函数执行之前都已初始化,因此在仍然没有实例的时刻。
其次:GameObject.Find
返回 aGameObject
不是 a Transform
。
因此,如果有的话,它可能宁愿是
// Best would still be to drag this in if possible
[SerializeField] private Transform player;
void Start()
{
if(!player) player = GameObject.Find("Player").transform;
rb = this.GetComponent<Rigidbody2D>();
}
一般来说,我总是建议尽可能不要使用Find
。它基本上只是使用一些静态或基于管理器/提供程序的代码的一种更昂贵的方式
推荐阅读
- node.js - 从 mongodb 查询所有元素的函数不填充数组
- git - 来自 SCM 的 Jenkinsfile 在应用程序代码上选择不同的分支
- java - 如何在 Intellij Idea 中使用 maven 在 ipfs 中创建远程连接?
- ns-3 - 显示 ns3 3.28 下 tcp-variants-comparison.cc 的结果
- flask - Flask-mongoengine:无法从 flask-mongoengine 导入 MongoEngine
- node.js - 如何获取在永久 npm 中运行的 NodeJs 应用程序的日志?
- javascript - 如何复制对象然后将其保存到本地存储
- javascript - 打印时如何实现引导包含另一个隐藏的用 javascript
- python - TypeError:bufsize 必须是整数?
- javascript - javascript 计时事件...这里有什么问题?