At the very beginning: I’m a beginner.
I have a problem with my little Game.
I want to create a hardcore mode where the Walls are deactivated.
This is my script:
using UnityEngine;
using System.Collections;
public class Hardcore : MonoBehaviour
{
public GameObject Walls;
void Update ()
{
if (Input.GetKeyUp(KeyCode.H))
{
if (Walls.SetActive(true))
{
Walls.SetActive(false);
}
else if(Walls.SetActive(false))
{
Walls.SetActive(true);
}
}
}
}
Unity says:
Assets/Scripts/Hardcore.cs(16,30): error CS0029: Cannot implicitly convert type void' to bool’
What does that mean?
What can I do?
Thanks and Sorry for mistakes in language. My english is not the best.
Your basic problem is that if statements are used with conditions, a type of code that can say true or false (Gets that value, not sets it)
SetActive does actually set an object as active, but with it you can’t check (Get) to know if the object is active or not
You have to call this “GameObject.activeInHierarchy”
So to fix your code
using UnityEngine;
using System.Collections;
public class Hardcore : MonoBehaviour
{
public GameObject Walls;
void Update ()
{
if (Input.GetKeyUp(KeyCode.H))
{
if (Walls.activeInHierarchy == true)
{
Walls.SetActive(false);
}
else if(activeInHierarchy == false)
{
Walls.SetActive(true);
}
}
}
}
But, hey your code isn’t optimized, if you already did if check, then in the else section, it means that the object isn’t really active, so properly there’s no need to check “If == false” you can just keep the else part with additional if! Here’s a more optimized code let’s say
using UnityEngine;
using System.Collections;
public class Hardcore : MonoBehaviour
{
public GameObject Walls;
void Update ()
{
if (Input.GetKeyUp(KeyCode.H))
{
if (Walls.activeInHierarchy == true)
{
Walls.SetActive(false);
}
else
{
Walls.SetActive(true);
}
}
}
}
SetActive() does not return a boolean value. You can check the state with activeSelf. As for your code, it can be simplified to:
using UnityEngine;
using System.Collections;
public class Hardcore : MonoBehaviour
{
public GameObject Walls;
void Update ()
{
if (Input.GetKeyUp(KeyCode.H))
{
Walls.SetActive (!Walls.activeSelf);
}
}
}