I am not getting very far looking at the api documentation pages, I need to know if I can use scripting with Unity to do the following unusual requirement:
run a script against Unity that will move a viewpoint/camera to a specified (within the script) position within a height map terrain. Then the view of that terrain is rendered as a single frame and save to disk as an image file.
this would happen headless, with no display. So a server running unity would pick up the script, run it and perform the operation above. The only output would be the saved image.
This is an unusual use case so the documentation doesn’t really cover it but I am hoping that somebody here might have seen something like this before?
Any way here is my interpretation of a screen shot thingy
using System.IO;
using UnityEngine;
public class ScreenShotControl : MonoBehaviour
{
public Camera shotCam;
public int imageHeight;
public int imageWidth;
public string folderName;
public string fileName;
void Start()
{
//setup the cameras target
shotCam.targetTexture = new RenderTexture(imageWidth, imageHeight, 24);
//set cams position and then...
TakePicture();
}
public void TakePicture()
{
//Render the camera and set the current active render
shotCam.Render();
RenderTexture.active = shotCam.targetTexture;
//save the RenderTexture to a texture
Texture2D screenShot = new(imageWidth, imageHeight, TextureFormat.RGB24, false);
screenShot.ReadPixels(new Rect(0, 0, imageWidth, imageHeight), 0, 0);
//Create a byte array and save the data to disk
byte[] saveData = screenShot.EncodeToPNG();
//make sure the folder exists and write the file
if (!Directory.Exists(Application.dataPath + "/" + folderName)) Directory.CreateDirectory(Application.dataPath + "/" + folderName);
File.WriteAllBytes(FileNameTimeStamp(), saveData);
}
private string FileNameTimeStamp()
{
return Application.dataPath + "/" + folderName + "/" + fileName + System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".png";
}
}
It depends on where you want to run your script. The build needs a GPU + a Window (context) to render to. So your server needs to have a GPU that’s for sure.
For the context (window), if you build for Linux, this might be possible. All you need is to have a virtual display by using X server for eg.
Check this article. The part you’re interested into is probably “Running Unity app with graphics on a server without monitor” or “Run Unity app with graphics on Amazon Cloud!”