Reputation: 113
(New to C#/Unity so this might be a stupid question with an easy way to solve it)
I am trying to hide a canvas, that acts as a cross-hair, when ever I ADS with a gun. I have searched how to do this but it is still not hiding the canvas when ADSing.
How do I fix this or is there an easier way of doing it?
if (ISADS == true) //if ADS is true
{
Debug.Log(ISADS);
GameObject.Find("AK-47").GetComponent<Canvas>().enabled = false; //hide the canvas (The crosshair)
GameObject.Find("Pistol").GetComponent<Canvas>().enabled = false; // same with Pistol
GameObject.Find("870_Shotgun").GetComponent<Canvas>().enabled = false; // same with Shotgun
}
else
{
Debug.Log(ISADS);
GameObject.Find("AK-47").GetComponent<Canvas>().enabled = true; //else (if you're not ADSing) show the canvas
GameObject.Find("Pistol").GetComponent<Canvas>().enabled = true; // same with Pistol
GameObject.Find("870_Shotgun").GetComponent<Canvas>().enabled = true; // same with Shotgun
}
Upvotes: 2
Views: 4880
Reputation: 155
Is your code inside the update function? If not, that might be why your coding isn't working. It should be working at the start function but for troubleshooting purpose, I recommend let it run inside the update function.
Also are the gameobjects AK-47, Pistol, 870_Shotgun children of any other gameobjects? That might be why unity can't find it using gameobject.find(). Unity is trying to find the gameobject at the same level, you are calling through the script (if that make sense).
I will recommend using this following pseudocode
gameobject.find("this.gameobject/child/grand-child")
Or you can use transform.find() to make it easier. Let me know if it works.
Upvotes: 0
Reputation: 151
There are two ways I'd recommend doing this:
Set the gameObject.SetActive(false)
Or add a CanvasGroup component to your Canvas. Then you can edit 3 different values called alpha, intractable, and blocksraycasts. IE, GameObject.Find("AK-47").GetComponent<CanvasGroup>().alpha = 0
Upvotes: 2