如何解决我的相机平滑移动错误



我一直在尝试一种新的方法,我发现关于相机运动(我试图做像一个metroidvania),我只是做了一个脚本,使相机大小碰撞器,所以相机只能移动它。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
private Transform player;
private BoxCollider2D camBox;
private GameObject[] boundaries;
private Bounds[] allBounds;
private Bounds targetBounds;
public float speed;
private float waitForSeconds = 0.5f;
void start()
{
player = GameObject.Find("Player").GetComponent<Transform>();
camBox = GetComponent<BoxCollider2D>();
FindLimits();
}
void LateUpdate()
{
if(waitForSeconds > 0)
{
waitForSeconds -= Time.deltaTime;
}else{
SetOneLimit();
FollowPlayer();
}
}
//Encuentra el encaje de la camara
void FindLimits() 
{
boundaries = GameObject.FindGameObjectsWithTag("Boundary");
allBounds = new Bounds[boundaries.Length];
for(int i = 0; i < allBounds.Length; i++)
{
allBounds[i] = boundaries[i].gameObject.GetComponent<BoxCollider2D>().bounds; 
}
}
//Ajusta la medida de la camara al borde
void SetOneLimit()
{
for(int i = 0; i < allBounds.Length; i++)
{
if(player.position.x > allBounds[i].min.x && player.position.x < allBounds[i].max.x && player.position.y > allBounds[i].min.y && player.position.y < allBounds[i].max.y)
{
targetBounds = allBounds[i];
return;
}
}
}
void FollowPlayer()
{
float xTarget=camBox.size.x<targetBounds.size.x?Mathf.Clamp(player.position.x, targetBounds.min.x+camBox.size.x/2, targetBounds.max.x-camBox.size.x/2):(targetBounds.min.x+targetBounds.max.x)/2;
float yTarget=camBox.size.y<targetBounds.size.y?Mathf.Clamp(player.position.y, targetBounds.min.y+camBox.size.y/2, targetBounds.max.y-camBox.size.y/2):(targetBounds.min.y+targetBounds.max.y)/2;
Vector3 target = new Vector3(xTarget, yTarget, transform.position.z);
transform.position = Vector3.Lerp(transform.position, target, speed * Time.deltaTime);
}
}

这是我使用的代码,这是我按下播放按钮时得到的错误。

NullReferenceException: Object reference not set to a instance of Object

CameraFollow。SetOneLimit () (at Assets/Scripts/camerfollowing .cs:46)

CameraFollow。LateUpdate () (at Assets/Scripts/camerfollowing .cs:28)

start()是小写的,我不确定它会像Start()一样工作;)检查它,因为可能你的字段没有正确初始化。

和阅读一些关于NullReferenceException;)

最新更新