unity3d fps游戏怎么给fps设置准心

最近在制作一款2d风格的unity iphone游戏,由于unity刚上手不久,因此经验上还是有很大的欠缺。特别是在场景的优化上。一开始我认为2d游戏应该消耗的资源比3d少很多??所以即使不用太多考虑场景优化应该对fps也不会有太大的影响,但我大错特错了!直到我发现我把游戏导入iphone后fps只有30,随着画面中敌人的增多,fps最终降至10!在忍无可忍的情况下,我决定做一些修改。
通过google以及unity answer上的一些搜索结果,要提升fps基本上可以从以下几点着手:
关于场景的优化,如有不对请多指教8050人阅读
Unity3D(123)
using UnityE
using System.C
public class Fps : MonoBehaviour
float updateInterval = 0.5f;
private float accum = 0.0f;
private float frames = 0;
// Use this for initialization
void Start()
if (!guiText)
timeleft = updateI
// Update is called once per frame
void Update()
timeleft -= Time.deltaT
accum += Time.timeScale / Time.deltaT
if (timeleft &= 0.0)
guiText.text = && + (accum / frames).ToString(&f2&);
timeleft = updateI
accum = 0.0f;
frames = 0;
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:431283次
积分:5470
积分:5470
排名:第2601名
原创:92篇
转载:73篇
评论:202条
(1)(1)(2)(1)(1)(7)(10)(2)(8)(4)(7)(2)(8)(6)(3)(1)(3)(11)(9)(8)(21)(5)(11)(12)(5)(14)(12)查看: 1195|回复: 5
最后登录注册时间阅读权限90积分32965
资深设计师, 积分 32965, 距离下一级还需 17035 积分
纳金币32806 精华12
看了很多&&太复杂&&求高手 给个代码 O(&_&)O 我懒 谢谢
最后登录注册时间阅读权限10积分30
设计初学者, 积分 30, 距离下一级还需 70 积分
纳金币30 精华0
用个 int 记录帧数` 在Update 里面每次加一&&然后在弄个记录时间的&&每次 += Time.deltaTime
然后当 记录时间的大于1就现实下记录的帧数 然后把帧数和时间清零`&&如此循环
最后登录注册时间阅读权限100积分70307
纳金币59031 精华16
& & // Attach this to a GUIText to make a frames/second indicator.
& & // It calculates frames/second over each updateInterval,
& & // so the display does not keep changing wildly.
& & // It is also fairly accurate at very low FPS counts (&10).
& & // We do this not by simply counting frames per interval, but
& & // by accumulating FPS for each frame. This way we end up with
& & // correct overall FPS even if the interval renders something like
& & // 5.5 frames.
& & var updateInterval = 0.5;
& & private var accum = 0.0; // FPS accumulated over the interval
& & private var frames = 0; // Frames drawn over the interval
& & private var timeleft : // Left time for current interval
& & function Start()
& & & & if( !guiText )
& && && & {
& & & && &&&print (&FramesPerSecond needs a GUIText component!&);
& & & && &&&enabled =
& & & && &&&
& & & & timeleft = updateI&&
& & function Update()
& & & & timeleft -= Time.deltaT
& & & & accum += Time.timeScale/Time.deltaT
& & & & ++
& & & & // Interval ended - update GUI text and start new interval
& & & & if( timeleft &= 0.0 )
& & & && &&&// display two fractional digits (f2 format)
& & & && &&&guiText.text = && + (accum/frames).ToString(&f2&);
& & & && &&&timeleft = updateI
& & & && &&&accum = 0.0;
& & & && &&&frames = 0;
最后登录注册时间阅读权限90积分32965
资深设计师, 积分 32965, 距离下一级还需 17035 积分
纳金币32806 精华12
最后登录注册时间阅读权限90积分21360
资深设计师, 积分 21360, 距离下一级还需 28640 积分
纳金币17491 精华31
学习了,虽然还是有难度,谢谢楼主的用心
最后登录注册时间阅读权限90积分28337
资深设计师, 积分 28337, 距离下一级还需 21663 积分
纳金币28625 精华31
谢谢楼主的帖子分享,学习了
活跃且尽责职守的版主
站长推荐 /1
纳金名模第83期餐桌椅模型:数量100个,大小为1.42GB。完全免费下载哦!这样的福利我和我的小伙伴们都惊呆了!!下载地址:
400-067-3919
Powered by - X2.5
Narkii Inc.[Unity3D]手机3D游戏开发:使用UnityRemote开发一个简单的FPS案例&&
学习Unity脚本推荐:
该案例来源是Digital Tutors的视频教程中的项目源码。
项目的下载的地址在:
手机游戏的开发建议使用UnityRemote,可以直接使用安卓机器运行项目,前提是一定要安装该安卓机的驱动。
UnityRemote的下载地址:
先来说下项目需求,做完之后大概实现一个任务的射击操作和碰撞检测,实现打中物体后的火化显示。
关键的源码大致有以下几个JS文件,可以先下载项目文件然后再对比阅读。
基本的模型不多说,直接看项目就懂,关键部分在于一下几个源码的解析。
先来简单的介绍一下这个案例中的四个JS脚本。
PlayerWeapons用来控制玩家的武器,AssaultRifle和Shotgun是两种武器的具体脚本,里面涉及到因为武器不同而导致的开Qiang频率不同的具体设定。DamageController是伤害的具体控制。
先看第一个脚本PlayerWeapons:
//This script is going to provide base functionality of any weapon we create
function Awake()
// Select the first weapon
SelectWeapon(1);
function Update ()
//Check if the fire button was pressed
if(Input.GetButton(&Fire1&))
BroadcastMessage(&Fire&);
if(Input.GetKeyDown(&1&))
SelectWeapon(0);
else if(Input.GetKeyDown(&2&))
SelectWeapon(1);
function SelectWeapon(index : int)
for (var i=0;i&transform.childCi++)
// Activate the selected weapon
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
// Deactivate all other weapons
transform.GetChild(i).gameObject.SetActiveRecursively(false);
在Hierachy面板中我们可以看到,各种枪都是在WeaponGo的子目录下的:
脚本通过使用SetActiveRecursively的方法来激活或取消激活武器。
使用for遍历所有武器确保每次只有一个武器处于激活的状态。
运行后可以发现,按下1后的武器和按下2后的武器不一样,同时Hierachy面板中明确的显示了武器的激活状态:
再看接下来的两个武器脚本,里面涉及到了开Qiang间隔的时间控制。
var shotCount : int = 8;
//Amount of pellets in a shotgun shell
private var shotSpread :
var range = 100.0;
var fireRate = 0.05;
var force = 10.0;
var damage = 5.0;
var bulletsPerClip = 15;
var clips = 20;
var reloadTime = 2.0;
private var mainCam : GameO
private var hitParticles : ParticleE
var muzzleFlash : R
var bulletsLeft : int = 0;
private var nextFireTime = 0.0;
private var m_LastFrameShot = -1;
private var reloading =
function Start ()
mainCam = GameObject.FindWithTag(&MainCamera&);
hitParticles = GetComponentInChildren(ParticleEmitter);
// We don't want to emit particles all the time, only when we hit something.
if (hitParticles)
hitParticles.emit =
bulletsLeft = bulletsPerC
function Fire()
if (bulletsLeft == 0)
// If there is more than one bullet between the last and this frame
// Reset the nextFireTime
if (Time.time - fireRate & nextFireTime)
nextFireTime = Time.time - Time.deltaT
// Keep firing until we used up the fire time
while( nextFireTime & Time.time && bulletsLeft != 0)
for (var i=0; i&shotC i++)
FireOneBullet();
nextFireTime += fireR
bulletsLeft--;
// Register that we shot this frame so that the LateUpdate function enabled the muzzleflash renderer
m_LastFrameShot = Time.frameC
// Reload gun in reload Time
if (bulletsLeft == 0)
function FireOneBullet ()
var layerMask = 1 && 8; // layer 8 is waypoints
layerMask = ~layerM // so hit everything but layer 8 (invert the mask)
var hits : RaycastHit[];
var direction = SprayDirection();
hits = Physics.RaycastAll(transform.position, direction, range,layerMask);
System.Array.Sort(hits, Comparison);
Did we hit anything?
for (var i=0;i&hits.i++)
var hit : RaycastHit = hits[i];
// Apply a force to the rigidbody we hit
if (hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
// Place the particle system for spawing out of place where we hit the surface!
// And spawn a couple of particles
if (hitParticles) {
var newParticles = Instantiate(hitParticles, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
newParticles.Emit();
newParticles.GetComponent(ParticleAnimator).autodestruct =
// Send a damage message to the hit object
hit.collider.SendMessageUpwards(&ApplyDamage&, damage, SendMessageOptions.DontRequireReceiver);
function Comparison(x : RaycastHit, y : RaycastHit) : int
var xDistance = x.
var yDistance = y.
return xDistance - yD
function SprayDirection()
var vx = (1 - 2 * Random.value) * .05;
var vy = (1 - 2 * Random.value) * .05;
var vz = 1.0;
return mainCam.transform.TransformDirection(Vector3(vx,vy,vz));
function Reload ()
// Wait for reload time first - then add more bullets!
if(bulletsLeft == 0)
yield WaitForSeconds(reloadTime);
// We have a clip left reload
if (clips & 0)
//clips--;
//-------uncomment if you want limited ammo
bulletsLeft = bulletsPerC
AssultRifle:
var range = 100.0;
//This is just a default value to give us a range that our weapon can shoot
var fireRate = 1.0;
//This is another default value that we can change directly in the editor to change the rate of fire
var force = 10.0;
//This variable gives us the ability to adjust how much force our weapon has when it shoots something
var damage = 10.0;
//This allows us to apply damage to enemies if they have hit points that must reach 0 before they actually die
var bulletsPerClip = 15;
//This variable gives us flexibility to◇◇ign how many bullets go into a clip of a specific weapon
var clips = 10;
//This variable gives the ability to have limited ammo
var reloadTime = 0.5;
//We need to be able to adjust how long it takes to reload our weapon
private var hitParticles : ParticleE
//We need some visual feedback that our bullets are hitting something
var muzzleFlash : R
//We also need to see if it's actually firing, plus it looks cool
private var bulletsLeft : int = 0;
//This variable is going to store how many bullets we have left in our clip
private var nextFireTime = 0.0;
//This is going to regulate our fire rate to use actual time instead of how fast the computer runs
private var m_LastFrameShot = -1;
//This also helps regulate the fire rate
function Start ()
//Start functions run any code as the level starts but does not continue to update
//Get the particle system attached to the AssaultRifleGO
hitParticles = GetComponentInChildren(ParticleEmitter);
//Keeps particles from emitting all the time
if(hitParticles)
hitParticles.emit =
bulletsLeft = bulletsPerC
function LateUpdate()
//LateUpdate functions updates every frame as long as the behaviour is enabled
if(muzzleFlash)
//We shot this frame so enable the muzzle flash
if(m_LastFrameShot == Time.frameCount)
//Enable our muzzle flash and animate it to rotate
muzzleFlash.transform.localRotation = Quaternion.AngleAxis(Random.Range(0, 359), Vector3.forward);
muzzleFlash.enabled =
//Play sound
if(!audio.isPlaying)
audio.Play();
audio.loop =
//We need to disable the muzzle flash
muzzleFlash.enabled =
//Stop sound
audio.loop =
//Can we fire? This function is going to check
function Fire ()
if(bulletsLeft == 0)
//If there is more than one bullet between the last and this frame, reset the nextFireTime
//This help regulate the fire rate to actual time
if(Time.time - fireRate & nextFireTime)
nextFireTime = Time.time - Time.deltaT
//Keep firing until we have used up the fire time
while(nextFireTime & Time.time && bulletsLeft != 0)
FireOneShot();
nextFireTime += fireR
//This function tells our weapon how to shoot
function FireOneShot()
//We need to cast a ray out in front of the player
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastH
//Check to see if we hit anything
if(Physics.Raycast(transform.position, direction, hit, range))
//Apply force to the rigid body we hit
if(hit.rigidbody)
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
//Spawn particles at the point we hit the surface
if(hitParticles)
var newParticles = Instantiate(hitParticles, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal));
hitParticles.transform.position = hit.
hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
hitParticles.Emit();
newParticles.GetComponent(ParticleAnimator).autodestruct =
//Send damage message to the hit object
hit.collider.SendMessageUpwards(&ApplyDamage&, damage, SendMessageOptions.DontRequireReceiver);
bulletsLeft --;
//We need to tell the LateUpdate function that we shot and that it can enable the muzzle flash and audio
m_LastFrameShot = Time.frameC
//We need to reload automatically if the clip is empty
if(bulletsLeft == 0)
function Reload()
//We want the actual reload to wait while the animation plays
yield WaitForSeconds(reloadTime);
//We need to check if we have a clip to reload
if(clips & 0)
bulletsLeft = bulletsPerC
//We may need to check how many bullets to reload if we have total ammo count
function GetBulletsLeft()
return bulletsL
这两个脚本有很多值得学习的地方,比如粒子的使用,音频的播放,时间Time的控制,信息传送等等,但是个人需求不同就不慢慢解释了,仅做参考。
最后就是伤害的处理DamageController:
@script RequireComponent(Rigidbody)
var hitPoints = 100.0;
//We need to determine the amount of hitPoints an enemy has
var explosionDelay = 0.0;
//This is just in case you want the ticks to delay on their explosion
var explosion : T
//This variable allows us to attach an explosion behaviour and the ability to control the enemy as it explodes
function ApplyDamage(damage : float)
//We need to check if the enemy is already dead
if(hitPoints &= 0.0)
hitPoints -=
if(hitPoints &= 0.0)
//StartEmittingParticles
var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
if(emitter)
emitter.emit =
Invoke(&DelayedExplosion&, explosionDelay);
function DelayedExplosion ()
BroadcastMessage(&Detonate&);
function Detonate()
Destroy(gameObject);
if(explosion)
Instantiate (explosion, transform.position, transform.rotation);
var emitter : ParticleEmitter = GetComponentInChildren(ParticleEmitter);
if(emitter)
emitter.emit =
emitter.transform.parent =
这个脚本是直接拖拽到敌人的GameObject上的,ApplyDamage是在武器脚本中调用的,SendMessageUpwards方法将该消息传播出去,并且由这个敌人GameObject接收信息并进行伤害处理。
这是一个简单的FPS案例,脚本或许作用不大,但是这个设计思路还是可取的,也就是使用一个GameObject来作为武器的父亲来实现武器的控制,并使用BroadcastMessage方法调用其他对象的函数。
深入的学习还请参照项目源码。
被转藏 : 1次}

我要回帖

更多关于 unity fps 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信