Reputation: 1
I'm using Unity Engine 2019.3.9f1. Right now I'm trying to hide an object via SetActive(false), but perhaps I'm doing it incorrectly, or haven't anticipated something.
Right now I have a GameObject called 'TILE_LARGE_1' in the scene.
By pressing 'D' on the keyboard, I want to hide the object using SetActive(false). The script compiles fine, but the object isn't hidden when I press 'D'. Is there a caveat I'm unaware of using this method?
using UnityEngine;
using System.Collections;
[AddComponentMenu("Utilities/VisObjects1")]
public class VisObjects1 : MonoBehaviour
{
public GameObject TILE_LARGE_1;
void Start()
{
TILE_LARGE_1.SetActive(true); // false to hide, true to show
}
void Update()
{
if (Input.GetKeyDown(KeyCode.D))
{
TILE_LARGE_1.SetActive(false); // false to hide, true to show
}
}
}
Upvotes: 0
Views: 4144
Reputation: 1
As @Abion47 pointed out, I hadn't indicated where/what the game object was. Solution as follows:
GameObject TILE_LARGE_1 = GameObject.Find("TILE_LARGE_1");
TILE_LARGE_1.GetComponent<Renderer>().enabled = false;
Upvotes: 0
Reputation: 24661
You put the code in the Start
method, which is only called once at the beginning of the object's lifetime. You should instead put it in the Update
method which is called every frame:
void Update()
{
if (Input.GetKeyDown(KeyCode.D))
{
TILE_LARGE_1.SetActive(false); // false to hide, true to show
}
}
Upvotes: 2