unity3d 如何在Unity 2D的预置脚本中引用摄像机?

s6fujrry  于 2023-01-31  发布在  其他
关注(0)|答案(3)|浏览(155)

我已经创建了一个玩家预置(在我的项目中称为Tim),并试图直接从一个玩家脚本(实际上附加到一个枪对象,这是玩家预置的子对象)中引用所有gameObjects和转换。

问题是我无法在脚本中引用摄像头,尽管我已经尝试了许多不同的方法,但似乎都不起作用。Unity在控制台中打印了此错误:“空引用异常:对象引用未设置为对象”“的示例。脚本如下:

public class Gun_Control : MonoBehaviour
{
// References for GameObjects
[SerializeField] private Rigidbody2D rb;
private GameObject Player;
[SerializeField] private Transform PlayerTransform;
private GameObject Gun;
[SerializeField] private Transform GunTransform;
private Camera MainCamera;
private GameObject firePoint;
[SerializeField] private Transform firePointTransform;
[SerializeField] private GameObject bulletPrefab;

// Variables for Shooting
private Vector2 mousePos;
private float bulletForce = 20f;

// Start is called at the beginning
void Start()
{
    Debug.Log("Starting");
    Player = GameObject.FindWithTag("Player");
    PlayerTransform = Player.transform;
    Gun = GameObject.FindWithTag("PlayerGun");
    GunTransform = Gun.transform;
    MainCamera = GameObject.FindWithTag("Camera").GetComponent<Camera>();
    firePoint = GameObject.FindWithTag("PlayerFirePoint");
    firePointTransform = firePoint.transform;
}

// Update is called once per frame
void Update()
{
    // Get mouse position
    mousePos = MainCamera.ScreenToWorldPoint(Input.mousePosition);

    // Run shoot function on left click
    if(Input.GetButtonDown("Fire1"))
    {
        Shoot();
    }
}

// Update is called on every physics frame
void FixedUpdate()
{
    // Set gun position to player position
    GunTransform.position = PlayerTransform.position;
    // Set gun rotation to mouse position
    Vector2 lookDir = mousePos - rb.position;
    float angle = Mathf.Atan2(lookDir.y ,lookDir.x) * Mathf.Rad2Deg - 180f;
    rb.rotation = angle;
}

void Shoot()
{
    // Instantiate a bullet at the firepoint and give it force
    GameObject bullet = Instantiate(bulletPrefab, firePointTransform.position, firePointTransform.rotation);
    Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
    rb.AddForce(firePointTransform.up * bulletForce, ForceMode2D.Impulse);
}
}

现在我有一个变量,MainCamera,当脚本启动时,我会寻找一个标签为“Camera”且设置正确的相机。如果有人需要更多细节,我可以添加,并感谢大家抽出时间来帮助。
编辑1:我尝试了Thunderkill建议的方法,但似乎不起作用。下面是新代码的图片。

而当我尝试使用Debug.log(Camera.main)时;它打印null。

l0oc07j2

l0oc07j21#

下面是访问主摄像头一个很好的示例:

Camera m_MainCamera;
void Start()
{
        //This gets the Main Camera from the Scene
     if(Camera.main != null){
        m_MainCamera = Camera.main;
        //This enables Main Camera
        m_MainCamera.enabled = true; 
        }
}
zf9nrax1

zf9nrax12#

Camera c = Camera.main;//get the camera Tagged "MainCamera"

所以你必须检查你的相机标签是“主相机”。
或者你试试

GameObject.FindObjectOfType<Camera>();

(我不推荐第二种解决方案)

nfeuvbwi

nfeuvbwi3#

所以我最终找到了答案。我只是删除了我场景中的相机,并创建了一个新的,然后最终使用:MainCamera = GameObject.FindWithTag("Camera").GetComponent<Camera>();,这次起作用了。这个问题也可能是由我的代码中以前出现的错误引起的。

相关问题