Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Object reference not set to an instance of an object

Discussion in 'Scripting' started by TrovezVoid, Mar 22, 2021.

  1. TrovezVoid

    TrovezVoid

    Joined:
    Sep 21, 2020
    Posts:
    20
    Object reference not set to an instance of an object
    PlayerCharacterController.Awake () (at Assets/Scripts/PlayerCharacterController.cs:32)

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerCharacterController : MonoBehaviour {
    6.  
    7.     private const float NORMAL_FOV = 60f;
    8.     private const float HOOKSHOT_FOV = 100f;
    9.  
    10.     [SerializeField] private float mouseSensitivity = 1f;
    11.     [SerializeField] private Transform debugHitPointTransform;
    12.     [SerializeField] private Transform hookshotTransform;
    13.  
    14.     private CharacterController characterController;
    15.     private float cameraVerticalAngle;
    16.     private float characterVelocityY;
    17.     private Vector3 characterVelocityMomentum;
    18.     private Camera playerCamera;
    19.     private ParticleSystem speedLinesParticleSystem;
    20.     private State state;
    21.     private Vector3 hookshotPosition;
    22.     private float hookshotSize;
    23.  
    24.     private enum State {
    25.         Normal,
    26.         HookshotThrown,
    27.         HookshotFlyingPlayer,
    28.     }
    29.  
    30.     private void Awake() {
    31.         characterController = GetComponent<CharacterController>();
    32.         playerCamera = transform.Find("Camera").GetComponent<Camera>();
    33.         speedLinesParticleSystem = transform.Find("Camera").Find("SpeedLinesParticleSystem").GetComponent<ParticleSystem>();
    34.         Cursor.lockState = CursorLockMode.Locked;
    35.         state = State.Normal;
    36.         hookshotTransform.gameObject.SetActive(false);
    37.     }
    38.  
    39.     private void Update() {
    40.         switch (state) {
    41.         default:
    42.         case State.Normal:
    43.             HandleCharacterLook();
    44.             HandleCharacterMovement();
    45.             HandleHookshotStart();
    46.             break;
    47.         case State.HookshotThrown:
    48.             HandleHookshotThrow();
    49.             HandleCharacterLook();
    50.             HandleCharacterMovement();
    51.             break;
    52.         case State.HookshotFlyingPlayer:
    53.             HandleCharacterLook();
    54.             HandleHookshotMovement();
    55.             break;
    56.         }
    57.     }
    58.  
    59.     private void HandleCharacterLook() {
    60.         float lookX = Input.GetAxisRaw("Mouse X");
    61.         float lookY = Input.GetAxisRaw("Mouse Y");
    62.  
    63.         // Rotate the transform with the input speed around its local Y axis
    64.         transform.Rotate(new Vector3(0f, lookX * mouseSensitivity, 0f), Space.Self);
    65.  
    66.         // Add vertical inputs to the camera's vertical angle
    67.         cameraVerticalAngle -= lookY * mouseSensitivity;
    68.  
    69.         // Limit the camera's vertical angle to min/max
    70.         cameraVerticalAngle = Mathf.Clamp(cameraVerticalAngle, -89f, 89f);
    71.  
    72.         // Apply the vertical angle as a local rotation to the camera transform along its right axis (makes it pivot up and down)
    73.         playerCamera.transform.localEulerAngles = new Vector3(cameraVerticalAngle, 0, 0);
    74.     }
    75.  
    76.     private void HandleCharacterMovement() {
    77.         float moveX = Input.GetAxisRaw("Horizontal");
    78.         float moveZ = Input.GetAxisRaw("Vertical");
    79.  
    80.         float moveSpeed = 20f;
    81.  
    82.         Vector3 characterVelocity = transform.right * moveX * moveSpeed + transform.forward * moveZ * moveSpeed;
    83.  
    84.         if (characterController.isGrounded) {
    85.             characterVelocityY = 0f;
    86.             // Jump
    87.             if (TestInputJump()) {
    88.                 float jumpSpeed = 30f;
    89.                 characterVelocityY = jumpSpeed;
    90.             }
    91.         }
    92.  
    93.         // Apply gravity to the velocity
    94.         float gravityDownForce = -60f;
    95.         characterVelocityY += gravityDownForce * Time.deltaTime;
    96.  
    97.  
    98.         // Apply Y velocity to move vector
    99.         characterVelocity.y = characterVelocityY;
    100.  
    101.         // Apply momentum
    102.         characterVelocity += characterVelocityMomentum;
    103.  
    104.         // Move Character Controller
    105.         characterController.Move(characterVelocity * Time.deltaTime);
    106.  
    107.         // Dampen momentum
    108.         if (characterVelocityMomentum.magnitude > 0f) {
    109.             float momentumDrag = 3f;
    110.             characterVelocityMomentum -= characterVelocityMomentum * momentumDrag * Time.deltaTime;
    111.             if (characterVelocityMomentum.magnitude < .0f) {
    112.                 characterVelocityMomentum = Vector3.zero;
    113.             }
    114.         }
    115.     }
    116.  
    117.     private void ResetGravityEffect() {
    118.         characterVelocityY = 0f;
    119.     }
    120.  
    121.     private void HandleHookshotStart() {
    122.         if (TestInputDownHookshot()) {
    123.             if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out RaycastHit raycastHit)) {
    124.                 // Hit something
    125.                 debugHitPointTransform.position = raycastHit.point;
    126.                 hookshotPosition = raycastHit.point;
    127.                 hookshotSize = 0f;
    128.                 hookshotTransform.gameObject.SetActive(true);
    129.                 hookshotTransform.localScale = Vector3.zero;
    130.                 state = State.HookshotThrown;
    131.             }
    132.         }
    133.     }
    134.  
    135.     private void HandleHookshotThrow() {
    136.         hookshotTransform.LookAt(hookshotPosition);
    137.  
    138.         float hookshotThrowSpeed = 500f;
    139.         hookshotSize += hookshotThrowSpeed * Time.deltaTime;
    140.         hookshotTransform.localScale = new Vector3(1, 1, hookshotSize);
    141.  
    142.         if (hookshotSize >= Vector3.Distance(transform.position, hookshotPosition)) {
    143.             state = State.HookshotFlyingPlayer;
    144.             speedLinesParticleSystem.Play();
    145.         }
    146.     }
    147.  
    148.     private void HandleHookshotMovement() {
    149.         hookshotTransform.LookAt(hookshotPosition);
    150.  
    151.         Vector3 hookshotDir = (hookshotPosition - transform.position).normalized;
    152.  
    153.         float hookshotSpeedMin = 10f;
    154.         float hookshotSpeedMax = 40f;
    155.         float hookshotSpeed = Mathf.Clamp(Vector3.Distance(transform.position, hookshotPosition), hookshotSpeedMin, hookshotSpeedMax);
    156.         float hookshotSpeedMultiplier = 5f;
    157.  
    158.         // Move Character Controller
    159.         characterController.Move(hookshotDir * hookshotSpeed * hookshotSpeedMultiplier * Time.deltaTime);
    160.  
    161.         float reachedHookshotPositionDistance = 1f;
    162.         if (Vector3.Distance(transform.position, hookshotPosition) < reachedHookshotPositionDistance) {
    163.             // Reached Hookshot Position
    164.             StopHookshot();
    165.         }
    166.  
    167.         if (TestInputDownHookshot()) {
    168.             // Cancel Hookshot
    169.             StopHookshot();
    170.         }
    171.  
    172.         if (TestInputJump()) {
    173.             // Cancelled with Jump
    174.             float momentumExtraSpeed = 7f;
    175.             characterVelocityMomentum = hookshotDir * hookshotSpeed * momentumExtraSpeed;
    176.             float jumpSpeed = 40f;
    177.             characterVelocityMomentum += Vector3.up * jumpSpeed;
    178.             StopHookshot();
    179.         }
    180.     }
    181.  
    182.     private void StopHookshot() {
    183.         state = State.Normal;
    184.         ResetGravityEffect();
    185.         hookshotTransform.gameObject.SetActive(false);
    186.         speedLinesParticleSystem.Stop();
    187.     }
    188.  
    189.     private bool TestInputDownHookshot() {
    190.         return Input.GetKeyDown(KeyCode.E);
    191.     }
    192.  
    193.     private bool TestInputJump() {
    194.         return Input.GetKeyDown(KeyCode.Space);
    195.     }
    196.  
    197.  
    198. }
    199.  
     
    Last edited: Mar 22, 2021
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    The answer is always the same... ALWAYS. It is the single most common error ever.

    Don't waste your life spinning around and round on this error. Instead, learn how to fix it fast... it's EASY!!

    Some notes on how to fix a NullReferenceException error in Unity3D
    - also known as: Unassigned Reference Exception
    - also known as: Missing Reference Exception
    - also known as: Object reference not set to an instance of an object

    http://plbm.com/?p=221

    The basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.

    Expect to see this error a LOT. It's easily the most common thing to do when working. Learn how to fix it rapidly. It's easy. See the above link for more tips.

    This is the kind of mindset and thinking process you need to bring to this problem:

    https://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    Step by step, break it down, find the problem.
     
  3. TrovezVoid

    TrovezVoid

    Joined:
    Sep 21, 2020
    Posts:
    20
    I will try to use this but since I just started actually trying to use unity 5 days ago so I don't understand a lot.
     
  4. Seehundy1995

    Seehundy1995

    Joined:
    Mar 22, 2021
    Posts:
    6
    How i can do my own post?
     
  5. TrovezVoid

    TrovezVoid

    Joined:
    Sep 21, 2020
    Posts:
    20
    go to a topic like scripting in the forums page and press post new thread
     
    Seehundy1995 likes this.
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    This error:

    Tells you the file and the line number (32).

    From that begin your investigation.

    If you started this from a tutorial, back up until he discusses this line and things related to it.

    Make sure you also pay attention to setup in the tutorial. It will NEVER just be the script: the script has to be installed and configured properly before it will work. Pay attention to that part of the tutorial too.