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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question Object reference not set to an instance of an object

Discussion in 'Scripting' started by Only4gamers, Jun 4, 2022.

  1. Only4gamers

    Only4gamers

    Joined:
    Nov 8, 2019
    Posts:
    312
    Hello everyone,
    While I faced this error countless times before in Unity editor and solving this error is quite easy. But this time I am getting this error inside Windows Standalone build, while this error is not happening in the Editor at all. And it's really tough to understand exactly in which line this error is happening. How to debug Windows Standalone build?

    Error:
    Code (CSharp):
    1. Exception
    2. NullReferenceException: Object reference not set to an instance of an object
    3. ShipController.FindClosestEnemy () (at <c9e0c0710bef452d9c11c840866edbd3>:0)
    4. ShipController+<DistanceFromTargetCarrier>d__80.MoveNext () (at <c9e0c0710bef452d9c11c840866edbd3>:0)
    5. UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <2031488213494187ad8fdf6a91d614ad>:0)
    My full script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class ShipController : MonoBehaviour
    7. {
    8.     public bool isPlayerCarrier;
    9.     public bool isEnemyCarrier;
    10.     public bool isPlayerFighter;
    11.     public bool isEnemyFighter;
    12.     public bool isStation;
    13.     public bool isEnemyFreighter;
    14.  
    15.     [HideInInspector] public enum Mode
    16.     {
    17.         Attack,
    18.         Idle
    19.     }
    20.     [HideInInspector] public Mode mode;
    21.     [HideInInspector] public float defaultSpeed;
    22.     public float minSpeed = 2;
    23.     public float maxSpeed = 4;
    24.     public float rotateSpeed;
    25.     [HideInInspector] public Vector3 target;
    26.     [HideInInspector] public Transform targetWaypoint;
    27.     [HideInInspector] public Quaternion carrierTargetRotation;
    28.     public int hull;
    29.     public int shield;
    30.     public int energy;
    31.     public float speed = 1.5f; // For Carrier Ships Set From Inspector
    32.     public int weaponSlots;
    33.     public int utilitySlots;
    34.     public int maxFighterShips;
    35.  
    36.     [HideInInspector] public PageManager pageManager;
    37.     [HideInInspector] public GameObject gameOverPage;
    38.     [HideInInspector] public Transform closestEnemy;
    39.     [HideInInspector] public float distanceFromEnemy;
    40.     [HideInInspector] public float distanceFromWaypoint; // Only for Player Carriers
    41.  
    42.     [HideInInspector] public ShipStats shipStats;
    43.  
    44.  
    45.     //For Carrier Ships
    46.     [HideInInspector] public Waypoints waypoints;
    47.     [HideInInspector] public Transform waypoint; // Waypoint marker
    48.     private Camera cam;
    49.     public int shipNumber = 0;
    50.     [HideInInspector] public TargetMover targetMover;
    51.  
    52.     [HideInInspector] public Vector3 camTransformInStart;
    53.     [HideInInspector] public float camOrthoSizeInStart;
    54.     [HideInInspector] public Vector3 AILerpTransInStart;
    55.     [HideInInspector] public bool isPlayer = false;
    56.     [HideInInspector] public bool isFaction1 = false; // Filling in awake
    57.     [HideInInspector] public bool isFaction2 = false;
    58.     [HideInInspector] public bool isPirate = false;
    59.     [HideInInspector] public Reputation reputation;
    60.  
    61.  
    62.     // For Fighter Ships
    63.     private Vector3 zAxis;
    64.     private bool isChasing = true;
    65.     [HideInInspector] public FighterSpawner fighterSpawner; // Used by fighter ships. Dont fill from the Inspector
    66.     private int startOrbitingDistance;
    67.     private int z;
    68.     public float totalValue;
    69.     private string shipTag;
    70.  
    71.     [HideInInspector] public string sortingLayer;
    72.     [HideInInspector] public int orderInLayer;
    73.     [HideInInspector] public bool preparingHyperJump = false;
    74.     [HideInInspector] public SpriteRenderer spriteRenderer;
    75.  
    76.     [HideInInspector] public PirateHunt pirateHunt;
    77.     [HideInInspector] public DefenceMission defenceMission;
    78.     //[HideInInspector] public InterceptFreighter interceptFreighter;
    79.     //[HideInInspector] public DestroyAllPirates destroyAllPirates;
    80.     [HideInInspector] public MainScript2 mainScript2;
    81.  
    82.     //public GameObject selectedImage;
    83.     private int rotateTowardOffset;
    84.     public Transform preferredEnemy;
    85.     [HideInInspector] public ShipSpawner shipSpawner; // Setting this while spawning from ShipSpawner
    86.     //[HideInInspector] public PlayerOptions playerOptions;
    87.     [HideInInspector] public Material nonSelectedMaterial;
    88.     public Material selectedOutlineMaterial;
    89.     //public Material playerOutline;
    90.     public Material enemyOutline;
    91.     public Material neutralOutline;
    92.     public Material allyOutline;
    93.     [HideInInspector] public bool isSelected;
    94.     [HideInInspector] public bool isAttackOn = true;
    95.     [HideInInspector] public bool isDefenceOn = true;
    96.     [HideInInspector] public bool isThrusterOn;
    97.     [HideInInspector] public bool isTargetingStation;
    98.     //public bool canAttackStation;
    99.  
    100.     void Awake()
    101.     {
    102.         mode = Mode.Attack;
    103.         mainScript2 = GetComponent<MainScript2>();
    104.         shipStats = GetComponentInChildren<ShipStats>();
    105.         cam = Camera.main;
    106.  
    107.         shipSpawner = GameObject.FindObjectOfType<ShipSpawner>();
    108.  
    109.         Debug.Log("ShipSpawner:   "+shipSpawner);
    110.  
    111.         if(tag == "Player")  //|| tag == "Faction1Station"
    112.         {
    113.             isPlayer = true;
    114.         }
    115.         else if(tag == "Faction1")  //|| tag == "Faction1Station"
    116.         {
    117.             isFaction1 = true;
    118.         }
    119.         else if(tag == "Faction2") // || tag == "Faction2Station"
    120.         {
    121.             isFaction2 = true;
    122.         }
    123.         else if(tag == "Pirate")
    124.         {
    125.             isPirate = true;
    126.         }
    127.      
    128.         spriteRenderer = GetComponent<SpriteRenderer>();
    129.         sortingLayer = spriteRenderer.sortingLayerName;
    130.  
    131.         shipTag = tag;
    132.  
    133.         if(isPlayerCarrier || isEnemyCarrier || isEnemyFreighter || isStation)
    134.         {
    135.             pageManager = GameObject.FindObjectOfType<PageManager>();
    136.             reputation = GameObject.FindObjectOfType<Reputation>();
    137.         }
    138.  
    139.         Debug.Log("Page Manager:   "+pageManager);
    140.         Debug.Log("Reputation:   "+reputation);
    141.  
    142.         nonSelectedMaterial = spriteRenderer.material;
    143.      
    144.         if(isPlayerCarrier)
    145.         {
    146.             isSelected = true;
    147.             spriteRenderer.material = selectedOutlineMaterial;
    148.             waypoints = GameObject.FindObjectOfType<Waypoints>();
    149.  
    150.             Debug.Log("Waypoint:   "+waypoints);
    151.             waypoint = waypoints.transform;
    152.  
    153.             defaultSpeed = speed;
    154.             if(!GameResources.isFirstScene && SceneManager.GetActiveScene().name != "Tutorial")
    155.             {
    156.                 StartCoroutine(mainScript2.ExitHyperJump());
    157.             }
    158.         }
    159.     }
    160.  
    161.     //[HideInInspector] public Reputation reputation;
    162.  
    163.     private Vector3 freighterFirstWP; // Waypoint
    164.     private StationSpawner stationSpawner;
    165.  
    166.     void Start()
    167.     {
    168.         if(!isStation)
    169.         {
    170.             if(isPlayerCarrier)
    171.             {
    172.                 StartCoroutine(SendShipValue());
    173.  
    174.                 targetMover = pageManager.targetMover;
    175.                 gameOverPage = pageManager.gameOverPage;
    176.  
    177.                 camTransformInStart = cam.transform.position;
    178.                 camOrthoSizeInStart = cam.orthographicSize;
    179.                 AILerpTransInStart = pageManager.aILerp.transform.position;
    180.             }
    181.  
    182.             if(isEnemyFreighter)
    183.             {
    184.                 defaultSpeed = speed;
    185.                 targetMover = pageManager.targetMover;
    186.                 //shipSpawner = pageManager.shipSpawner;
    187.                 mode = Mode.Idle;
    188.  
    189.                 stationSpawner = shipSpawner.GetComponent<StationSpawner>();
    190.  
    191.                 int randomX = Random.Range(-10, 10);
    192.                 int randomY = Random.Range(-10, 10);
    193.                 freighterFirstWP = new Vector3(stationSpawner.station.transform.position.x+randomX,
    194.                 stationSpawner.station.transform.position.y+randomY);
    195.  
    196.                 StartCoroutine(FreighterWaypoint());
    197.             }
    198.  
    199.             // For Enemy Carrier
    200.             else if(isEnemyCarrier)
    201.             {
    202.                 targetMover = pageManager.targetMover;
    203.                 target = transform.position;
    204.             }
    205.  
    206.             // For Fighter Ships
    207.             else if(isPlayerFighter || isEnemyFighter)
    208.             {
    209.                 target = transform.position;
    210.             }
    211.         }
    212.  
    213.         if(!isPlayerFighter && !isEnemyFreighter && !isPirate)
    214.         {
    215.             StartCoroutine(ChangeOutlineColor());
    216.         }
    217.     }
    218.  
    219.     IEnumerator ChangeOutlineColor()
    220.     {
    221.         if(EnemyAllyList.playerEnemiesTmp.Contains(tag) || EnemyAllyList.playerEnemies.Contains(tag))
    222.         {
    223.             selectedOutlineMaterial = enemyOutline;
    224.         }
    225.         else if(EnemyAllyList.playerAllies.Contains(tag))
    226.         {
    227.             selectedOutlineMaterial = allyOutline;
    228.         }
    229.         else if(EnemyAllyList.playerNeutrals.Contains(tag))
    230.         {
    231.             selectedOutlineMaterial = neutralOutline;
    232.         }
    233.  
    234.         while(true)
    235.         {
    236.             yield return new WaitForSeconds(5f);
    237.             if(isSelected)
    238.             {
    239.                 if(EnemyAllyList.playerEnemiesTmp.Contains(tag) || EnemyAllyList.playerEnemies.Contains(tag))
    240.                 {
    241.                     selectedOutlineMaterial = enemyOutline;
    242.                 }
    243.                 else if(EnemyAllyList.playerAllies.Contains(tag))
    244.                 {
    245.                     selectedOutlineMaterial = allyOutline;
    246.                 }
    247.                 else if(EnemyAllyList.playerNeutrals.Contains(tag))
    248.                 {
    249.                     selectedOutlineMaterial = neutralOutline;
    250.                 }
    251.  
    252.                 spriteRenderer.material = selectedOutlineMaterial;
    253.             }
    254.         }
    255.     }
    256.  
    257.     void OnEnable()
    258.     {
    259.         tag = shipTag;
    260.         isKilled = false;
    261.         if(isPlayerCarrier)
    262.         {
    263.             StartCoroutine(DistanceFromTargetCarrier());
    264.         }
    265.  
    266.         // For Enemy Carrier
    267.         else if(isEnemyCarrier)
    268.         {
    269.             StartCoroutine(DistFromTargetEnemyCarrier());
    270.             StartCoroutine(UpdateTargetOffset());
    271.         }
    272.  
    273.         // For Fighter Ships
    274.         else if(isPlayerFighter || isEnemyFighter)
    275.         {
    276.             StartCoroutine(DistFromTargetFighters());
    277.             StartCoroutine(UpdateZAxisForFighters());
    278.             StartCoroutine(SendShipValue());
    279.         }
    280.         else if(isStation)
    281.         {
    282.             StartCoroutine(ClosestEnemyForStation());
    283.         }
    284.     }
    285.  
    286.     IEnumerator SendShipValue()
    287.     {
    288.         if(isPlayerCarrier) // || isPlayerFighter
    289.         {
    290.             if(targetWaypoint == null) // *** For tutorial page
    291.             {
    292.                 BuyShipButton.allSC.Add(this);
    293.  
    294.                 if(shipNumber == 1)
    295.                 {
    296.                     targetWaypoint = waypoints.firstShipPosition;
    297.                     BuyShipButton.ship1SC = this;
    298.                 }
    299.                 else if(shipNumber == 2)
    300.                 {
    301.                     targetWaypoint = waypoints.secondShipPosition;
    302.                     BuyShipButton.ship2SC = this;
    303.                 }
    304.             }
    305.  
    306.             yield return new WaitForSeconds(0.02f);
    307.             ShipSpawner.playerStrenght += totalValue;
    308.         }
    309.     }
    310.  
    311.     private int targetOffset; // For Enemy Carrier
    312.  
    313.     private WaitForSeconds wait4 = new WaitForSeconds(4f);
    314.     private WaitForSeconds wait1 = new WaitForSeconds(1f);
    315.  
    316.     IEnumerator UpdateTargetOffset()
    317.     {
    318.         while(true)
    319.         {
    320.             targetOffset = Random.Range(20, 30);
    321.             yield return wait4;
    322.         }
    323.     }
    324.  
    325.     IEnumerator UpdateZAxisForFighters()
    326.     {
    327.         while(true)
    328.         {
    329.             if(Random.value<0.5f)
    330.             {
    331.                 z = 1;
    332.             }
    333.             else
    334.             {
    335.                 z = -1;
    336.             }
    337.      
    338.             zAxis  = new Vector3(0, 0, z);
    339.             if(!isKilled)
    340.             {
    341.                 speed = Random.Range(minSpeed, maxSpeed);
    342.             }
    343.             yield return wait4;
    344.         }
    345.     }
    346.  
    347.     // For Carrier Ships
    348.     IEnumerator DistanceFromTargetCarrier()
    349.     {
    350.         while(true)
    351.         {
    352.             yield return wait1;
    353.             if(!isKilled) //mode == Mode.Attack
    354.             {
    355.                 closestEnemy = FindClosestEnemy();
    356.  
    357.                 if(closestEnemy != null)
    358.                 {
    359.                     distanceFromEnemy = Vector3.Distance (transform.position, closestEnemy.position);
    360.                 }
    361.  
    362.                 if(isPlayerCarrier && isThrusterOn && shipStats.energyShip > 0 && speed > 1f)
    363.                 {
    364.                     shipStats.energyShip -= 1;
    365.                     shipStats.ChangeEnergy(""); //""
    366.                 }
    367.  
    368.                 if(!isTargetingStation)
    369.                 {
    370.                     distanceFromWaypoint = Vector3.Distance (transform.position, targetWaypoint.position);
    371.              
    372.                     if(distanceFromWaypoint < 7 && !preparingHyperJump)
    373.                     {
    374.                         StartCoroutine(LerpSpeedCarrier(0, 2f));
    375.                     }
    376.                     else if(!preparingHyperJump)
    377.                     {
    378.                         StartCoroutine(LerpSpeedCarrier(defaultSpeed, 2f));
    379.                     }
    380.                 }
    381.             }
    382.         }
    383.     }
    384.  
    385.     public IEnumerator LerpSpeedCarrier(float endValue, float duration)
    386.     {
    387.         float time = 0;
    388.         float startValue = speed;
    389.  
    390.         while (time < duration)
    391.         {
    392.             speed = Mathf.Lerp(startValue, endValue, time / duration);
    393.             time += Time.deltaTime;
    394.             yield return null;
    395.         }
    396.         speed = endValue;
    397.     }
    398.  
    399.     // For Fighter Ships and Enemy Carrier
    400.     IEnumerator DistFromTargetFighters()
    401.     {
    402.         while(true)
    403.         {
    404.             yield return wait1;
    405.             rotateTowardOffset = Random.Range(-100, 100);
    406.             if(mode == Mode.Attack)
    407.             {
    408.                 closestEnemy = FindClosestEnemy();
    409.  
    410.                 if(closestEnemy != null)
    411.                 {
    412.                     target = closestEnemy.position;
    413.  
    414.                     distanceFromEnemy = Vector3.Distance (transform.position, target);
    415.  
    416.                     startOrbitingDistance = Random.Range(30, 40);
    417.                     if(distanceFromEnemy < startOrbitingDistance)
    418.                     {
    419.                         isChasing = false;
    420.                     }
    421.                     else
    422.                     {
    423.                         isChasing = true;
    424.                     }
    425.                 }
    426.             }
    427.             else
    428.             {
    429.                 FollowMotherShip();
    430.                 yield return new WaitForSeconds(3f);
    431.                 FindClosestEnemy();
    432.             }
    433.         }
    434.     }
    435.  
    436.     void FollowMotherShip()
    437.     {
    438.         Transform motherShip = fighterSpawner.transform;
    439.         Vector3 pos = motherShip.position;
    440.         int randomDiff = Random.Range(10, 20);
    441.         target = new Vector3(pos.x+randomDiff, pos.y+randomDiff, 0);
    442.     }
    443.  
    444.     // For enemy carriers only
    445.     IEnumerator DistFromTargetEnemyCarrier()
    446.     {
    447.         while(true)
    448.         {
    449.             if(mode == Mode.Attack)
    450.             {
    451.                 yield return wait1;
    452.                 if(mode == Mode.Attack)
    453.                 {
    454.                     closestEnemy = FindClosestEnemy();
    455.                  
    456.                     if(closestEnemy != null)
    457.                     {
    458.                         if(!isStation)
    459.                         {
    460.                             target = new Vector3(closestEnemy.position.x+targetOffset, closestEnemy.position.y+targetOffset, 0);
    461.                         }
    462.                      
    463.                         distanceFromEnemy = Vector3.Distance (transform.position, closestEnemy.position);
    464.                     }
    465.                 }
    466.             }
    467.             else
    468.             {
    469.                 yield return new WaitForSeconds(2f);
    470.  
    471.                 FindClosestEnemy();
    472.             }
    473.         }
    474.     }
    475.  
    476.     IEnumerator ClosestEnemyForStation()
    477.     {
    478.         while(true)
    479.         {
    480.             if(mode == Mode.Attack)
    481.             {
    482.                 yield return wait1;
    483.                 if(mode == Mode.Attack)
    484.                 {
    485.                     closestEnemy = FindClosestEnemy();
    486.                  
    487.                     if(closestEnemy != null)
    488.                     {
    489.                         distanceFromEnemy = Vector3.Distance(transform.position, closestEnemy.position);
    490.                     }
    491.                 }
    492.             }
    493.             else
    494.             {
    495.                 yield return new WaitForSeconds(2f);
    496.  
    497.                 FindClosestEnemy();
    498.             }
    499.         }
    500.     }
    501.  
    502.     private float curDistance;
    503.     private List <GameObject> gos;
    504.  
    505.     Transform FindClosestEnemy()
    506.     {
    507.         if(isKilled)
    508.         {
    509.             Debug.Log("Killed");
    510.             return null;
    511.         }
    512.  
    513.         Debug.Log(preferredEnemy.name);
    514.  
    515.         if(preferredEnemy == null || !preferredEnemy.gameObject.activeInHierarchy)
    516.         {
    517.             gos = new List<GameObject>();
    518.  
    519.             if(isPlayer)
    520.             {
    521.                 gos = EnemyAllyList.playerAllTargetsTmp;
    522.             }
    523.             else if(isFaction1)
    524.             {
    525.                 gos = EnemyAllyList.faction1AllTargets;
    526.             }
    527.             else if(isFaction2)
    528.             {
    529.                 gos = EnemyAllyList.faction2AllTargets;
    530.             }
    531.             else if(isPirate)
    532.             {
    533.                 gos = EnemyAllyList.pirateAllTargets;
    534.             }
    535.  
    536.             Vector3 diff;
    537.             float distance = Mathf.Infinity;
    538.  
    539.             //Debug.Log(gos.Count);
    540.  
    541.             if(gos.Count != 0)
    542.             {
    543.                 mode = Mode.Attack;
    544.             }
    545.             else
    546.             {
    547.                 if(EnemyAllyList.playerAllTargets.Count == 0 && isPlayerCarrier && mode == Mode.Attack && SceneManager.GetActiveScene().name != "Tutorial")
    548.                 {
    549.                     SaveMidGame();
    550.                     mode = Mode.Idle;
    551.                 }
    552.  
    553.                 if(isEnemyCarrier)
    554.                 {
    555.                     diff = target - transform.position;
    556.                     distance = diff.sqrMagnitude;
    557.  
    558.                     if(distance < 100)
    559.                     {
    560.                         target = new Vector3(transform.position.x+Random.Range(-100, 100), transform.position.y+Random.Range(-100, 100), 0);
    561.                     }
    562.  
    563.                     mode = Mode.Idle;
    564.                 }
    565.  
    566.                 return null;
    567.             }
    568.          
    569.             GameObject closest = null;
    570.             Vector3 position = transform.position;
    571.  
    572.             //Debug.Log("All GOS:  "+gos.Count);
    573.          
    574.             foreach (GameObject go in gos)
    575.             {
    576.                 diff = go.transform.position - position;
    577.                 curDistance = diff.sqrMagnitude;
    578.  
    579.                 if(curDistance < 300) // Problem with this. Opening repair while enemy present
    580.                 {
    581.                     continue;
    582.                 }
    583.                 if (curDistance < distance)
    584.                 {
    585.                     closest = go;
    586.                     distance = curDistance;
    587.                 }
    588.             }
    589.             if(closest != null)
    590.             {
    591.                 return closest.transform;
    592.             }
    593.             else
    594.             {
    595.                 if(isEnemyCarrier)
    596.                 {
    597.                     diff = target - transform.position;
    598.                     distance = diff.sqrMagnitude;
    599.  
    600.                     if(distance < 100)
    601.                     {
    602.                         target = new Vector3(transform.position.x+Random.Range(-50, 50), transform.position.y+Random.Range(-50, 50), 0);
    603.                     }
    604.                 }
    605.  
    606.                 mode = Mode.Idle;
    607.                 return null;
    608.             }
    609.         }
    610.         else
    611.         {
    612.             if(EnemyAllyList.playerEnemies.Contains(preferredEnemy.tag)) //EnemyAllyList.playerEnemiesTmp.Contains(preferredEnemy.tag) ||
    613.             {
    614.                 return preferredEnemy;
    615.             }
    616.             else
    617.             {
    618.                 return null;
    619.             }
    620.          
    621.         }
    622.     }
    623.  
    624.     void SaveMidGame()
    625.     {
    626.         shipStats.SaveHullNShied();
    627.  
    628.         if(!pageManager.isAlreadySaved)
    629.         {
    630.             pageManager.SaveEverythingMidGame();
    631.         }
    632.     }
    633.     void FixedUpdate()
    634.     {
    635.         if(isPlayerCarrier)
    636.         {
    637.             MoveForward();
    638.             if(speed > 0.4f)
    639.             {
    640.                 if(distanceFromWaypoint > 5)
    641.                 {
    642.                     RotateTowardTarget(targetWaypoint.position, transform.position);
    643.                 }
    644.                 else
    645.                 {
    646.                     transform.rotation = Quaternion.Slerp(transform.rotation, carrierTargetRotation, Time.deltaTime * rotateSpeed);
    647.                 }
    648.             }
    649.         }
    650.  
    651.         else if(isPlayerFighter || isEnemyFighter)
    652.         {
    653.             if(isChasing || mode == Mode.Idle)
    654.             {
    655.                 MoveForward();
    656.                 RotateTowardTarget(new Vector2(target.x, target.y+rotateTowardOffset), transform.position);
    657.             }
    658.             else if(mode == Mode.Attack)
    659.             {
    660.                 transform.RotateAround(target, zAxis, Time.deltaTime * speed);
    661.                 RotateTowardTarget(target, transform.position);
    662.             }
    663.         }
    664.  
    665.         else if(isEnemyCarrier)
    666.         {
    667.             if(mode == Mode.Attack)
    668.             {
    669.                 MoveForward();
    670.                 RotateTowardTarget(target, transform.position);
    671.             }
    672.             else if(isEnemyFleeing)
    673.             {
    674.                 StartCoroutine(mainScript2.HyperJumpEnemy());
    675.                 isEnemyFleeing = false;
    676.             }
    677.             else if(mode == Mode.Idle)
    678.             {
    679.                 MoveForward();
    680.                 RotateTowardTarget(target, transform.position);
    681.             }
    682.         }
    683.         else if(isStation && !isKilled)
    684.         {
    685.             transform.Rotate(0, 0, -rotateSpeed * Time.deltaTime);
    686.         }
    687.         else if(isEnemyFreighter)
    688.         {
    689.             MoveForward();
    690.             RotateTowardTarget(target, transform.position);
    691.         }
    692.     }
    693.  
    694.     IEnumerator FreighterWaypoint()
    695.     {
    696.         target = freighterFirstWP;
    697.         while(!isKilled)
    698.         {
    699.             distanceFromWaypoint = Vector3.Distance(transform.position, freighterFirstWP);
    700.              
    701.             if(distanceFromWaypoint < 15) //  && !preparingHyperJump
    702.             {
    703.                 StartCoroutine(LerpSpeedCarrier(0, 2f));
    704.                 break;
    705.             }
    706.             yield return new WaitForSeconds(2f);
    707.         }
    708.  
    709.         yield return new WaitForSeconds(15f);
    710.  
    711.         Vector3 currentPos = targetMover.aILerp.transform.position;
    712.         Transform nextNode = mainScript2.GetClosestNode(pageManager.mapNodes, currentPos);
    713.         ShipSpawner.enemyFleetJumpedToSceneName = nextNode.name;
    714.         Vector3 targetDirEnter = (nextNode.position - currentPos).normalized;
    715.  
    716.         isEnemyFleeing = true;
    717.         target += targetDirEnter * 300;
    718.  
    719.         StartCoroutine(mainScript2.HyperJumpEnemy());
    720.     }
    721.  
    722.     [HideInInspector] public bool isEnemyFleeing = false;
    723.  
    724.     void MoveForward()
    725.     {
    726.         if(isPlayerCarrier && isThrusterOn && shipStats.energyShip > 0)
    727.         {
    728.             transform.position += transform.right * speed * 2 * Time.deltaTime;
    729.         }
    730.         else
    731.         {
    732.             transform.position += transform.right * speed * Time.deltaTime;
    733.         }
    734.     }
    735.  
    736.     void RotateTowardTarget(Vector2 targ, Vector2 pos)
    737.     {
    738.         Vector2 vectorToTarget = targ - pos;
    739.         float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
    740.         Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
    741.         transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * rotateSpeed);
    742.     }
    743.  
    744.     [HideInInspector] public bool isKilled = false;
    745.  
    746.     public void Killed()
    747.     {
    748.         if(!isKilled)
    749.         {
    750.             tag = "Untagged";
    751.             isKilled = true;
    752.  
    753.             if(!isStation)
    754.             {
    755.                 StartCoroutine(LerpSpeedCarrier(0.5f, 3f));
    756.             }
    757.          
    758.             StartCoroutine(mainScript2.DeathExplosion());
    759.         }
    760.     }
    761.  
    762.     void OnDisable()
    763.     {
    764.         if((isPlayerFighter || isEnemyFighter) && fighterSpawner != null)
    765.         {
    766.             fighterSpawner.spawnedFighters.Remove(gameObject);
    767.         }
    768.  
    769.         if(isKilled)
    770.         {
    771.             if(pirateHunt != null)
    772.             {
    773.                 pirateHunt.pirateCount--;
    774.                 if(pirateHunt.pirateCount == 0 && pirateHunt.numberOfWaypoints != 0)
    775.                 {
    776.                     pirateHunt.SpawnPirateNextBatch();
    777.                 }
    778.                 else if(pirateHunt.pirateCount == 0 && pirateHunt.numberOfWaypoints == 0)
    779.                 {
    780.                     pirateHunt.MissionCompleted();
    781.                 }
    782.             }
    783.             else if(defenceMission != null)
    784.             {
    785.                 defenceMission.enemyShipsCount--;
    786.                 if(defenceMission.enemyShipsCount == 0)
    787.                 {
    788.                     defenceMission.MissionCompleted();
    789.                 }
    790.             }
    791.         }
    792.     }
    793. }
     
    Last edited: Jun 4, 2022
  2. lordconstant

    lordconstant

    Joined:
    Jul 4, 2013
    Posts:
    389
    You at least know its in FindClosestEnemy so normally you step through checking each thing that could be null & when its used unsafely (no null checks).

    If that doesnt give you an obvious answer then create a development build & tick wait for the debugger. Then attach your preferred IDE to debug the application.

    In this case your using Debug.Log on preferredEnemy.name before the null check.
     
    Only4gamers likes this.