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) ?

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);
		}
	}
}