Answer the question
In order to leave comments, you need to log in
Camera Controller 2d (attach the camera to the character). How to fix the error?
Error:
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)
Code:
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;
}
}
}
Answer the question
In order to leave comments, you need to log in
Have you given your character the "player" tag?
UPD:
The script is working, you are probably doing something wrong.
Hang the script on the Main Camera
I believe that instead of the TAG *player*, you assigned the character Layer *player*
Also check how your TAG is registered, it is in the script with a small letter, which means it should also be in the inspector with a small letter!
And it would be best to change the letter in the script and you will be happy.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question