[英]Unity finding Transform object in scene
我是游戏开发新手,我有疑问,我有敌人预制件和敌人脚本,包含
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);
}
}
}
首先,您不能在 static 上下文中使用Find
。 (这可能是您所指的错误。)
它更深入地介绍了 c# 的工作原理,但简而言之:class 字段甚至在构造函数执行之前就已全部初始化,因此此时仍然没有实例。
其次: GameObject.Find
返回一个GameObject
而不是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
。 它基本上只是使用一些 static 或基于管理器/提供程序的代码的更昂贵的方式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.