首页 > 解决方案 > 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);
        }
    }
}

标签: c#unity3d

解决方案


首先,您不能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。它基本上只是使用一些静态或基于管理器/提供程序的代码的一种更昂贵的方式


推荐阅读