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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

object reference not set to an instance of an object

Discussion in 'Scripting' started by Zammystuff, Apr 7, 2020.

  1. Zammystuff

    Zammystuff

    Joined:
    Jun 30, 2015
    Posts:
    9
    Hello everyone. this is for a movewithinRange that functions as a way to stop the navmesh from running directly inside of the target with selecting an enemy to attack, as im still pretty new to programming im having a hard time finding why this error is actually occuring in this script. it may also be in another script but i havent figured it out quite yet. Any assistance would be greatly appreciated.
    -----------------------------------------------------

    Debug Log:
    NullReferenceException: Object reference not set to an instance of an object
    RPG.Combat.Fighter.Update () (at Assets/Scripts/Fighter.cs:18)
    -------------------------------------------------------
    Script



    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using RPG.Movement;
    6. namespace RPG.Combat
    7. {
    8. public class Fighter : MonoBehaviour
    9.  
    10.  
    11. {
    12.     [SerializeField] float weaponRange = 2.0f;
    13.     Transform target;
    14.  
    15.    
    16.    
    17.     private void Update() {
    18.         bool isInRange = Vector3.Distance(transform.position, target.position) < weaponRange;
    19.         if (target != null && !isInRange)
    20.         {
    21.             GetComponent<Mover>().MoveTo(target.position);
    22.         }
    23.         else
    24.         {
    25.             GetComponent<Mover>().Stop();
    26.         }
    27.  
    28.     }
    29.     public void Attack(CombatTarget combatTarget)
    30.     {
    31.         print("Take that you short squat peasent!");
    32.         target = combatTarget.transform;
    33.  
    34.  
    35.     }
    36.  
    37.        
    38.     }
    39. }
     
  2. Zammystuff

    Zammystuff

    Joined:
    Jun 30, 2015
    Posts:
    9
    False alarm. Fixed it by creating a new method for isInRange.

    also i could have just inserted

    if (target == null) return;

    just incase someone else runs across this.
     
    Last edited: Apr 7, 2020