Queen2
@Queen2

Camera Controller 2d(привязать камеру к персонажу). Как исправить ошибку?

Ошибка:
NullReferenceException: Object reference not set to an instance of an object
CameraController.FindPlayer (Boolean playerIsLeft) (at Assets/ScriptHero/CameraController.cs:22)
CameraController.Start () (at Assets/ScriptHero/CameraController.cs:17)

Код:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour {

public float dumping = 1.5f;
public Vector2 offset = new Vector2(2f, 1f);
public bool isLeft;
private Transform player;
private int lastX;

// Use this for initialization
void Start ()
{
offset = new Vector2(Mathf.Abs(offset.x), offset.y);
FindPlayer(isLeft);

}
public void FindPlayer(bool playerIsLeft)
{
player = GameObject.FindGameObjectWithTag("player").transform;
lastX = Mathf.RoundToInt(player.position.x);
if (playerIsLeft)
{
transform.position = new Vector3(player.position.x - offset.x, player.position.y - offset.y, transform.position.z);
}
else
{
transform.position = new Vector3(player.position.x + offset.x, player.position.y + offset.y, transform.position.z);
}
}



// Update is called once per frame
void Update ()
{
if(player)
{
int currentX = Mathf.RoundToInt(player.position.x);
if (currentX > lastX) isLeft = false;
if (currentX < lastX) isLeft = true;
lastX = Mathf.RoundToInt(player.position.x);

Vector3 target;
if (isLeft)
{
target = new Vector3(player.position.x - offset.x, player.position.y + offset.y, transform.position.z);
}
else
{
target = new Vector3(player.position.x + offset.x, player.position.y + offset.y, transform.position.z);
}
Vector3 currentPosition = Vector3.Lerp(transform.position, target, dumping * Time.deltaTime);
transform.position = currentPosition;
}
}
}
  • Вопрос задан
  • 282 просмотра
Решения вопроса 1
@4xy0
А вы присвоили своему своему персонажу тег "player" ?

UPD:
Скрипт рабочий, Вы наверное все таки что-то делаете не так.
Вешайте скрипт на Main Camera
Я полагаю что вместо именно ТЕГа *player*, вы присвоили персонажу Layer *player*
5eeb9d824fe21799715192.jpeg
Так же проверьте как прописан у Вас ТЕГ, в скрипте он с маленькой буквы, значит и в инспекторе тоже должен быть с маленькой буквы!
А лучше всего будет в скрипте изменить букву и будет Вам счастье.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы