Как ограничить fps в unity
Перейти к содержимому

Как ограничить fps в unity

  • автор:

How to limit framerate in Unity without causing screentears?

Is there any way to limit framerate in Unity without causing screentears in build? I cannot seem to do it, but Valheim has an fps-slider and they use Unity, so thinking there must be a way?

1 Answer 1

Note that the way you enable vSync in Unity is by setting the value QualitySettings.vSyncCount , which is an integer value, with 4 being the allowed maximum. The target framerate becomes the monitor refresh rate divided by that integer. Which can be obtained via RefreshRate.value . So if you want both vSync and a limited framerate that is lower than the refresh rate, then you can just set the vSyncCount to the correct factor.

The documentation says that the maximum allowed vSyncCount is 4, but the behavior you get when you set it to a higher value is undocumented. So I would recommend to Mathf.Clamp the value to the range of 1 to 4.

So if you want to have a limit of (as close as possible to) 60 Fps while also having vSync enabled, then you can do this:

Как ограничить fps в unity

Reddit and its partners use cookies and similar technologies to provide you with a better experience.

By accepting all cookies, you agree to our use of cookies to deliver and maintain our services and site, improve the quality of Reddit, personalize Reddit content and advertising, and measure the effectiveness of advertising.

By rejecting non-essential cookies, Reddit may still use certain cookies to ensure the proper functionality of our platform.

For more information, please see our Cookie Notice and our Privacy Policy .

Get the Reddit app

Unity is the ultimate entertainment development platform. Use Unity to build high-quality 3D and 2D games and experiences. Deploy them across mobile, desktop, VR/AR, consoles or the Web and connect with people globally. This community is here to help users of all levels gain access to resources, information, and support from others in regards to anything related to Unity. Showcase your work and use this independent forum to connect with enthusiasts sharing the same passions. Post away!

Unity как ограничить fps

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

Specifies the frame rate at which Unity tries to render your game.

The default value of Application.targetFrameRate is -1. In the default case, Unity uses the platform’s default target frame rate.

Otherwise, targetFrameRate is a positive integer representing frames per second (fps). Unity tries to render your game at that frame rate.

Use targetFrameRate to control the frame rate of your game. For example, you might need to reduce your game’s frame rate to make sure your game displays smoothly and consistently. You can also reduce your game’s frame rate to conserve battery life on mobile devices and avoid overheating.

Note that platform and device capabilities affect the frame rate at runtime, so your game might not achieve the target frame rate.

targetFrameRate and vSyncCount

Both Application.targetFrameRate and QualitySettings.vSyncCount let you control your game’s frame rate for smoother performance. targetFrameRate controls the frame rate by specifying the number of frames your game tries to render per second, whereas vSyncCount specifies the number of screen refreshes to allow between frames.

Mobile platforms ignore QualitySettings.vSyncCount. Use Application.targetFrameRate to control the frame rate on mobile platforms.

VR platforms ignore both QualitySettings.vSyncCount and Application.targetFrameRate. Instead, the VR SDK controls the frame rate.

On all other platforms, Unity ignores the value of targetFrameRate if you set vSyncCount . When you use vSyncCount , Unity calculates the target frame rate by dividing the platform’s default target frame rate by the value of vSyncCount . For example, if the platform’s default render rate is 60 fps and vSyncCount is 2, Unity tries to render the game at 30 frames per second.

Platform notes

Standalone platforms

On standalone platforms, the default frame rate is the maximum achievable frame rate. To use the platform’s default frame rate, set Application.targetFrameRate to -1.

Mobile platforms

A mobile device’s maximum achievable frame rate is the refresh rate of the screen. For example, a device with a refresh rate of 60 Hertz has a maximum achievable frame rate of 60 frames per second. To target the maximum achievable frame rate, set Application.targetFrameRate to the screen’s refresh rate. Screen.currentResolution contains the screen’s refresh rate.

To conserve battery power, the default frame rate on mobile platforms is lower than the maximum achievable frame rate. Usually, the default frame rate on mobile platforms is 30 fps. To target the default frame rate, set Application.targetFrameRate to -1.

To target a frame rate other than the maximum achievable frame rate or the platform default on mobile platforms, set Application.targetFrameRate to the screen’s refresh rate divided by an integer. If the target frame rate is not a divisor of the screen refresh rate, the resulting frame rate is always lower than Application.targetFrameRate.

Note that mobile platforms ignore the QualitySettings.vSyncCount setting. Instead, you use the target frame rate to achieve the same effect as setting the vertical sync count. To do this, divide the screen’s refresh rate by the number of vertical syncs you want to allow between frames, and set Application.targetFrameRate to this number.

For example, on a device with a screen refresh rate of 60 Hz, to allow:

  • 1 vertical sync between frames, set targetFrameRate to 60.
  • 2 vertical syncs between frames, set targetFrameRate to 30.
  • 3 vertical syncs between frames, set targetFrameRate to 20.

WebGL

By default, WebGL lets the browser choose a frame rate that matches its render loop timing. To use the browser’s chosen frame rate, set Application.targetFrameRate to -1.

Usually, the browser’s chosen frame rate gives the smoothest performance. You should only set a different target frame rate on WebGL if you want to throttle CPU usage.

Locking frame rate to 60 in the editor

This works on the iPhone. But in the editor it only reduced the frame rate to around 80-90. Am I missing yet another setting?

Mac OSX Mavericks.

Saturn's user avatar

2 Answers 2

For the target frame rate to be applied in the editor it is important that the vsync is disabled.

This can be changed using the Quality Settings GUI by selecting «Don’t sync» or programmatically:

Also, it worth noting that FPS number displayed in the Editor stats window is not accurate at all. I even came to a point where I wonder if the number displayed is about Frames Per Seconds.

Unity как ограничить fps

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

Specifies the frame rate at which Unity tries to render your game.

The default value of Application.targetFrameRate is -1. In the default case, Unity uses the platform’s default target frame rate.

Otherwise, targetFrameRate is a positive integer representing frames per second (fps). Unity tries to render your game at that frame rate.

Use targetFrameRate to control the frame rate of your game. For example, you might need to reduce your game’s frame rate to make sure your game displays smoothly and consistently. You can also reduce your game’s frame rate to conserve battery life on mobile devices and avoid overheating.

Note that platform and device capabilities affect the frame rate at runtime, so your game might not achieve the target frame rate.

targetFrameRate and vSyncCount

Both Application.targetFrameRate and QualitySettings.vSyncCount let you control your game’s frame rate for smoother performance. targetFrameRate controls the frame rate by specifying the number of frames your game tries to render per second, whereas vSyncCount specifies the number of screen refreshes to allow between frames.

Mobile platforms ignore QualitySettings.vSyncCount. Use Application.targetFrameRate to control the frame rate on mobile platforms.

VR platforms ignore both QualitySettings.vSyncCount and Application.targetFrameRate. Instead, the VR SDK controls the frame rate.

On all other platforms, Unity ignores the value of targetFrameRate if you set vSyncCount . When you use vSyncCount , Unity calculates the target frame rate by dividing the platform’s default target frame rate by the value of vSyncCount . For example, if the platform’s default render rate is 60 fps and vSyncCount is 2, Unity tries to render the game at 30 frames per second.

Platform notes

Standalone platforms

On standalone platforms, the default frame rate is the maximum achievable frame rate. To use the platform’s default frame rate, set Application.targetFrameRate to -1.

Mobile platforms

A mobile device’s maximum achievable frame rate is the refresh rate of the screen. For example, a device with a refresh rate of 60 Hertz has a maximum achievable frame rate of 60 frames per second. To target the maximum achievable frame rate, set Application.targetFrameRate to the screen’s refresh rate. Screen.currentResolution contains the screen’s refresh rate.

To conserve battery power, the default frame rate on mobile platforms is lower than the maximum achievable frame rate. Usually, the default frame rate on mobile platforms is 30 fps. To target the default frame rate, set Application.targetFrameRate to -1.

To target a frame rate other than the maximum achievable frame rate or the platform default on mobile platforms, set Application.targetFrameRate to the screen’s refresh rate divided by an integer. If the target frame rate is not a divisor of the screen refresh rate, the resulting frame rate is always lower than Application.targetFrameRate.

Note that mobile platforms ignore the QualitySettings.vSyncCount setting. Instead, you use the target frame rate to achieve the same effect as setting the vertical sync count. To do this, divide the screen’s refresh rate by the number of vertical syncs you want to allow between frames, and set Application.targetFrameRate to this number.

For example, on a device with a screen refresh rate of 60 Hz, to allow:

  • 1 vertical sync between frames, set targetFrameRate to 60.
  • 2 vertical syncs between frames, set targetFrameRate to 30.
  • 3 vertical syncs between frames, set targetFrameRate to 20.

WebGL

By default, WebGL lets the browser choose a frame rate that matches its render loop timing. To use the browser’s chosen frame rate, set Application.targetFrameRate to -1.

Usually, the browser’s chosen frame rate gives the smoothest performance. You should only set a different target frame rate on WebGL if you want to throttle CPU usage.

Locking frame rate to 60 in the editor

This works on the iPhone. But in the editor it only reduced the frame rate to around 80-90. Am I missing yet another setting?

Mac OSX Mavericks.

user avatar

2 Answers 2

For the target frame rate to be applied in the editor it is important that the vsync is disabled.

This can be changed using the Quality Settings GUI by selecting «Don’t sync» or programmatically:

Also, it worth noting that FPS number displayed in the Editor stats window is not accurate at all. I even came to a point where I wonder if the number displayed is about Frames Per Seconds.

How to limit FPS?

into my only one camera’s script. In the stats of the Game window I see 96-110 FPS. How to limit it to 30? I use the latest Unity on the latest MacOSX.

4 Ответов

As others have mentioned, you disable vSync and set the targetFrameRate like this:

However, you have to test the result on device to see if it works. The documentation doesn’t say anything about the game view render update in the editor, but it does say that the results are different per platform.

I’ve tested the code in the editor and it was working, but we need to understand that it’s not a hard limit, but just a recommendation. When I set it to render at 30, I get results up to 40 frames per second displayed in the stats panel. This may be because the stats panel doesn’t measure fps accurately or because the final frame rate may be a little higher on standalone. In any case, I would measure fps on device with one of the official profiling tools, e.g. Apple’s XCode for iOS devices. There, the limit of 30 vs 60 fps works accurately (at least when I tested last).

Why would you ever want to limit FPS?

EDIT To be more helpful, and actually provide an answer 🙂

To decrease battery usage on mobile devices if I don’t need fps to be around 60. Or I can use dynamic FPS ins$$anonymous$$d.

This isn’t an answer, please remove it and post it as a comment ins$$anonymous$$d 🙂

yea my bad. Settings targetFrameRate should be they way though.

Do something like this.

might be over kill checking every frame but it will work

As a side note, there is a comma on line 8 that should be a period. Other than that this works fine 🙂 Cheers!

this surely worked for $$anonymous$$e I wanted to set the fps around 60 so I made the target FPS to 70

For those who still wonders how the targetFrameRate works, it’s not an absolute value.

There’s a lot of information on the API description here.

For those who still don’t get it, the value may be partially or fully ignored for multiple reasons. First, in case you’re enabling VSync (above 0), the framerate will be ignoring the targetFrameRate value (as explained here) and will, instead, use the system default framerate. If your device has a default FPS of 120 with VSync at 1, it will try to render at 120 fps regardless of targetFrameRate. If you set VSync to 1-4 (max value applicable is 4), the fps will be equal to the device’s default framerate divided by the VSync value. So, if you set it to 2 and your device has a default framerate of 120, it will be render at 60 fps. At the same time, if it’s a default 30 fps, it will drop at a max of 15 fps.

PCs default framerates are determined by the GPU driver and can be accessed by the player/user through their GPU interface. You can’t change it from within the game so, if you allow VSync in some options menu, it’s a good practice to put some sort of notice/info panel when VSync is enabled to make the player know that he or she has to do the change while the game is not running. On mobile device, 95% of the devices doesn’t allow the user to change the default framerate. Some manufacturers will allows it through the device’s screen refresh rate in the devices’ screen advanced settings. In the case of consoles (for those who wonders), both the Xbox X and S have default framerate of 60 while the PS4 is set to 60 and PS5 is set to 120. It’s possible to make the Xbox X render at 120, but it requires a particular plugin and I’m not sure if it’s compatible with the way Unity determines the device’s default framerate.

Русские Блоги

Настройка частоты кадров Unity3d и отображение частоты кадров при запуске игры

Поделитесь учебником по искусственному интеллекту моего учителя! Нулевой фундамент, легко понять!http://blog.csdn.net/jiangjunshow

Вы также можете перепечатать эту статью. Делитесь знаниями, приносите пользу людям и осознайте великое омоложение нашей китайской нации!

В Unity3d частота кадров игры может быть ограничена настройками кода.

Значение -1 означает неограниченную частоту кадров. Перевод с http://blog.csdn.net/huutu

Как правило, в мобильных играх мы ограничиваем частоту кадров до 30, и это нормально.

Но после добавления этого кода в проект он работал в Unity и не нашел применения. , , ,

Перевод с http://blog.csdn.net/huutu

Так что перейдите на официальный сайт, чтобы просмотреть информацию

Общая идея такова:

Application.targetFrameRate используется для запуска игры с указанной частотой кадров. Если установлено значение -1, игра будет работать с максимальной скоростью.

Но этот параметр повлияет на вертикальную синхронизацию.

Если установлена ​​вертикальная синхронизация, этот параметр будет отброшен и запущен в соответствии с частотой обновления экранного оборудования.

Если вертикальная синхронизация установлена ​​на 1, то это 60 кадров.

Если установлено значение 2, то это 30 кадров.

Щелкните меню «Редактор» -> «ProjectSetting-» — «QualitySettings», чтобы открыть панель настроек качества рендеринга.

Перевод с http://blog.csdn.net/huutu

1. Сначала отключите вертикальную синхронизацию, как показано выше.

Установите частоту кадров 100

Тогда частота кадров после запуска равна 100.

2. Установите вертикальную синхронизацию на 1

Вы можете видеть, что частота кадров колеблется около 60 кадров, полностью игнорируя настройки в коде.

Перевод с http://blog.csdn.net/huutu

3. Установите вертикальную синхронизацию на 2

Вы можете видеть, что частота кадров скачет около 30 кадров.

Перевод с http://blog.csdn.net/huutu

Отображение кода частоты кадров в игре:

Последнее предложение в официальном документе на веб-сайте . проверено, чтобы быть действительным в состоянии редактора. ,

Как понизить FPS?

Как понизить напряжение с 14.4 до 5 В
Добрый день! Есть аккумулятор на 14.4В, мне нужно получить 5В (для роутера). На многих форумах.

как понизить трафик
У меня в пакете всего гигобайт трафика. Докупила сейчас ещё 2, но не хочется каждый раз платить.

Как понизить температуру ЦП
У меня AMD FX4300, вроде не греется, и нет никаких багов, но вольтаж завышен. Как можно снизить.

Как понизить напряжение?
Вопрос от чайника: Есть блок питания 5В, 0,6А постоянного, стабилизированного тока. И есть.

Лучший ответСообщение было отмечено GSerge как решение

Решение

Как бы понизить напряжение
с диодного моста до 5В , при этом используя только пассивные элементы ? Или &quot;резануть&quot; верха. Для.

Как понизить уровень безопасности
Подскажите пожалуйста, как победить следущую ситуацию. На сетевом ресурсе есть аксессовская база.

Как понизить порядок матрицы с 4 до 3?
Есть матрица 4 на 4, как понизить ее порядок до 3-его, без разбора на миноры? 5 4 -4 1 8 .

как чистоту приемника понизить с 63 Гц до 27 Гц?
как чистоту приемника понизить с 63 Гц до 27 Гц.

Как понизить качество картинки
Определенной картинки например kartinka.jpg весом в 3 мегабайта, нужно сделать ну хотябы не более.

Как понизить напряжение с 12в до 8,5в?
Делаю зарядку аккумулятора в обход контроллера зарядки. Т.е. + от шлейфа зарядки пустил сразу на +.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *