我已经创建了一个玩家预置(在我的项目中称为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。
3条答案
按热度按时间l0oc07j21#
下面是访问主摄像头一个很好的示例:
zf9nrax12#
所以你必须检查你的相机标签是“主相机”。
或者你试试
(我不推荐第二种解决方案)
nfeuvbwi3#
所以我最终找到了答案。我只是删除了我场景中的相机,并创建了一个新的,然后最终使用:
MainCamera = GameObject.FindWithTag("Camera").GetComponent<Camera>();
,这次起作用了。这个问题也可能是由我的代码中以前出现的错误引起的。