简体   繁体   English

如何在 Unity 2D 的预制脚本中引用相机?

[英]How to reference camera in prefab script in Unity 2D?

I have created a player prefab (called Tim in my project) and am trying to make all the references to gameObjects and transforms directly from the one of the players scripts which is actually attached to a gun object which is a child of the player prefab.我已经创建了一个玩家预制件(在我的项目中称为 Tim),并试图对 gameObjects 进行所有引用,并直接从实际上附加到枪 object 的玩家脚本之一进行转换,这是玩家预制件的子项。

在此处输入图像描述

The issue is I cant manage to reference the camera in the script although I've looked and tried many different methods, none of them seemed to work.问题是我无法设法在脚本中引用相机,尽管我已经查看并尝试了许多不同的方法,但似乎都不起作用。 Unity prints this error in the console though: "NullReferenceException: Object reference not set to an instance of an object". Unity 在控制台中打印此错误:“NullReferenceException:Object 引用未设置为对象的实例”。 And here is the script:这是脚本:

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);
}
}

Right now I have a variable, MainCamera, and when the script starts I look for a camera which has "Camera" as its tag which is set correctly.现在我有一个变量,MainCamera,当脚本启动时,我会寻找一个以“Camera”作为标签且设置正确的相机。 I can add on if anyone needs more details and thank you to everyone for taking the time to help.如果有人需要更多详细信息,我可以补充,感谢大家花时间提供帮助。

Edit 1: I tried what thunderkill suggested but it doesnt seem to work.编辑 1:我尝试了 thunderkill 的建议,但它似乎不起作用。 Here is a picture of the new code.这是新代码的图片。

在此处输入图像描述

And when I try to use Debug.Log(Camera.main);当我尝试使用 Debug.Log(Camera.main); it prints null.它打印出 null。

here is a good example to access your main camera:这是访问主摄像头的一个很好的例子:

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; 
        }
}

So i ended up finding the answer.所以我最终找到了答案。 I just deleted the camera in my scene and created a new one and then ended up using: "MainCamera = GameObject.FindWithTag("Camera").GetComponent();"我刚刚删除了场景中的相机并创建了一个新相机,然后最终使用:“MainCamera = GameObject.FindWithTag("Camera").GetComponent();” which worked this time.这次有效。 The issue could have also been caused by errors present before in my code.该问题也可能是由我的代码中之前出现的错误引起的。

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

So you have to Check if your Camera tag is "MainCamera".所以你必须检查你的相机标签是否是“MainCamera”。

or you try:或者你试试:

GameObject.FindObjectOfType<Camera>();

(I don't recommend the second solution) (我不推荐第二种方案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM