0
\$\begingroup\$

I am learning the Unity engine and have been practicing with various tutorials, but there is a curious error I am experiencing with the space shooter tutorial. Collisions with the player ship do not destroy asteroids or the player, while collisions with bolts fired by the player will destroy the asteroids but not increase the score at all.

The error being logged is "Cannot find GameController script" which makes me think there is a problem with my code below, specifically the void Start() function that checks if GameController != null.

Is there something about Unity 5 that differs from Unity 4 that I would need to change? Or have I made a mistake in this code attempting to reference the GameController script?

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

public class DestroyByContact : MonoBehaviour {

    public GameObject explosion;
    public GameObject playerExplosion;
    public int scoreValue;
    private GameController gameController;

    void Start()
    {
        GameObject gameControllerObject = GameObject.FindWithTag("GameController");
        if (gameController != null)
        {
            gameController = gameControllerObject.GetComponent<GameController>();
        }
        if (gameController == null)
        {
            Debug.Log("Cannot find 'GameController' script");
        }
    } 

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Boundary")
        {
            return;
        }
        Instantiate(explosion, transform.position, transform.rotation);
        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
            gameController.GameOver();
        }

        Debug.Log(other.name);
        Destroy(other.gameObject);
        Destroy(gameObject);
        gameController.AddScore(scoreValue);
    }
}
\$\endgroup\$
2
\$\begingroup\$

You're most-likely doing a wrong check in the Start function and it should read

if (gameControllerObject != null)
{
 ...
}

because you're trying to find the controller object by tag and have to verify that the return value of GameObject.FindWithTag(...) is not null. Otherwise you might risk running into a NullReferenceException.

\$\endgroup\$
0
\$\begingroup\$

Make sure you have the game object tagged as GameController. See image.

enter image description here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.