nullreferenceexception object reference not set to an instance of an object

Hello

i have problem in the game app after bulid

show me in game console

nullreferenceexception object reference not set to an instance of an object
PlayerController. OnTriggerEnter (UnityEngine Collider Other ) PlayerController.cs 171

the game inside the unity is working fine but when bulid the object not worling

the PlayerController source

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class PlayerController : BaseController {

    public Transform cannon;
    public float cannonRotationSpeed = 15f; //speed of rotation to direction of cannon
    public ParticleSystem shootFX;
    public GameObject bulletPrefab;
    public GameObject explosionPrefab;
    public Transform bulletStartPoint;
    public float reloadSpeed = 1;
    public int health = 100;
    private float maxHealth = 100;
    Vector3 cannonDirection = Vector3.zero;
    private bool canFire = true;
    SoundManager soundManager;

    // Use this for initialization
    void Start () {
        Init();
        soundManager = FindObjectOfType<SoundManager>();
        cannonDirection = transform.forward;
        maxHealth = (float)health;
    }
   
    // Update is called once per frame
    void Update () {
        if (gameplay.gameState != GamePlay.GameState.Playing)
            return;
        #if UNITY_EDITOR || UNITY_WEBPLAYER
        //control with keyboard
        if (Input.GetKey(KeyCode.LeftArrow)) {
            MoveLeft();
        }
        if (Input.GetKey(KeyCode.RightArrow)) {
            MoveRight();
        }
        if (Input.GetKey(KeyCode.UpArrow)) {
            MoveFast();
        }
        if (Input.GetKey(KeyCode.DownArrow)) {
            MoveSlow();
        }
        if (Input.GetKeyUp(KeyCode.LeftArrow)) {
            MoveStraight();
        }
        if (Input.GetKeyUp(KeyCode.RightArrow)) {
            MoveStraight();
        }
        if (Input.GetKeyUp(KeyCode.UpArrow)) {
            MoveNormal();
        }
        if (Input.GetKeyUp(KeyCode.DownArrow)) {
            MoveNormal();
        }
        //rotate the vehicle in side direction
        ChangeRotation();
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject()) {
            Vector3 newDirection = getCannonDirection(Input.mousePosition);
            if (Vector3.Angle(transform.forward, newDirection) <= 60)
                cannonDirection = newDirection;
        }
        RotateCannonToDirection(); //rotate cannon to mouse direction
        CheckGUIButtons(true);
        #elif UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8
        if (gameplay.gameSettings.controlType == GameSettings.ControlType.Accelerometer) {
            //move left or right with accelerometer
            float acceleration = Mathf.Abs(Input.acceleration.x);
            if (acceleration < 0.1f) {
                speed  = new Vector3(0, 0, speed.z);
            } else if (0.1f < acceleration && acceleration < 0.2f) {
                speed  = new Vector3(xSpeed/4 * Mathf.Sign(Input.acceleration.x), 0, speed.z);
            } else if (acceleration < 0.8f) {
                speed  = new Vector3(xSpeed/2 * Mathf.Sign(Input.acceleration.x), 0, speed.z);
            } else if (acceleration < 1f) {
                speed  = new Vector3(xSpeed * Mathf.Sign(Input.acceleration.x), 0, speed.z);
            }
            //rotation of car
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0,2*maxAngle*Input.acceleration.x,0), Time.deltaTime*rotationSpeed);
            CheckGUIButtons(false);
        } else if (gameplay.gameSettings.controlType == GameSettings.ControlType.OnScreen) {
            ChangeRotation();
            CheckGUIButtons(true);
        }
        foreach (Touch touch in Input.touches) {
            if (touch.phase == TouchPhase.Began && !EventSystem.current.IsPointerOverGameObject(touch.fingerId)) {
                Vector3 newDirection = getCannonDirection(Input.mousePosition);
                if (Vector3.Angle(transform.forward, newDirection) <= 60)
                    cannonDirection = newDirection;
            }
        }
        RotateCannonToDirection(); //rotate cannon to mouse direction
        #endif

    }

    public void OnFire() {
        if (!canFire)
            return;
        canFire = false;
        shootFX.Play();
        soundManager.PlaySound(soundManager.shootSound);
        /*RaycastHit hit;
        if (Physics.Raycast(cannon.position, cannonDirection, out hit, 100, LayerMask.GetMask(new string[]{"Obstacles"}))) {
            hit.transform.GetComponent<ExplosiveObstacle>().Explode();
        }*/
        GameObject bullet = Instantiate(bulletPrefab, bulletStartPoint.position, bulletStartPoint.rotation) as GameObject;
        bullet.GetComponent<Bullet>().Move(2000);
        StartCoroutine(Reload());
    }

    IEnumerator Reload() {
        gameplay.energyBar["EnergyBar"].speed = reloadSpeed;
        gameplay.energyBar.Play("EnergyBar");
        yield return new WaitForSeconds(gameplay.energyBar["EnergyBar"].length/reloadSpeed);
        canFire = true;
    }
   
    void ChangeRotation() {
        if (speed.x > 0)
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0,maxAngle,0), Time.deltaTime*rotationSpeed);
        else if (speed.x < 0)
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0,-maxAngle,0), Time.deltaTime*rotationSpeed);
        else
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0,0,0), Time.deltaTime*rotationSpeed);
    }

    //returns cannon directionn to target vector
    Vector3 getCannonDirection(Vector3 target) {
        return (getWorldPoint(target) - transform.position);
    }

    //converts screen to world point on specific height
    Vector3 getWorldPoint(Vector3 screenPoint) {
        Ray ray = Camera.main.ScreenPointToRay(screenPoint);
        Plane plane = new Plane(Vector3.up, transform.position);
        float distance = 0;
        if (plane.Raycast(ray, out distance)){    
            return ray.GetPoint(distance);
        }
        return Vector3.zero;
    }

    //makes smooth rotation of transform to direction
    void RotateCannonToDirection() {
        if (cannonDirection != Vector3.zero) {
            Quaternion qTo = Quaternion.LookRotation(cannonDirection);
            if (Quaternion.Angle(cannon.rotation, qTo) > 0.5f) {
                cannon.rotation = Quaternion.Slerp(cannon.rotation, qTo, rotationSpeed * Time.deltaTime);
            }
        }
    }

    void FixedUpdate() {
        if (gameplay.gameState == GamePlay.GameState.Playing)
            GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + speed * Time.deltaTime);
    }

    void OnTriggerEnter(Collider other) {
        if (other.tag == "Obstacle") {
            if (other.GetComponent<ExplosiveObstacle>() != null) {
                Hurt(other.GetComponent<ExplosiveObstacle>().damage);
                other.GetComponent<ExplosiveObstacle>().Explode();
            } else {
                Hurt(10);
                soundManager.PlaySound(soundManager.fireSound);
            }
        } else if (other.tag == "Zombie") {
            other.GetComponent<Zombie>().Die();
            soundManager.PlaySound(soundManager.zombieSmashSounds[Random.Range(0, soundManager.zombieSmashSounds.Length)]);
            gameplay.AddScore(1);
        }
    }

    void Hurt(int damage) {
        health -= damage;
        if (health > 0) {
            float lifeLength = -100f + 325f * (1f - health/maxHealth);
            gameplay.lifeBar.offsetMax = new Vector2(-lifeLength, gameplay.lifeBar.offsetMax.y);
            Camera.main.GetComponent<Animation>().Play("CameraShake");
        } else {
            Destroy(GetComponent<Rigidbody>());
            GetComponent<Collider>().enabled = false;
            foreach (Renderer renderer in GetComponentsInChildren<Renderer>()) {
                renderer.enabled = false;
            }
            foreach (ParticleSystem ps in GetComponentsInChildren<ParticleSystem>()) {
                ps.Stop();
            }
            if (PlayerPrefs.GetInt("sound", 1) == 1)
                GetComponent<AudioSource>().Play();
            GameObject explosion = Instantiate(explosionPrefab, transform.position, Quaternion.identity) as GameObject;
            gameplay.lifeBar.offsetMax = new Vector2(-240, gameplay.lifeBar.offsetMax.y);
            gameplay.OnGameOver();
        }
    }
}

any soultion plz

regards

that tells me the zombie gameobject that you hit does not have a Zombie script attached to it. So when you try and access the .Die() it fails.

how will solve it ?

Make sure a Zombie script is on all the game objects tagged as “Zombie”. :slight_smile:

yes its in the file

Split your GetComponent call from your use of the component, and add some debugging to output if the returned component is null before you try to use it. You’ll likely find that the component is null, so you’ll need to figure out why that is.

here is some code that might help

else if (other.tag == "Zombie") {
            Zombie zombie= other.GetComponent<Zombie>();
            if(!zombie == null) // if zombie does not equal null
            {
                zombie.Die();
            }else
            {
                Debug.Log("zombie did not have the Zombie script attached.");
                //lets try and add it at RunTime, AHHH,  this feels bad
                zombie.transform.gameObject.AddComponent<Zombie>();
                //now we can kill it
                zombie.Die();
            }
            soundManager.PlaySound(soundManager.zombieSmashSounds[Random.Range(0, soundManager.zombieSmashSounds.Length)]);
            gameplay.AddScore(1);
           
        }
1 Like

Do you mean the zombie prefab has the Zombie script attached?

1 Like