Search Unity

Object reference not set to an instance of an Object C#

Discussion in 'Scripting' started by georetro, Feb 4, 2014.

  1. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    Make sure the object has a rigidbody attached to it
     
  2. RuneMaster98

    RuneMaster98

    Joined:
    Jan 21, 2016
    Posts:
    1
    I'm having the same issue as King_Chaos but my script does contain a private Rigidbody rb; line directly beneath the public class PlayerController: MonoBehaviour {

    I followed the instructions laid out by the roll a ball tutorial exactly but I still get the error where the tutor says none should turn up.
    I'm a massive n00b so pls help...
     
  3. ashokbugude

    ashokbugude

    Joined:
    Feb 10, 2016
    Posts:
    20
    I am having the same same issue in RogueLike tutorial game in enemy.cs file when 1st level completes. Below is the code

    protected override void Start ()
    {
    //Register this enemy with our instance of GameManager by adding it to a list of Enemy objects.
    //This allows the GameManager to issue movement commands.
    GameManager.instance.AddEnemyToList (this);

    //Get and store a reference to the attached Animator component.
    animator = GetComponent<Animator> ();

    //Find the Player GameObject using it's tag and store a reference to its transform component.
    target = GameObject.FindGameObjectWithTag ("Player").transform;

    int x = Random.Range(1, 8);
    int y = Random.Range(1, 8);

    transform.position = new Vector3(x, y, 0);

    //Call the start function of our base class MovingObject.
    base.Start ();
    }
     
  4. kyllella2018

    kyllella2018

    Joined:
    Feb 12, 2016
    Posts:
    1
    Good Day, I'm new to using unity and I'm having a problem with my game, this was the error I got:

    NullReferenceException: Object reference not set to an instance of an object
    TextBoxManager.DisableTextBox () (at assets/scripts/Dialog/TextBoxManager.cs:84)
    TextBoxManager.Start () (at assets/scripts/Dialog/TextBoxManager.cs:45)

    Here is my code for TextBoxManager:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;

    public class TextBoxManager : MonoBehaviour {

    public GameObject textBox;

    public Text theText;

    public TextAsset textFile;
    public string[] textLines;

    public int currentLine;
    public int endAtLine;

    public PlayerMovement player;

    public bool isActive;

    public bool stopPlayerMovement;

    // Use this for initialization
    void Start()
    {
    player = FindObjectOfType<PlayerMovement>();
    if (textFile != null)
    {
    textLines = (textFile.text.Split('\n'));
    }
    if (endAtLine == 0)
    {
    endAtLine = textLines.Length - 1;
    }
    if (isActive)
    {
    EnableTextBox();
    }
    else
    {
    DisableTextBox();
    }
    }

    void Update()
    {
    if (!isActive)
    {
    return;
    }
    theText.text = textLines[currentLine];
    if (Input.GetKeyDown(KeyCode.Space))
    {
    currentLine += 1;
    }
    if (currentLine > endAtLine)
    {
    DisableTextBox();
    }
    }

    public void EnableTextBox()
    {
    textBox.SetActive(true);
    if (stopPlayerMovement)
    {
    player.canMove = false;
    }
    }

    public void DisableTextBox()
    {
    textBox.SetActive(false);
    player.canMove = true;
    }
    }

    and here's the one for PlayerMovement:

    using UnityEngine;
    using System.Collections;

    public class PlayerMovement : MonoBehaviour {

    Rigidbody2D rbody;
    Animator anim;

    public bool canMove;

    // Use this for initialization
    void Start () {
    rbody = GetComponent<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
    }

    // Update is called once per frame
    void Update () {
    if (!canMove)
    {
    anim.SetBool("iswalking", false);
    return;
    }
    Vector2 movement_vector = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
    if (movement_vector != Vector2.zero) {
    anim.SetBool ("iswalking", true);
    anim.SetFloat ("input_x", movement_vector.x);
    anim.SetFloat ("input_y", movement_vector.y);
    } else {
    anim.SetBool ("iswalking", false);
    }
    rbody.MovePosition (rbody.position + movement_vector * Time.deltaTime);
    }
    }

    I'm using the latest version of unity, it'll be a big help if someone could help me fix this, thanks in advance.
     
  5. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    Use code tags please.

    It looks like the object textBox isn't being assigned.

    NullReferenceException means you're trying to do something to a value that doesn't exist (Referencing a null).

    MAKE SURE you have textBox being assigned in the inspector or somewhere in your script.
     
  6. TheJerma45

    TheJerma45

    Joined:
    Feb 25, 2016
    Posts:
    1
    I have a similar error with my code's:
    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.Update () (at Assets/PlayerController.cs:28)

    Playercontroller script:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. [RequireComponent(typeof(PlayerMotor))]
    4. public class PlayerController : MonoBehaviour {
    5.  
    6.     [SerializeField]
    7.     private float speed = 5f;
    8.  
    9.     private PlayerMotor motor;
    10.  
    11.     void start()
    12.     {
    13.         motor = GetComponent<PlayerMotor>();
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         float _xMov = Input.GetAxisRaw("Horizontal");
    19.         float _zMov = Input.GetAxisRaw("Vertical");
    20.  
    21.         Vector3 _movHorizontal = transform.right * _xMov;
    22.         Vector3 _movVertical = transform.forward * _zMov;
    23.  
    24.         // final movement
    25.         Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
    26.  
    27.         //Apply movement
    28.         motor.Move(_velocity);
    29.  
    30.     }
    31. }
    32.  
    And my PlayerMovement script:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. [RequireComponent(typeof(Rigidbody))]
    5.  
    6. public class PlayerMotor : MonoBehaviour
    7. {
    8.     private Vector3 velocity = Vector3.zero;
    9.  
    10.     private Rigidbody rb;
    11.  
    12.     void start  ()
    13.     {
    14.         rb = GetComponent<Rigidbody>();
    15.     }
    16.  
    17.     public void Move (Vector3 _velocity)
    18.     {
    19.         velocity = _velocity;
    20.     }
    21.  
    22.     void FixedUpdate ()
    23.     {
    24.         PerformMovement();
    25.     }
    26.  
    27.     void PerformMovement ()
    28.     {
    29.         if (velocity != Vector3.zero)
    30.         {
    31.             rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
    32.         }
    33.     }
    34.  
    35. }
    36.  
     
  7. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    Change start() in both scripts to Start()
     
  8. cybercutte

    cybercutte

    Joined:
    Nov 15, 2015
    Posts:
    31
    i have same problem

    NullReferenceException: Object reference not set to an instance of an object
    bangsat.OnMouseDown () (at Assets/bangsat.cs:22)
    UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)



    i have 4 cubes,
    h1, h2, h3, h4
    click h1 show cube h2
    click h3 show h4 but destroy h2 if enable/true

    script bangsat into h1 to show h2 and destroy h4 if enable

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class bangsat : MonoBehaviour {
    5.  
    6.     private GameObject peki;
    7.     private GameObject peka;
    8.    
    9.     // Use this for initialization
    10.     void Start () {
    11.         peka = GameObject.Find("h2");
    12.         peki = GameObject.Find("h4");
    13.         peka.SetActive(false);
    14.         peki.SetActive(false);
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     void Update () {
    19.        
    20.     }
    21.     void OnMouseDown(){
    22.         peki.SetActive(true);
    23.         peka.SetActive (false);
    24.     }
    25. }
    script kecoa into h3 to show h4 and destroy h2 if enable

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class kecoa : MonoBehaviour {
    5.  
    6.     private GameObject peki;
    7.     private GameObject peka;
    8.    
    9.     // Use this for initialization
    10.     void Start () {
    11.         peka = GameObject.Find("h2");
    12.         peki = GameObject.Find("h4");
    13.         peka.SetActive(false);
    14.         peki.SetActive(false);
    15.     }
    16.    
    17.     // Update is called once per frame
    18.     void Update () {
    19.        
    20.     }
    21.     void OnMouseDown(){
    22.         peki.SetActive (true);
    23.         peka.SetActive(false);
    24.     }
    25. }
    26.  
     
  9. arefin_siam98

    arefin_siam98

    Joined:
    Mar 20, 2016
    Posts:
    5
    Hello, I am facing that same kind of problem and being a very beginner in C# ,i can't figure out what to do ,and have been following "Survival Shooter Tutorial"

    MY en_attack script is :

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class e_attack : MonoBehaviour {
    5.     public float timeBA= 0.5f;
    6.     public int am=10;
    7.     Animator anim;
    8.     GameObject player;
    9.     float timer;
    10.     p_health health_script;
    11.     bool inRange;
    12.  
    13.     // Use this for initialization
    14.     void Awake () {
    15.         player = GameObject.FindGameObjectWithTag ("Player");
    16.         health_script = GetComponent<p_health> ();
    17.         anim = GetComponent<Animator> ();
    18.    
    19.     }
    20.     void OnTriggerEnter(Collider other){
    21.         if (other.gameObject == player) {
    22.             inRange=true;
    23.                 }
    24.         }
    25.     void OnTriggerExit(Collider other){
    26.         if (other.gameObject != other) {
    27.             inRange=false;
    28.                 }
    29.         }
    30.  
    31.  
    32.  
    33.     // Update is called once per frame
    34.     void Update () {
    35.         timer += Time.deltaTime;
    36.         if (timer >= timeBA && inRange) {
    37.             Attack();
    38.                 }
    39.         if (health_script.c_h <= 0) {
    40.             anim.SetTrigger("PlayerDead");
    41.                 }
    42.  
    43.    
    44.     }
    45.     void Attack(){
    46.         timer = 0f;
    47.         if (health_script.c_h > 0) {
    48.             health_script.TakeDam(am);
    49.                 }
    50.  
    51.  
    52.     }
    53. }
    54.  
    HERE :p_health is a script i attached to my player. And continuously getting the following error :
    NullReferenceException: Object reference not set to an instance of an object
    e_attack.Attack () (at Assets/e_attack.cs:47)
    e_attack.Update () (at Assets/e_attack.cs:37)
    As i've figured out these two lines are -
    47 : if (health_script.c_h > 0)
    37: Attack();

    Please Help, I am stuck there :'( :( :(
     
  10. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    so "health_script" is null, which suggests the current object doesn't have a "p_health" component attached to it (from the initialisation on line 16)...
     
    arefin_siam98 likes this.
  11. arefin_siam98

    arefin_siam98

    Joined:
    Mar 20, 2016
    Posts:
    5
    Should i attach "p_health" component to my enemy? If so, i have done so getting the same error.
    N.B. All my scripts are under Assets folder. Could that be a cause? :(
     
  12. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    I think you might have mistyped line 14.

    Given that the script that it is looking for is "p_health" and line 13 just got a reference to the player you probably need

    Code (csharp):
    1.  
    2. health_script = player.GetComponent<p_health>();
    3.  
    i.e. get the "p_health" script from the "player" gameobject, not the current gameobject.
     
    arefin_siam98 likes this.
  13. arefin_siam98

    arefin_siam98

    Joined:
    Mar 20, 2016
    Posts:
    5
    That kinda makes a bit sense. Though i deleted previous one.Let me start once again. Appreciate your kind effort.Thanks buddy . (Y)
     
  14. kave.design

    kave.design

    Joined:
    Jun 1, 2016
    Posts:
    1
    Hi everyone,
    I got the same problem, I have installed Vuforia on Unity and using it to publish my app.
    but I can not publish the app, Unity tells me " NullReferenceException: Object reference not set to an instance of an object
    UnityEditor.Android.PostProcessAndroidPlayer..ctor ()"
    and also: " UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:316)
    UnityEditor.HostView:OnGUI() "

    I really do appreciate if some can help me to fix this problem.
    Big thanks in advance,
     
  15. cybercutte

    cybercutte

    Joined:
    Nov 15, 2015
    Posts:
    31
    please edit your text, and put script to insert > code, soo we can see your problem
     
  16. dijerar

    dijerar

    Joined:
    Jul 2, 2016
    Posts:
    1
    NullReferenceException: Object reference not set to an instance of an object
     
  17. kenncann

    kenncann

    Joined:
    Jul 16, 2015
    Posts:
    5
    I had this problem because I was trying to use GameObject.Find on a UI element that I was setting to inactive during awake. I solved my problem by making the UI element inactive during Start and Finding that UI element in my other scripts during awake (you can also play with setting the script orders in project settings)
     
  18. chazz85

    chazz85

    Joined:
    Aug 8, 2014
    Posts:
    5
    I saw this thread was helping with this issue and i have a pretty complex verison of it.

    Shooting script segment
    [Command]
    void CmdPlayerShot ( int _damage )
    {


    Debug.Log("fired");
    //charactercontroller _player = GameManager.GetPlayer(_playerID);
    player.Instance.RpcTakeDamage(_damage);
    }

    Ok so whats happening is on the last line of code it's giving me a object reference not set to an instance of and object error yet the RPC and the player exist.
    [ClientRpc]
    public void RpcTakeDamage(int _amount)
    {
    Debug.Log("test");
    health -= _amount;
    }
    Thanks for any advice in advance.
     
  19. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    if you're getting a null ref error from
    Code (csharp):
    1.  
    2. player.Instance.RpcTakeDamage(_damage);
    3.  
    either player is null, or player.Instance is null... how are they being set?


    (having said that, null ref errors are so generic having "one thread" on them is practically useless since the problems are always project/script specific. It's a generic "something you think should be there isn't" which isn't ever going to have a single solution :rolleyes: )
     
  20. helder227

    helder227

    Joined:
    Nov 9, 2016
    Posts:
    1
    Hi Hello Every One
    Hi Have Start a Game And I Have Similar Problem With My Script
    My Script Come With One Error

    How To Handle With This Error
    Can Some One Help Me With My script PLS.
    NullReferenceException object reference not set to an instance of an object Health.start()

    This Is My Code

    using UnityEngine;
    using UnityEngine.UI;
    using System.Collections;

    public class health : MonoBehaviour
    {
    public Slider healthBar;


    // Use this for initialization
    void Start ()
    {
    healthBar.value = 100;
    }
    void OnTrigerStay(Collider col)
    {
    if (col.gameObject.tag == "Enemy")
    {
    healthBar.value -= 2;
    }
    }

    // Update is called once per frame
    void Update () {

    }
    }
     
  21. keroleung

    keroleung

    Joined:
    Oct 24, 2016
    Posts:
    4
    I have the problem of "UnassignedReferenceException: The variable gameOverUI of bulletControl has not been assigned." Can someone help me? :( This is my first CSharp game:(


    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5.  
    6. public class bulletControl : MonoBehaviour
    7. {
    8.  
    9.  
    10.  
    11.     GameObject scoreUITextGO;
    12.     GameObject livesTextUIGO;
    13.     public GameObject gameOverUI;
    14.  
    15.     int HPNum;
    16.  
    17.  
    18.  
    19.     public float degreesPerSec = 360f;
    20.  
    21.     float speed;
    22.     Vector2 _direction;
    23.     bool isReady;
    24.  
    25.     public bool hit_Bln;
    26.  
    27.     void Start ()
    28.     {
    29.         speed = 3.5f;
    30.         scoreUITextGO = GameObject.FindGameObjectWithTag ("ScoreTextTag");
    31.         livesTextUIGO = GameObject.FindGameObjectWithTag ("LivesTextTag");
    32.         //gameOverUI = GameObject.FindGameObjectWithTag ("GameController");
    33.     }
    34.  
    35.     public void EndGame ()
    36.     {
    37.         Debug.Log ("GAME OVER");
    38.         gameOverUI.SetActive (true);
    39.         //gameOverUI = GameObject.FindGameObjectWithTag ("GameController");
    40.         //GameObject gameOverUI = GameObject.Find ("GameOver");
    41.        
    42.  
    43.     }
    44.  
    45.  
    46.  
    47.  
    48.  
    49.     // Update is called once per frame
    50.     void Update () {
    51.  
    52.  
    53.         float rotAmount = degreesPerSec * Time.deltaTime;
    54.         float curRot = transform.localRotation.eulerAngles.z;
    55.         transform.localRotation = Quaternion.Euler(new Vector3(0,0,curRot+rotAmount));
    56.  
    57.         Vector2 position = transform.position;
    58.  
    59.         position = new Vector2 (position.x, position.y - speed * Time.deltaTime);
    60.  
    61.         transform.position = position;
    62.  
    63.         Vector2 min = Camera.main.ViewportToWorldPoint (new Vector2 (0, 0));
    64.  
    65.             if (transform.position.y < min.y)
    66.            
    67.  
    68.             {
    69.  
    70.                 Destroy (gameObject);
    71.         }
    72.  
    73.  
    74.  
    75.         if (hit_Bln) {
    76.             HPNum = int.Parse (livesTextUIGO.GetComponent<Text> ().text);
    77.             HPNum -= 1;
    78.    
    79.  
    80.             livesTextUIGO.GetComponent<Text> ().text = HPNum.ToString ();
    81.             hit_Bln = false;
    82.  
    83.  
    84.             if (HPNum <= 0) {
    85.  
    86.                 EndGame ();
    87.  
    88.             }
    89.             else{
    90.                 Destroy (gameObject);
    91.         }
    92.            
    93.  
    94.     }
    95.     }
    96.  
    97.     void OnTriggerEnter2D(Collider2D col)
    98.     {
    99.  
    100.         if (col.tag == "PlayerTag" ) {
    101.  
    102.             scoreUITextGO.GetComponent<GameScore> ().Score += 1;
    103.  
    104.    
    105.  
    106.                 Destroy (gameObject);
    107.             }
    108.  
    109.         if (col.tag == "DestoryWall_bottom") {
    110.             hit_Bln = true;
    111.             print (col.tag);
    112.  
    113.  
    114.  
    115.         }
    116.     }
    117. }
     
  22. 1uu1

    1uu1

    Joined:
    Dec 15, 2016
    Posts:
    1
    using UnityEngine;
    using System.Collections;

    public class RigthOne : MonoBehaviour {

    private GameObject mcircle;

    void start() {
    mcircle = GameObject.Find ("mine circle");
    }

    void OnMouseDown() {

    if (GetComponent <Renderer> ().material.color == mcircle.GetComponent <Renderer> ().material.color)
    mcircle.GetComponent <GameCntrl> ().next = true;
    else
    mcircle.GetComponent <GameCntrl> ().lose = true;
    }
    }
     
  23. nstamen0vah

    nstamen0vah

    Joined:
    Jan 28, 2017
    Posts:
    1
    Hi,
    I am trying to make a PinchZoom as shown in the Beginners Tutorial (https://unity3d.com/learn/tutorials/topics/mobile-touch/pinch-zoom) . However, my script gives:
    NullReferenceException: Object reference not set to an instance of an object
    PinchZoom..ctor () (at Assets/PinchZoom.cs:10)

    and I am not really sure what to do. This is my script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PinchZoom : MonoBehaviour
    6. {
    7.     public float perspectiveZoomSpeed = 0.5f;        // The rate of change of the field of view in perspective mode.
    8.     public float orthoZoomSpeed = 0.5f;        // The rate of change of the orthographic size in orthographic mode.
    9.     public static GameObject other;
    10.     public new Camera camera = other.GetComponent<Camera>();
    11.  
    12.  
    13.  
    14.     void Start()
    15.     {
    16.         // If there are two touches on the device...
    17.         if (Input.touchCount == 2)
    18.         {
    19.             // Store both touches.
    20.             Touch touchZero = Input.GetTouch(0);
    21.             Touch touchOne = Input.GetTouch(1);
    22.  
    23.             // Find the position in the previous frame of each touch.
    24.             Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
    25.             Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
    26.  
    27.             // Find the magnitude of the vector (the distance) between the touches in each frame.
    28.             float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
    29.             float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
    30.  
    31.             // Find the difference in the distances between each frame.
    32.             float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
    33.  
    34.             // If the camera is orthographic...
    35.             if (camera.orthographic)
    36.             {
    37.                 // ... change the orthographic size based on the change in distance between the touches.
    38.                 camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
    39.  
    40.                 // Make sure the orthographic size never drops below zero.
    41.                 camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
    42.             }
    43.             else
    44.             {
    45.                 // Otherwise change the field of view based on the change in distance between the touches.
    46.                 camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
    47.  
    48.                 // Clamp the field of view to make sure it's between 0 and 180.
    49.                 camera.fieldOfView = Mathf.Clamp(camera.fieldOfView, 0.1f, 179.9f);
    50.             }
    51.         }
    52.     }
    53. }
    54.  
    55.  
     
  24. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    check line 10, you use the 'new' keyword should not be used when defining a field, but only when instantiating a (non-monobehaviour) object.
     
  25. Daam455

    Daam455

    Joined:
    Apr 15, 2017
    Posts:
    2
    Hey guys i got this error,

    NullReferenceException: Object reference not set to an instance of an object
    PlayerWeaponController.EquipWeapon (.Item itemToEquip) (at Assets/Scripts/PlayerWeaponController.cs:26)
    InventoryController.Update () (at Assets/Scripts/InventoryController.cs:21)

    but i cant seem to find out what i do wrong.
    This is my PlayerWeaponController:
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class PlayerWeaponController : MonoBehaviour {
    7.     public GameObject playerHand;
    8.     public GameObject EquippedWeapon { get; set; }
    9.  
    10.     IWeapon equippedWeapon;
    11.     CharacterStats characterStats;
    12.  
    13.     void Start()
    14.     {
    15.         characterStats = GetComponent<CharacterStats>();
    16.     }
    17.  
    18.     public void EquipWeapon(Item itemToEquip)
    19.     {
    20.         if (EquippedWeapon != null)
    21.         {
    22.             characterStats.RemoveStatBonus(EquippedWeapon.GetComponent<IWeapon>().Stats);
    23.             Destroy(playerHand.transform.GetChild(0).gameObject);
    24.         }
    25.         EquippedWeapon = (GameObject)Instantiate(Resources.Load<GameObject>("Weapons/" + itemToEquip.ObjectSlug), playerHand.transform.position, playerHand.transform.rotation);
    26.         equippedWeapon = EquippedWeapon.GetComponent<IWeapon>();
    27.         equippedWeapon.Stats = itemToEquip.Stats;
    28.         EquippedWeapon.transform.SetParent(playerHand.transform);
    29.         characterStats.AddStatBonus(itemToEquip.Stats);
    30.         Debug.Log(equippedWeapon.Stats[0].GetCalculatedStatValue());
    31.     }
    32.  
    33.     public void PerformWeaponAttack()
    34.     {
    35.         equippedWeapon.PerformAttack();
    36.     }
    37. }
    38.  
    and this is my InventoryController:
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class InventoryController : MonoBehaviour {
    7.     public PlayerWeaponController playerWeaponController;
    8.     public Item Sword;
    9.  
    10.     void Start()
    11.     {
    12.         playerWeaponController = GetComponent<PlayerWeaponController>();
    13.         List<BaseStats> swordStats = new List<BaseStats>();
    14.         swordStats.Add(new BaseStats(6, "Power", "Your Power Level."));
    15.         Sword = new Item(swordStats, "Sword");
    16.     }
    17.  
    18.     void Update()
    19.     {
    20.         if (Input.GetKeyDown(KeyCode.V))
    21.         {
    22.             playerWeaponController.EquipWeapon(Sword);
    23.         }
    24.     }
    25.  
    26. }
    27.  
    im stuck here almost 2 hours now and i cant really find out where i do wrong, so please hep !
     
  26. ChepeBlak

    ChepeBlak

    Joined:
    May 17, 2017
    Posts:
    1
    I have been gettin the -NullReferenceException: Object reference not set to an instance of an object Pokemon.NewMethod at (Assets/Pokemon.cs:18) Help please. I dont know what to do.
     

    Attached Files:

  27. MrVylon

    MrVylon

    Joined:
    May 31, 2017
    Posts:
    1
    Hey i have the same errror,
    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.Start () (at Assets/PlayerController.cs:18)
    and
    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.FixedUpdate () (at Assets/PlayerController.cs:23).

    my script looks like that:

    using UnityEngine;
    using System.Collections;

    public class PlayerController : MonoBehaviour
    {
    public float speed = 10, jumpVelocity = 10;
    public LayerMask playerMask;
    Transform myTrans, tagGround;
    Rigidbody2D myBody;

    public bool isGrounded = false;


    void Start()
    {
    myBody = this.GetComponent<Rigidbody2D>();
    myTrans = this.transform;
    tagGround = GameObject.Find(this.name + "/Ground").transform;
    }

    void FixedUpdate()
    {
    isGrounded = Physics2D.Linecast(myTrans.position, tagGround.position, playerMask);

    Move(Input.GetAxis("Horizontal"));
    if (Input.GetButtonDown("Jump"))
    Jump();

    }

    public void Move(float horizontalInput)
    {
    Vector2 moveVel = myBody.velocity;
    moveVel.x = horizontalInput * speed;
    myBody.velocity = moveVel;

    }

    public void Jump()
    {
    if(isGrounded)
    myBody.velocity += jumpVelocity * Vector2.up;
    }

    }


    pls help :D,i dont know whta to do.
     
  28. Evan123456

    Evan123456

    Joined:
    Oct 29, 2017
    Posts:
    1
    Can you help me? i have the same problem with this code


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class DreamCar01Track : MonoBehaviour {

    public GameObject TheMarker;
    public GameObject Mark01;
    public GameObject Mark02;
    public GameObject Mark03;
    public GameObject Mark04;
    public GameObject Mark05;
    public GameObject Mark06;
    public GameObject Mark07;
    public GameObject Mark08;
    public GameObject Mark09;
    public GameObject Mark10;
    public GameObject Mark11;
    public GameObject Mark12;
    public GameObject Mark13;
    public GameObject Mark14;
    public GameObject Mark15;
    public int MarkTracker;

    void Update()
    {
    if (MarkTracker == 0)
    {
    TheMarker.transform.position = Mark01.transform.position;
    }
    if (MarkTracker == 1)
    {
    TheMarker.transform.position = Mark02.transform.position;
    }
    if (MarkTracker == 2)
    {
    TheMarker.transform.position = Mark03.transform.position;
    }
    if (MarkTracker == 3)
    {
    TheMarker.transform.position = Mark04.transform.position;
    }
    if (MarkTracker == 4)
    {
    TheMarker.transform.position = Mark05.transform.position;
    }
    if (MarkTracker == 5)
    {
    TheMarker.transform.position = Mark06.transform.position;
    }
    if (MarkTracker == 6)
    {
    TheMarker.transform.position = Mark07.transform.position;
    }
    if (MarkTracker == 7)
    {
    TheMarker.transform.position = Mark08.transform.position;
    }
    if (MarkTracker == 8)
    {
    TheMarker.transform.position = Mark09.transform.position;
    }
    if (MarkTracker == 9)
    {
    TheMarker.transform.position = Mark10.transform.position;
    }
    if (MarkTracker == 10)
    {
    TheMarker.transform.position = Mark11.transform.position;
    }
    if (MarkTracker == 11)
    {
    TheMarker.transform.position = Mark12.transform.position;
    }
    if (MarkTracker == 12)
    {
    TheMarker.transform.position = Mark13.transform.position;
    }
    if (MarkTracker == 13)
    {
    TheMarker.transform.position = Mark14.transform.position;
    }
    if (MarkTracker == 14)
    {
    TheMarker.transform.position = Mark15.transform.position;
    }


    }

    IEnumerator OnTriggerEnter(Collider collision)
    {
    if (collision.gameObject.tag == "Dreamcar01")
    {
    this.GetComponent<BoxCollider>().enabled = false;
    MarkTracker += 1;
    if (MarkTracker == 15)
    {
    MarkTracker = 0;
    }
    yield return new WaitForSeconds(1);
    this.GetComponent<BoxCollider>().enabled = true;
    }
    }
    }
    on the line that is bolded, it says error-
    NullReferenceException: Object reference not set to an instance of an object
    UnityStandardAssets.Utility.WaypointProgressTracker.Update () (at Assets/Standard Assets/Utility/WaypointProgressTracker.cs:96)
     
  29. gabalcazar02

    gabalcazar02

    Joined:
    Nov 10, 2017
    Posts:
    9
    i also have a problem please help, i am only a beginner in unity.
    cant understand the problem of " Object reference not set to an instance of an Object C# " it appears in line 38
     

    Attached Files:

  30. pk_Holzbaum

    pk_Holzbaum

    Joined:
    Jul 26, 2012
    Posts:
    84
    Please post the code directly on the forums and use Code Tags to format it. It makes it easier to analyze the code.
    Probably your 'gameCodes' variable is null and therefore doesn't reference an object. I suspect that your line in the Awake() method doesn't find any object with this type. Or the object has already been destroyed before calling Submit().
     
  31. gabalcazar02

    gabalcazar02

    Joined:
    Nov 10, 2017
    Posts:
    9
    okay thank you :) this is big help for me
     
  32. gabalcazar02

    gabalcazar02

    Joined:
    Nov 10, 2017
    Posts:
    9
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using UnityEngine.SceneManagement;
    6.  
    7. public class Scene2Codes : MonoBehaviour
    8. {
    9.     public Button returnMap;
    10.     public Button A;
    11.     public InputField wordCreated;
    12.     public Text count;
    13.  
    14.     private int level = 0;
    15.     private GameCodes gameCodes1;
    16.  
    17.     void Awake()
    18.     {
    19.         gameCodes1 = GameObject.FindObjectOfType <GameCodes> ();
    20.     }
    21.        
    22.     public void ReturnToMap(string returnToMap)
    23.     {
    24.         SceneManager.LoadScene (returnToMap);
    25.     }
    26.  
    27.     public void letterA()
    28.     {
    29.         wordCreated.text = wordCreated.text + "A";
    30.     }
    31.  
    32.     public void Submit()
    33.     {
    34.         if (wordCreated.text == "A")
    35.         {
    36.             level++;
    37.             count.text = level.ToString();
    38.             gameCodes1.UnlockMap2 (level);
    39.  
    40.         }
    41.     }
    42. }
    43.  
    i need to pass the value of "level++ " to UnlockMap 2 in another script

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using UnityEngine.SceneManagement;
    6.  
    7. public class GameCodes : MonoBehaviour
    8. {
    9.     public Button map1;
    10.     public Button map2;
    11.     public Text show;
    12.  
    13.     void Start ()
    14.     {
    15.         map2.enabled = false;
    16.     }
    17.  
    18.     void Update()
    19.     {
    20.            
    21.     }
    22.  
    23.     public void goToMap1(string sceneName)
    24.     {
    25.         SceneManager.LoadScene (sceneName);
    26.     }
    27.  
    28.     public void UnlockMap2(int sum)
    29.     {
    30.         if(sum == 1)
    31.         {
    32.             map2.enabled = true;
    33.             show.text = sum.ToString ();
    34.         }
    35.     }
    36. }
    37.  
     
  33. Idlerid

    Idlerid

    Joined:
    Nov 7, 2017
    Posts:
    2
    Thanks!
     
  34. kavanavak

    kavanavak

    Joined:
    Sep 30, 2015
    Posts:
    31
    similar issue..

    Game works in Unity, but freezes when built to PC or iOS.. I've spent days rebuilding this, tearing out an event system and it still not working.. please help :/

    debug error:
    error:
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2.   at OverlayControl.ClearVoiceOver () [0x00013] in D:\Dev\Unity Projects\Walkabout v4\Assets\Scripts\Game\UI\OverlayControl.cs:21
    3.   at UnityEngine.Events.InvokableCall.Invoke () [0x00000] in <filename unknown>:0
    4.   at UnityEngine.Events.UnityEvent.Invoke () [0x00000] in <filename unknown>:0
    5.   at UnityEngine.UI.Button.Press () [0x0002d] in C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\UI\Core\Button.cs:36
    6.   at UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) [0x00012] in C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\UI\Core\Button.cs:45
    7.   at UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00008] in C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\ExecuteEvents.cs:50
    8.   at UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) [0x00073] in C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\ExecuteEvents.cs:261
    9. UnityEngine.DebugLogHandler:Internal_LogException(Exception, Object)
    10. UnityEngine.DebugLogHandler:LogException(Exception, Object)
    11. UnityEngine.Logger:LogException(Exception, Object)
    12. UnityEngine.Debug:LogException(Exception)
    13. UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1) (at C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\ExecuteEvents.cs:265)
    14. UnityEngine.EventSystems.StandaloneInputModule:ProcessMousePress(MouseButtonEventData) (at C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\InputModules\StandaloneInputModule.cs:554)
    15. UnityEngine.EventSystems.StandaloneInputModule:ProcessMouseEvent(Int32) (at C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\InputModules\StandaloneInputModule.cs:453)
    16. UnityEngine.EventSystems.StandaloneInputModule:ProcessMouseEvent() (at C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\InputModules\StandaloneInputModule.cs:433)
    17. UnityEngine.EventSystems.StandaloneInputModule:Process() (at C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\InputModules\StandaloneInputModule.cs:212)
    18. UnityEngine.EventSystems.EventSystem:Update() (at C:\buildslave\unity\build\Extensions\guisystem\UnityEngine.UI\EventSystem\EventSystem.cs:294)

    the referenced file, Overlay.cs -- it has an issue it seems with the script reference timer (it is attached via the editor) ..

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class OverlayControl : MonoBehaviour {
    7.  
    8.     [SerializeField]
    9.     private Timer timer; //.ResetTimer(); .UnPause();
    10.  
    11.     public GameObject VoiceOver;
    12.  
    13.     private void Awake()
    14.     {
    15.         VoiceOver.SetActive(true);
    16.     }
    17.  
    18.     public void ClearVoiceOver()
    19.     {
    20.         VoiceOver.SetActive(false);
    21.         timer.ResetTimer();
    22.         timer.UnPause();
    23.     }
    24.  
    25. }

    and here's Timer.cs, and the reference to reset

    Code (CSharp):
    1. public class Timer : MonoBehaviour
    2. {
    3. ...
    4.     public void ResetTimer()
    5.     {
    6.         t_offset = Time.time;
    7.     }
    8.  
    9.     public void Pause()
    10.     {
    11.         Time.timeScale = 0f;
    12.         isPaused = true;
    13.     }
    14.  
    15.     public void UnPause()
    16.     {
    17.         Time.timeScale = 1f;
    18.         isPaused = false;
    19.     }
    20. }
     
  35. kavanavak

    kavanavak

    Joined:
    Sep 30, 2015
    Posts:
    31
    is this as simple as me missing
    Code (CSharp):
    1. timer = GetComponent<Timer>();
    ?? in the overlay awake call?
    is that needed when you attach the script in editor? and if so, why would it play fine in Unity but crash outside?


    *** that doesn't seem to fix it.. still getting the same error messages.

    ***Update I'm pressing Play and noticing that a ton of attached scripts jump form being there to showing none, then appearing again when it stops playing...

    Update ** I feel like I'm taking crazy pills, I just added a new debug UI button to the scene and am now seeing that its not being incorporated into the PC builds .. for hours now I have no idea what edits I'm making are being built out .. was using Unity 2017.3.0f3 am now installing the beta to see if its a bug that's been fixed..
     
    Last edited: Dec 31, 2017
  36. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    19
    Good evening!

    I decided to stretch my goal on roll-a-ball tutorial by adding lives function, however I was running into problem to the point where I scratch my head in confusion.

    Here is my error I received when I collide with an enemy object.
    NullReferenceException: Object reference not set to an instance of an object
    Respawn.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Respawn.cs:21)

    and here are my scripts

    Code (CSharp):
    1. public class Respawn : MonoBehaviour
    2. {
    3.     public GameObject respawn;
    4.  
    5.     private int lossLife = -1;      //loss one life each time you respawn
    6.     private Lives lives;            //call Lives Class to reduce lives by 1
    7.  
    8.     void OnTriggerEnter(Collider other)
    9.     {
    10.         //Respawn if collided with Tag Enemy
    11.         if(other.CompareTag("Enemy"))
    12.         {
    13.             this.transform.position = respawn.transform.position;
    14.            
    15.             //call AjudstLives function in Lives Class
    16.             lives.AdjustLives(lossLife);
    17.         }
    18.     }
    19. }
    Code (CSharp):
    1. public class Lives : MonoBehaviour
    2. {
    3.     public int lives;       //set the number of lives
    4.     public Text livesText;  //display number of lives
    5.  
    6.     void Start()
    7.     {
    8.         UpdateLives();      //set Lives Text and number of lives
    9.     }
    10.  
    11.     //adjust number of lives
    12.     public void AdjustLives(int newLivesCount)
    13.     {
    14.         lives += newLivesCount;
    15.         UpdateLives();
    16.     }
    17.  
    18.     //update number of lives
    19.     public void UpdateLives()
    20.     {
    21.         livesText.text = "X " + lives;
    22.     }
    23. }
    I did assign public Text livesText to my livesText. I notice the code crash when it try to execute when calling AdjustLives in Respawn Script.
     
  37. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,713
    Your 'Lives' variable is private. If the script exists on the same game object, you can look it up in Awake().
    Code (csharp):
    1. void Awake() {
    2.    lives = GetComponent<Lives>();
    3.  }
    4.  
    What can also work, same game object or not is setting 'lives' to a public or (preferably) a SerializeField
    Code (csharp):
    1.  
    2. [SerializeField]
    3. Lives lives; // drag and drop in the inspector.
    4.  
    Small note, I know some topics 'seem' like the same problem, but personally I find it a little odd to see a long thread about many different people's issue on the same topic. lol Confusing because answers are similar but it's not one issue. Usually it's better to create a new thread :)

    Anyways, hope that helps.
     
  38. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    19
    Wow! I'm fairly new with programming but Awake work like a charm; I should look more into it. I try to mimic how to call a function from another class from Space Shooter tutorial but I guess I got too ahead of myself. With your advice, I shall post a new thread next time. And I wanted to thank you for your help as well. :D
     
  39. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,713
    No problem. Glad it worked. :) take care.
     
  40. aessi27

    aessi27

    Joined:
    Mar 22, 2018
    Posts:
    1
    Thanks buddy it also helped me
     
  41. Ahsan_mughal

    Ahsan_mughal

    Joined:
    Mar 30, 2018
    Posts:
    10
    kindly help me ,,I have done all, but this error prevent me to play my own game, anyone code master kindly help , GmAddScore is not working ,,
    Public Void GmAddScore(){
    this.myScore++;
    }
    and i call it on the obstacles script but unity shows all of the errors abour the same it dont adding the score , and dragon drops down and error generating continously :( :'( please somebody help ,, its about my lots of struggle :(
     

    Attached Files:

  42. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,713
    You should create your own thread, and post your own code. Use code tags, which you can read about here: https://forum.unity.com/threads/using-code-tags-properly.143875/
    That will post the code nicely formatted into your thread.

    Is it the score object that is null or the game manager? You have to be sure you have the right spelling. In fact, you should try to avoid using 'GameObject.Find'. Since you're new, one problem at a time. Feel free to ask about that part, once this error is resolved. :)
     
  43. darkStar27

    darkStar27

    Joined:
    Sep 14, 2018
    Posts:
    8
    Hello, I am trying to refer a function from another script LifeControler.cs in the player script Bird.cs. I have made an object of LifeControler in the Bird script and am referencing the function LivesCount() in the LifeControler script. below is my Bird script.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Bird : MonoBehaviour {
    4.  
    5.     private LifeControler lc;
    6.     public float upForce = 200f;
    7.     private bool isDead = false;
    8.     private Rigidbody2D rb2d;
    9.     private int collisionCounter = 3;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.         rb2d = GetComponent<Rigidbody2D>();
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.         if (isDead == false)
    19.         {
    20.             if (Input.GetKeyDown("space"))
    21.             {
    22.                 rb2d.velocity = Vector2.zero;
    23.                 rb2d.AddForce(new Vector2(0, upForce));                
    24.             }
    25.         }
    26.     }
    27.  
    28.     void OnCollisionEnter2D()
    29.     {
    30.         if (collisionCounter > 1)
    31.         {
    32.             lc.LivesCount(collisionCounter);
    33.             GameControl.instance.BirdDied();
    34.             collisionCounter--;
    35.         }
    36.         else
    37.         {
    38.             isDead = true;
    39.             rb2d.velocity = Vector2.zero;
    40.             lc.LivesCount(collisionCounter);
    41.         }
    42.     }
    43. }
    44.  

    The error is as follows:
    NullReferenceException: Object reference not set to an instance of an object
    LifeControler.LivesCount (Int32 lc) (at Assets/Scripts/LifeControler.cs:30)
    Bird.OnCollisionEnter2D () (at Assets/Scripts/Bird.cs:53)
     
  44. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    243
    If the LifeController script is attached to the same object as Bird, make the field "lc" public and drag-and-drop the LifeController component to the Bird component in the inspector.
     
  45. DoublePixelStudio

    DoublePixelStudio

    Joined:
    Jan 30, 2017
    Posts:
    69
    If you're setting it to private, you need to reference as a get component. So if the lifecontroller is attached to player and your player has a tag you'd say

    Code (CSharp):
    1. lc = GameObject.FindObjectWithTag("Player").GetComponent<LifeController>();
    Add this to start. Edit to fit your stuff.
     
  46. DoublePixelStudio

    DoublePixelStudio

    Joined:
    Jan 30, 2017
    Posts:
    69
    He would still be able to leave it private as long as he referenced it in start as get component

    Code (CSharp):
    1. Lc =GetComponent<LifeController>();
     
  47. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    243
    They could also leave it private and tag it as [SerializeField]. This would be preferable to a potentially unnecessary and expensive call to FindObjectWithTag(given it sounds like Bird and LifeController are attached to the same object). An advangage to doing this (as opposed to using GetComponent) is that you avoid introducing the requirement that LifeController be attached to the exact same gameObject (e.g. if you wanted to attach lifeController to a subobject for organisational purposes).

    Code (CSharp):
    1. [SerializeField]
    2. private LifeControler lc;
    3.  
     
    DoublePixelStudio likes this.
  48. darkStar27

    darkStar27

    Joined:
    Sep 14, 2018
    Posts:
    8
    Thanks for you help @bobisgod234 and @District3Studios for your help. Its solved now.

    I had one more question. Its not related to this thread, but if someone can please answer it.
    I am very new to game development and has just developed my first game and was thinking of uploading it to the play store to generate some revenue so that i can peruse GameDev as a carrier.

    I was wondering if its possible to add Google AdMob and UnityAds to a single game.
    Is it OK, can I do that without violating any T&C. and most of all would it help.
     
  49. DoublePixelStudio

    DoublePixelStudio

    Joined:
    Jan 30, 2017
    Posts:
    69
    I would personally use one or the other. Admobs ads are good but i like unitys ads. I typically use reward ads since most of my games use in app purchases and i dont want ads popping up when there are IAPs in the first place. But if you soley plan on a free game all around, like no IAP then i would use admob, something like banner ads. But if i was you i would read up on CPM. You need alot of ad calls to generate any kind of actual revenue.
     
  50. zumbeemods

    zumbeemods

    Joined:
    Sep 26, 2018
    Posts:
    2
    I'm having this issue with the object reference error as well, but it's for a follow script where an AI follows the player. I can't see anything wrong in the script, although I don't know much about scripting to begin with. Here's the script:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class FollowAI : MonoBehaviour
    5. {
    6.     public GameObject target; //the enemy's target
    7.     public float moveSpeed = 5; //move speed
    8.     void Start()
    9.     {
    10.         target = GameObject.FindGameObjectWithTag("Player");
    11.     }
    12.     void Update()
    13.     {
    14.  
    15.         Vector3 targetDir = target.transform.position - transform.position;
    16.         float angle = Mathf.Atan2(targetDir.y,targetDir.x) * Mathf.Rad2Deg - 90f;
    17.         Quaternion q = Quaternion.AngleAxis(angle,Vector3.forward);
    18.         transform.rotation = Quaternion.RotateTowards(transform.rotation,q,180);
    19.         transform.Translate(Vector3.up * Time.deltaTime * moveSpeed);
    20.     }
    21. }