Instantiated object not recognized

Hi, I’d like to rotate an instantiated object while holding down the right mouse button but it doesn’t work. Here’s the code :

void Update(){
    
if (Input.GetButtonDown ("Fire1")) {
			
     GameObject longCube = Instantiate (SpawnCube, hit.point, Quaternion.identity) as GameObject;
}
if (Input.GetButton ("Fire2")) {

     longCube.transform.LookAt (lookTarget);

The problem is, it doesn’t recognize the longCube.transform.lookAt when I use it inside another IF. What can I do to be able to use longCube variable inside another IF condition ? Thanks for reading.

longCube is a local variable that is ONLY accessible in that one if statement. You can move the initial declaration (to null) outside the if statement but it will then be local to Update() so won’t be available next frame. You need the reference at the class instance (object) level. Example:

GameObject longCube = null;

void Update(){
     
 if (Input.GetButtonDown ("Fire1")) {            
      longCube = Instantiate (SpawnCube, hit.point, Quaternion.identity) as GameObject;
 }
 if (Input.GetButton ("Fire2") && longCube != null) {
      longCube.transform.LookAt (lookTarget);
 }
 ...

If you only ever need a single longCube then create it once and hide/unhide it as required (setting up it’s initial transform each time). Otherwise make sure you Destroy it when no longer required.

GameObject longCube;

void Update(){
    if (Input.GetButtonDown ("Fire1")) {
        longCube = Instantiate (SpawnCube, hit.point, Quaternion.identity) as GameObject;
    }

    if (Input.GetButton ("Fire2")) {
        longCube.transform.LookAt (lookTarget);
    }
}