- Home /
Making A Debug.Log depending on what GameObject is active
Hi! Sorry, but I'm really new to coding and am having a problem with something that is probably really simple. I have several items in my scene that can be "added to my inventory" (in reality they're just being disabled because I haven't implemented an inventory yet). I want to be able to press a button and get a description of the last object I "picked up." I have set up some invisible game objects, and "picking up" certain objects will turn these objects on and off. Depending on which invisble object is active, the O key is supposed to do a different thing. My code looks like this:
private void OnMouseDown()
{
if (gameObject.name == "SmallRock01")
{
gameObject.SetActive(false);
RockDescription.SetActive(true);
StatueDescription.SetActive(false);
KeyDescription.SetActive(false);
}
if (RockDescription.activeSelf && Input.GetKeyDown(KeyCode.O))
{
Debug.Log("The description of the rock goes here")
}
}
I have the same code set up for a small statuette and a key (thats why there are also objects called StatueDescription and KeyDescription) but with the right ones being active or inactive. Visual Studio isn't giving me any errors, but when I press O after "collecting" one of the objects nothing happens. Once again, sorry if my code is messy, I'm a beginner, and thanks in advance for all of the answers!
Answer by unity_ek98vnTRplGj8Q · Jul 23, 2020 at 04:40 PM
Try moving this code
if (RockDescription.activeSelf && Input.GetKeyDown(KeyCode.O))
{
Debug.Log("The description of the rock goes here")
}
out of the OnMouseDown() function and over to the Update() function so that it looks like this
private void OnMouseDown()
{
if (gameObject.name == "SmallRock01")
{
gameObject.SetActive(false);
RockDescription.SetActive(true);
StatueDescription.SetActive(false);
KeyDescription.SetActive(false);
}
}
private void Update(){
if (RockDescription.activeSelf && Input.GetKeyDown(KeyCode.O))
{
Debug.Log("The description of the rock goes here")
}
}
The OnMouseDown function will only be called once on the frame that the mouse is clicked, but you are pressing the O key at some later time, so you need to continuously check for the O key every frame