RendermanGL
RendermanGL

Reputation: 5

NullReferenceException: Object reference not set to an instance of an object in unity 3D trying to make a function

 using UnityEngine;
using System.Collections;
[RequireComponent(typeof(flipPlayer))]
public class enemyInstantiate : MonoBehaviour 
{
    public GameObject[] enemies;
    public Transform enemyPos;
    public GameObject enemyClone;



    void Start()
    {

        enemyPos = GameObject.Find("enemySpawn").transform;
        enemyClone = GameObject.FindGameObjectWithTag("Player");
        enemySpawn();
        flip();
    }

    public void enemySpawn()
    {

        int enemyIndex = Random.Range(0, enemies.Length);
        Instantiate(enemies[enemyIndex], transform.position, transform.rotation);


    }
    void flip()
    {

        enemyClone.GetComponent<flipPlayer>().enabled = true;

    }

}

NullReferenceException: Object reference not set to an instance of an object enemyInstantiate.flip () (at Assets/Scripts/enemyInstantiate.cs:32) enemyInstantiate.Start () (at Assets/Scripts/enemyInstantiate.cs:18)

i'm pretty new to Unity 3D And still having trouble, can you please help out with what the problem is and why am i getting a nullReferenceException.

The error occurs in the line (enemyClone.GetComponent().enabled = true;).

Upvotes: 0

Views: 13136

Answers (2)

Ricardo Reiter
Ricardo Reiter

Reputation: 581

Probably in this line

enemyClone = GameObject.FindGameObjectWithTag("Player");

Is returning null to var enemyClone, and/or in GetComponent<flipPlayer>() from line

enemyClone.GetComponent<flipPlayer>()

also is returning null.

When you try to access a member of an object that is the null reference, this error happens.

Therefore, a way to check which reference is null, is debugging via MonoDevelop.

Upvotes: 1

Gaston Claret
Gaston Claret

Reputation: 998

Without the complete error, the only things I can say are:

  • Random.Range is a number between min and max INCLUSIVE! So if your length is 4 for example, and you do from 0-4 your range, and you try to access enemies[4] it will break! You need your line to be Random.Range(0, enemies.length - 1);
  • Do you have items in your enemies array?
  • Do you have an enemyspawn in the scene? maybe separate that line into a declaration first, and then make sure the item is not null before trying to access it's transform.

Hope this helps you! If not, please post the line in which the null reference is happening

Upvotes: 1

Related Questions