Search Unity

Help please.

Discussion in 'Editor & General Support' started by roninruggs, Jan 11, 2019.

  1. roninruggs

    roninruggs

    Joined:
    Jun 30, 2018
    Posts:
    2
    in Unity 2018.2.20f1:
    I am making a top down shooter(2d) and have a enemy class for all enemy AI to derive from. Pretty simple.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class AI : MonoBehaviour {
    6.  
    7.     public int health;
    8.     public float speed;
    9.  
    10.     public float timeTweenAttack;
    11.    
    12.     [HideInInspector]
    13.     public Transform player;
    14.  
    15.     public int damage;
    16.  
    17.     // Use this for initialization
    18.     void Start () {
    19.  
    20.         player = GameObject.FindGameObjectWithTag("Player").transform;
    21.     }
    22.    
    23.     // Update is called once per frame
    24.     void Update () {
    25.        
    26.     }
    27.  
    28.     public void takedamage(int damageAmount)
    29.     {
    30.         health -= damageAmount;
    31.         if (health <= 0)
    32.         {
    33.             Destroy(this.gameObject);
    34.         }
    35.     }
    36. }
    And yet, player = GameObject.FindGameObjectWithTag("Player").transform; throws up a Object not set to an instance of an object. Error. The player is a prefab, if that matters.

    What do I do?
     
  2. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    Where do you define GameObject?
     
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You don't have a GameObject tagged with "Player" active in the scene at the time this Start method is called. If you are later instantiating this object, wait until it exists before you try to grab a reference to it. Or better yet, just cache the reference Instantiate returns in the first place.
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
  5. roninruggs

    roninruggs

    Joined:
    Jun 30, 2018
    Posts:
    2
    I have a Player tagged as player at the start of the scene. It exists when the enemy is instantiated
     
  6. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    Please show the code where it is instantiated. It's not in scope in this script.