- Home /
What is the right way to modify depth of field focal distance via script at runtime?
I'm trying to use the built-in (Pro) DOF to selectively blur objects "in the background" while keeping the foreground crisp. But since the 2 dof filters in Unity will end up blurring everything that has alpha and all my objects (background and foreground) have alpha, I had to recur to two cameras and a foreground and background layers. So far so good.
But since I can't cause objects to blur or not based on their distance (since I'm doing the fixed layers), I thought the only way around it would be to instead modify the dof focal distance via a script at runtime. That is, when I want to focus on the foreground, I'd grab the background camera (with the dof script attached), and get the DOF script off it and modify it's focal distance.
I tried this (assume a MonoBehaviour, etc..):
Unity 3.4 DOF
// ...
private DepthOfField34 DOF34;
void Start() {
DOF34 = GameObject.Find("BackgroundCamera").GetComponent();
// ...
}
void Update() {
// ...
if (shouldFocusOnForeground) {
if (DOF34.focalZDistance > 1.0f) {
DOF34.focalZDistance -= 10f;
}
}
else {
if (DOF34.focalZDistance < 1000.0f) {
DOF34.focalZDistance += 10f;
}
}
}
But the script property "Focal Distance" doesn't move at all.
Then I tried the other DOF:
Unity 4 DOF Scatter / DX11
// ...
private DepthOfFieldScatter DOFx;
void Start() {
DOFx = GameObject.Find("BackgroundCamera").GetComponent();
// ...
}
void Update() {
// ...
if (shouldFocusOnForeground) {
if (DOFx.focalLength > 1.0f) {
DOFx.focalLength -= 10f;
}
}
else {
if (DOFx.focalLength < 1000.0f) {
DOFx.focalLength += 10f;
}
}
}
With this one, instead, only one time does 10 get subtracted or added to the focalLength. It just looks like a bug to me. But hopefully I'm just doing something wrong. Any ideas? (btw, I also tried in LateUpdate())
Answer by bernardfrancois · Sep 29, 2013 at 07:08 PM
Someone asked a similar question on the forums: http://forum.unity3d.com/threads/58828-dynamic-depth-of-field
Basically, you would be able to modify DepthOfField32.objectFocus, which is a transform. So you'd need to have a Transform object in your scene, which you move as you want to refocus the camera, while setting the objectFocus.
I didn't try it yet myself though. Curious to hear if it works.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
[Unity Free]Add textures to existing Unity DOF Shader 0 Answers
Material doesn't have a color property '_Color' 4 Answers
How to accurately map UV from second texture in image effects 0 Answers
Shader / Compute Shader in Unity 1 Answer