- Home /
What's the best way to toggle an instantiated object active/inactive?
I have a very clunky code i'm working on for a right click menu where i have something along the lines of this in the right click handler nesting...
if (MenuOpen)
{
RightClickMenu.SetActive(false);
}
else
{
RightClickMenu = instantiate(RightClickMenu, new vector 2(Input.MousePosition.x, Input.MousePosition.y - 150), quanterion.identity);
MenuOpen = true;
RightClickMenu.SetActive(true);}
The issue with this code is that it will continue to instantiate new gameObjects when right clicking to open the menu a second time and onward. Is there a way to command the script to only instantiate the object once, then after that toggle from gameObject.SetActive(true)/gameObject.SetActive(false) ?
Answer by yummy81 · Apr 27, 2020 at 08:53 AM
I wrote script for you. It's a general idea, so you can build upon it.
I set the camera as orthographic, and made it look at the forward direction.
You need 2 gameobjects. At first, create menu gameobject, put it in the scene, and set it inactive (you do not have to instantiate it by code. I didn't, but that depends on you). Then, attach this script on the second gameobject, the one which you want to control menu. Next, drag and drop menu gameobject into "public GameObject menu" slot in the inspector. That's it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
public GameObject menu;
public bool visible;
void Awake(){
menu.SetActive(visible);
}
void Update(){
if (Input.GetMouseButtonDown(1)){
visible ^= true;
if (visible){
menu.transform.position =
Camera.main.ScreenToWorldPoint(
new Vector3(Input.mousePosition.x,
Input.mousePosition.y,
-Camera.main.transform.position.z)
);
}
menu.SetActive(visible);
}
}
}
Your answer
Follow this Question
Related Questions
How do I make a game object appear a few seconds into the game? 1 Answer
SetActive is broken 0 Answers
A question about references in C# 2 Answers
[Solved]Instantiating prefab from a script and destroy it from another one 2 Answers
How to Instantiate a game object at the same position where the previous is destroyed 2 Answers