- Home /
SetActive messes up everything?
I'm really new to C# and unity and I'm working on this small game where you shoot incoming red triangles and not shoot white triangles around the environment. At the moment I'm working on UI. If you get hit by an enemy then the game over canvas correctly pops up but when you shoot a white 'innocent' triangle the menu doesn't. I also get this error:
NullReferenceException: Object reference not set to an instance of an object collision.OnDestroy () (at Assets/Scripts/collision.cs:46)
My script works now except when I try to put canvasGameOver.SetActive(true); in the if statement. When I do that everything gets messed up and doesn' t work anymore.
My Script:
private GameObject scoretext;
public GameObject player;
public ParticleSystem deathparticle;
public ParticleSystem deathparticlePlayer;
private AudioSource hit2;
private CameraShaker camShakerS;
private ScoreManager scoremanager;
private GameObject canvasGameOver;
private void Start()
{
hit2 = GameObject.Find("Hit2").GetComponent<AudioSource>();
camShakerS = GameObject.Find("Main Camera").GetComponent<CameraShaker>();
scoretext = GameObject.Find("Scoretext");
scoremanager = GameObject.Find("Scoretext").GetComponent<ScoreManager>();
canvasGameOver = GameObject.Find("CanvasGameOver");
}
private void Update()
{
player = GameObject.Find("Player");
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.gameObject.tag == "Bullet")
{
Destroy(collision.collider.gameObject);
scoremanager.score = 0;
Instantiate(deathparticle, transform.position, Quaternion.identity);
scoretext.SetActive(false);
camShakerS.shouldShake = true;
player.SetActive(false);
Instantiate(deathparticlePlayer, player.transform.position, Quaternion.identity);
hit2.Play(0);
Destroy(gameObject);
}
}
Answer by Cloudy71 · Jul 30, 2020 at 04:33 PM
Obviously it says there's error on line 46, but I don't see line 46 in your script. How are we supposed to help you, when we see barely nothing?
Line 5, 13: It's better to make this field public, so you can assign your Audio straight to the Object instead of making Object with only Audio, try to avoid making mess in your scene hierarchy.
Line 14: Use Camera.main
Line 22: Also avoid using GameObject.Find and GetComponent methods in your Update method, these methods are performance demanding.
Line 29: Use collision.collider.gameObject.CompareTag("Bullet")