Leonardo Stokes
Leonardo Stokes

Reputation: 11

Unity 5 Third Person Script Error

I'm getting the error NullReferenceException: Object reference not set to an instance of an object ThirdPersonCamera.Update () (at Assets/scripts/ThirdPersonCamera.cs:24)

My Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using UnityEngine.SocialPlatforms;
using UnityEngine.UI;
using UnityStandardAssets.Utility;

public class ThirdPersonCamera : MonoBehaviour {

    [SerializeField]Vector3 cameraOffset;
    [SerializeField]float damping;

    Transform cameraLookTarget;
    Player localPlayer;

    void Awake () {
        GameManger.Instance.OnLocalPlayerJoined += HandleOnLocalPlayerJoined;
    } 

    void HandleOnLocalPlayerJoined (Player player) {
        localPlayer = player;
        cameraLookTarget = localPlayer.transform.Find("cameraLookTarget");

        if (cameraLookTarget == null) {
            cameraLookTarget = localPlayer.transform;
        }
    }


    // Update is called once per frame
    void Update () {
        Vector3 targetPosition = cameraLookTarget.position + localPlayer.transform.forward * cameraOffset.z +
                localPlayer.transform.up * cameraOffset.y +
                localPlayer.transform.right * cameraOffset.x;

        transform.position = Vector3.Lerp(transform.position, targetPosition, damping * Time.deltaTime);
    }
}

I've tried changing the Script Execution Order, but nothing works. I don't know what's wrong.

Upvotes: 0

Views: 116

Answers (1)

Chad
Chad

Reputation: 892

Make sure you have a GameObject assigned to the LocalPlayer variable in your script. This object is looking in your hierarchy for something called 'cameraLookTarget' without quotes. Capitalization matters.

I recommend looking for a LocalPlayer object in your Awake() method and if it is null use Debug.Log("No local player assigned") to alert yourself that this is in fact not being assigned.

Upvotes: 1

Related Questions