我是游戏开发的新手,我有一个问题,我有我的敌人预制件和敌人脚本,包含
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);
}
}
}
答案 0 :(得分:1)
首先,您不能在静态上下文中使用 Find
。 (这可能是您所指的错误。)
它更深入地介绍了 c# 的工作原理,但简单地说:甚至在执行构造函数之前,类字段都已初始化,因此在仍然没有实例的时候。
其次: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
。它基本上只是使用一些静态或基于管理器/提供程序的代码的更昂贵的方式