Which server is used in script?
Each tab in SSMS is either linked to a SQL Server instance or working offline (disconnected). Whenever you open a .sql file in SSMS, it will automatically try to connect to the selected Instance and Database on your Object Explorer. When executing a query while offline it will pop up the connection window.

You can see the current connected instance if you hover the mouse over a connected tab or in the status bar at the bottom (default), next to the username and SPID, if you didn't hide it.

Scripts can't store the initial instance's connection. So make sure to connect previously to the proper instance. You might use sqlcmd inside scripts to connect to different instances but I don't think that's your concern.

There are add-ins like SSMS Tools in which you can map instances to color bars that are displayed on the side, up or down so for example you can map your Dev instance to color red and your Prod environment to green.