- Home /
Disable GameObject through Prefab?
Hi dear experts,
I have an issue with my Game. What I want is when the knife hits the barrier, the Game should end with a GameOver Screen.
However, I was unable to make references of the UI-Elements on the prefab of the knife. That's why I came up with the Idea, that when the Knife collides with the barrier, a bool value should change to true. After that I can check in another script in Update() the bool value, if it's true, the UI should also adapt to this.
However, this is not working and I dont have any solution for this.
Heres the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class KnifeScript : MonoBehaviour {
public bool hit;
// Use this for initialization
void OnCollisionEnter2D(Collision2D other){
if(other.collider.tag == "Barrier"){
Debug.Log("Barrier hit");
hit = true;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawnhandling : MonoBehaviour {
public GameObject mainui;
public GameObject gameOverPanel;
public GameObject knife; //Prefab
void Update(){
if(knife.GetComponent<KnifeScript>().hit){
mainui.SetActive(false);
gameOverPanel.SetActive(true);
}
}
Thanks a lot!
Answer by LCStark · Sep 30, 2018 at 07:00 PM
Since you're setting the hit
value on your instanced object, you would need to check in Spawnhandling.Update
all your instances for the value of hit.
If you only need to detect if any knife hit the barrier to end the game, you could make your hit
field static:
public class KnifeScript : MonoBehaviour {
public static bool hit;
...
void OnCollisionEnter2D(Collision2D other){
if(other.collider.tag == "Barrier"){
Debug.Log("Barrier hit");
KnifeScript.hit = true;
}
}
}
public class Spawnhandling : MonoBehaviour {
...
void Update(){
if(KnifeScript.hit) {
mainui.SetActive(false);
gameOverPanel.SetActive(true);
}
}
}
You might want to re-set
KnifeScript.hit
value to false when you start your scene, though.
Answer by noamro · Sep 30, 2018 at 06:40 PM
is the game 2d? and did u check the box colider of the knife checked as trigger?