Reputation: 11
I am making a backpack and I am trying to make it like Minecraft how you just press "E" and it will open and if is already open then they close it. Bty I am using Unity in C#.
if (Input.GetKeyDown(backpackKey) && backpack.activeInHierarchy == false)
{
backpack.SetActive(true);
}
if (Input.GetKeyDown(backpackKey) && backpack.activeInHierarchy == true)
{
backpack.SetActive(false);
}
Upvotes: 0
Views: 18593
Reputation: 90620
Both your if conditions will match:
Either use else if
to make both blocks run exclusive or .. actually you could simply do
if (Input.GetKeyDown(backpackKey))
{
// I would prefer using "activeSelf"
// If any parent is inactive your check might always return false even though the object
// itself is already set to active. Don't know if it has an impact on performance
// I just find it more convenient here since this is the value changed by "SetActive"
backpack.SetActive(!backpack.activeSelf);
}
Upvotes: 5
Reputation: 938
You are missing an else
statement:
if (Input.GetKeyDown(backpackKey))
{
if(backpack.activeInHierarchy == false)
{
backpack.SetActive(true);
} else {
backpack.SetActive(false);
}
}
In your code, whenever you try to open it then you end up falling into the second condition, now true, and closing it immediately.
Upvotes: 0