SlideShare a Scribd company logo
1 of 23
Optimizing Graphics Performance 그래픽 퍼포먼스가 낮아지는 이유는? 그려지는갯수? (화면상픽셀* 드로우 횟수) 쉐이더 연산? 버텍스 개수? Draw calls?
Draw calls 많은 수의 오브젝트들은 CPU의 부하를 주고, 많은 수의 triangle들은 GPU의 부하를 가져다 준다. 더해서 게임 코드를 위해서 또한 CPU가 필요. 오늘날에 그래픽 처리 장치는 초당 500 개의 draw call들 정도면적당하다. 각각의 픽셀 조명은 메쉬를한번더 그리게 되므로, 절대 많은 수의 픽셀 조명을 사용하지 말것!
Combining 씬내에 많은 수의 오브젝트들 – bad. 근접해 있는 오브젝트들간에 combine – good. “너무 많은 combine” – bad again.
Good Combining Combined objects are close to each other and use the same meterial Combine의 쉬운 예시로써는 집에 있는 방들 배치 같은경우 Often requires using texture sheets! 오브젝트 크기와 포인트/SPOT 라이트 크기가 같은 경우
Bad Combining 서로간에 멀리떨어진 오브젝트의 경우 절대 하지 말것. If light shines only on part of object, whole object needs to be drawn. 만약 조명이 오브젝트의 부분에만 드리워지면전체 오브젝트는 그려져야만 함. If camera sees only a tiny corner of object, 만약 카메라가 오브젝트 코너에 작은 영역만을 보는 경우 Whole object needs to be drawn. 전체 오브젝트가 그려질 필요가 있는경우
Combining Demo No combine
Combining Demo Combine all
Combining Demo Combineclose
Lights are for? 동적라이팅과정적라이트맵을합치는것. 라이트맵은 월드상에 고정적 빛 요소를 모두 제거 해준다. 빠르고 비주얼도 좋다. 그럼 동적 빛은 언제 써야할까? 로켓, 횟불, 동적 그림자등.. Culling masks!
Raycasting 레이캐스팅은 느려지며 각 프레임 별로 레이 캐스트 남용하지 말것. 컬링 마스크를 사용함으로써 레이캐스팅을 미리 방지 할 수 있다. 3프레임당 한번씩만 레이캐스팅을하는것은 어떨까? 컬링 마스크 = GUI : Layername부여.
Finding objects FindObjectsOfType, FindGameObjectWithTag, GameObject.Find Avoid doing it too much. It’s convenient but those calls can quickly add up. Use static variable 모든 활성화된 컴포넌트들을 static ArrayList와 OnEnable/OnDisable을 사용해서 저장 할 것.
Only Update nearby objects Don’t run scripts at all, when far away. Function Update() { if(far away) return; }does NOT count.Use enabled = false; Use triggers for finding out when player is close by or use coroutine that updates every seconds. 오브젝트가 근접했는지를 알아내기 위하여 Trigger를 사용또는 매초마다코-루틴 사용
Math Add, substract, multiply: a couple cycles. Divide : 30-40 cycles. Square root, sin, cos:60-100cycles Sqrt, Normalize In inner loops avoid Sqrt and Normalize. They are faily expensive. (Normalize internally uses Sqrt) Normalize = vec / sqrt(vec.x^2 + vec.y^2 + vec.z^2); use sqrMagnitude instead. If(distance > dif.magnitude) Bad! If(distance*distance > dif.sqrMagnitude)
Total Boids Demo Slow- 1.9FPS
Total Boids Demo Slow - code // Slow var neighbors = GameObject.FindGameObjectsWithTag("Vehicle"); // Slow varavgVelocity = Vector3.zero; for (var i=0;i<neighbors.Length;i++) { avgVelocity += neighbors[i].GetComponent(VehicleTags).velocity; } function ApplySeparation () { // Slow var neighbors = GameObject.FindGameObjectsWithTag("Vehicle"); // Slow var separate = Vector3.zero; for(var i=0; i<neighbors.Length; i++) { varposDiff = transform.position - neighbors[i].transform.position; separate += posDiff.normalized * (1.0 / (posDiff.sqrMagnitude + 0.5)); } separate.Normalize(); separate *= separateForce; steeringForce += separate; }
Total Boids Demo 1.Built-in array – 13.1FPS
Total Boids Demo 1.Built-in array – 13.1FPS function ApplySeparation () { /// OPTIMIZATION /// Use builtin array containing the vehicles instead of FindWithTag var separate = Vector3.zero; for(var i=0; i<allVehicles.Length; i++) { varposDiff = transform.position - allVehicles[i].transform.position; separate += posDiff.normalized * (1.0 / (posDiff.sqrMagnitude + 0.5)); } separate.Normalize(); separate *= separateForce; steeringForce += separate; }
1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS Total Boids Demo
1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS Total Boids Demo static function UpdateCachedPositions () { if (cachedPosition == null) cachedPosition = new Vector3[allVehicles.length]; for (var i=0;i<cachedPosition.length;i++) { cachedPosition[i] = allVehicles[i].transform.position; } } function ApplySeparation () { var separate = Vector3.zero; /// Optimizations /// * Cache position of our selves (no transform.position) /// * Cache position of other in an array updated once per frame (no transform.position) var position = transform.position; for(var i=0; i<allVehicles.Length; i++) { varposDiff = position - cachedPosition[i]; separate += posDiff.normalized * (1.0 / (posDiff.sqrMagnitude + 0.5)); } … }
1.Built-in array – 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS Total Boids Demo
1.Built-in array – 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS Total Boids Demo function ApplySeparation () { var separate = Vector3.zero; /// OPTIMIZATION ///  * Don't use Sqrt in innner loops var position = transform.position; for(var i=0; i<cachedPosition.Length; i++) { // Don't use Sqrt in innner loops // Save 1 division, 1 sqr root varposDiff = position - cachedPosition[i]; separate += posDiff / (posDiff.sqrMagnitude + 0.5); } … }
1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS 4.Precompute optimazation – 64.3FPS Total Boids Demo
1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS 4.Precompute optimazation – 64.3FPS Total Boids Demo static function UpdateCachedPositions () { if (cachedPosition == null) cachedPosition = new Vector3[allVehicles.length]; avgVelocity = Vector3.zero; for (var i=0;i<cachedPosition.length;i++) { cachedPosition[i] = allVehicles[i].transform.position; avgVelocity += allVehicles[i].velocity; } avgVelocity /= allVehicles.Length; } function ApplyAlignment () { /// Optimizations /// Precompute average velocity once per frame, no need to go through array var align = avgVelocity - velocity; align.Normalize(); align *= alignmentForce; steeringForce += align; }

More Related Content

What's hot

Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
henjeon
 
박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기
박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기
박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기
Kiheon Park
 
[Ndc11 박민근] deferred shading
[Ndc11 박민근] deferred shading[Ndc11 박민근] deferred shading
[Ndc11 박민근] deferred shading
MinGeun Park
 
니시카와젠지의 3 d 게임 팬을 위한 ps4
니시카와젠지의 3 d 게임 팬을 위한 ps4니시카와젠지의 3 d 게임 팬을 위한 ps4
니시카와젠지의 3 d 게임 팬을 위한 ps4
민웅 이
 
[1106 조진현] if you( batch rendering )
[1106 조진현] if you( batch rendering )[1106 조진현] if you( batch rendering )
[1106 조진현] if you( batch rendering )
진현 조
 
전형규, Vertex Post-Processing Framework, NDC2011
전형규, Vertex Post-Processing Framework, NDC2011전형규, Vertex Post-Processing Framework, NDC2011
전형규, Vertex Post-Processing Framework, NDC2011
devCAT Studio, NEXON
 

What's hot (20)

[IGC2018] 유영천 개발자 - Voxel기반 네트워크 게임 최적화기법
[IGC2018] 유영천 개발자 - Voxel기반 네트워크 게임 최적화기법[IGC2018] 유영천 개발자 - Voxel기반 네트워크 게임 최적화기법
[IGC2018] 유영천 개발자 - Voxel기반 네트워크 게임 최적화기법
 
빠른 렌더링을 위한 오브젝트 제외 기술
빠른 렌더링을 위한 오브젝트 제외 기술빠른 렌더링을 위한 오브젝트 제외 기술
빠른 렌더링을 위한 오브젝트 제외 기술
 
Sw occlusion culling
Sw occlusion cullingSw occlusion culling
Sw occlusion culling
 
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술Ndc2010 전형규   마비노기2 캐릭터 렌더링 기술
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
 
게임프로젝트에 적용하는 GPGPU
게임프로젝트에 적용하는 GPGPU게임프로젝트에 적용하는 GPGPU
게임프로젝트에 적용하는 GPGPU
 
박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기
박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기
박기헌 NDC12 초보 클라이언트 프로그래머의 병렬 프로그래밍 도전기
 
Modern gpu optimize
Modern gpu optimizeModern gpu optimize
Modern gpu optimize
 
[Ndc11 박민근] deferred shading
[Ndc11 박민근] deferred shading[Ndc11 박민근] deferred shading
[Ndc11 박민근] deferred shading
 
MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현
 
[Unite2015 박민근] 유니티 최적화 테크닉 총정리
[Unite2015 박민근] 유니티 최적화 테크닉 총정리[Unite2015 박민근] 유니티 최적화 테크닉 총정리
[Unite2015 박민근] 유니티 최적화 테크닉 총정리
 
니시카와젠지의 3 d 게임 팬을 위한 ps4
니시카와젠지의 3 d 게임 팬을 위한 ps4니시카와젠지의 3 d 게임 팬을 위한 ps4
니시카와젠지의 3 d 게임 팬을 위한 ps4
 
Visual Studio를 이용한 어셈블리어 학습 part 1
Visual Studio를 이용한 어셈블리어 학습 part 1Visual Studio를 이용한 어셈블리어 학습 part 1
Visual Studio를 이용한 어셈블리어 학습 part 1
 
GPU를 위한 병렬 음원 방향 추정 알고리즘
GPU를 위한 병렬 음원 방향 추정 알고리즘GPU를 위한 병렬 음원 방향 추정 알고리즘
GPU를 위한 병렬 음원 방향 추정 알고리즘
 
Motion blur
Motion blurMotion blur
Motion blur
 
[1106 조진현] if you( batch rendering )
[1106 조진현] if you( batch rendering )[1106 조진현] if you( batch rendering )
[1106 조진현] if you( batch rendering )
 
유니티 게임 그래픽스 아트 개발 사례 분석
유니티 게임 그래픽스 아트 개발 사례 분석유니티 게임 그래픽스 아트 개발 사례 분석
유니티 게임 그래픽스 아트 개발 사례 분석
 
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
 
Voxelizaition with GPU
Voxelizaition with GPUVoxelizaition with GPU
Voxelizaition with GPU
 
Compute shader DX11
Compute shader DX11Compute shader DX11
Compute shader DX11
 
전형규, Vertex Post-Processing Framework, NDC2011
전형규, Vertex Post-Processing Framework, NDC2011전형규, Vertex Post-Processing Framework, NDC2011
전형규, Vertex Post-Processing Framework, NDC2011
 

Similar to Unity performanceoptimzation

Deferred Shading
Deferred ShadingDeferred Shading
Deferred Shading
종빈 오
 
[0326 박민근] deferred shading
[0326 박민근] deferred shading[0326 박민근] deferred shading
[0326 박민근] deferred shading
MinGeun Park
 
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
zupet
 
[박민근] 3 d렌더링 옵티마이징_nv_perfhud
[박민근] 3 d렌더링 옵티마이징_nv_perfhud[박민근] 3 d렌더링 옵티마이징_nv_perfhud
[박민근] 3 d렌더링 옵티마이징_nv_perfhud
MinGeun Park
 
[NDC08] 최적화와 프로파일링 - 송창규
[NDC08] 최적화와 프로파일링 - 송창규[NDC08] 최적화와 프로파일링 - 송창규
[NDC08] 최적화와 프로파일링 - 송창규
ChangKyu Song
 

Similar to Unity performanceoptimzation (20)

Deferred Shading
Deferred ShadingDeferred Shading
Deferred Shading
 
[14.10.21] Far Cry and DX9 번역(shaderstudy)
[14.10.21] Far Cry and DX9 번역(shaderstudy)[14.10.21] Far Cry and DX9 번역(shaderstudy)
[14.10.21] Far Cry and DX9 번역(shaderstudy)
 
[0326 박민근] deferred shading
[0326 박민근] deferred shading[0326 박민근] deferred shading
[0326 박민근] deferred shading
 
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
[2B7]시즌2 멀티쓰레드프로그래밍이 왜 이리 힘드나요
 
Mapreduce tuning
Mapreduce tuningMapreduce tuning
Mapreduce tuning
 
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기헤테로지니어스 컴퓨팅 :  CPU 에서 GPU 로 옮겨가기
헤테로지니어스 컴퓨팅 : CPU 에서 GPU 로 옮겨가기
 
Modern gpu optimize blog
Modern gpu optimize blogModern gpu optimize blog
Modern gpu optimize blog
 
NDC11_슈퍼클래스
NDC11_슈퍼클래스NDC11_슈퍼클래스
NDC11_슈퍼클래스
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기
 
D2 Havok
D2 HavokD2 Havok
D2 Havok
 
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
시즌 2: 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
 
Gcd ppt
Gcd pptGcd ppt
Gcd ppt
 
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
실전프로젝트 정서경 양현찬
실전프로젝트 정서경 양현찬실전프로젝트 정서경 양현찬
실전프로젝트 정서경 양현찬
 
[Kgc2013] 모바일 엔진 개발기
[Kgc2013] 모바일 엔진 개발기[Kgc2013] 모바일 엔진 개발기
[Kgc2013] 모바일 엔진 개발기
 
[박민근] 3 d렌더링 옵티마이징_nv_perfhud
[박민근] 3 d렌더링 옵티마이징_nv_perfhud[박민근] 3 d렌더링 옵티마이징_nv_perfhud
[박민근] 3 d렌더링 옵티마이징_nv_perfhud
 
[NDC08] 최적화와 프로파일링 - 송창규
[NDC08] 최적화와 프로파일링 - 송창규[NDC08] 최적화와 프로파일링 - 송창규
[NDC08] 최적화와 프로파일링 - 송창규
 
Spring Cloud Workshop
Spring Cloud WorkshopSpring Cloud Workshop
Spring Cloud Workshop
 

Unity performanceoptimzation

  • 1. Optimizing Graphics Performance 그래픽 퍼포먼스가 낮아지는 이유는? 그려지는갯수? (화면상픽셀* 드로우 횟수) 쉐이더 연산? 버텍스 개수? Draw calls?
  • 2. Draw calls 많은 수의 오브젝트들은 CPU의 부하를 주고, 많은 수의 triangle들은 GPU의 부하를 가져다 준다. 더해서 게임 코드를 위해서 또한 CPU가 필요. 오늘날에 그래픽 처리 장치는 초당 500 개의 draw call들 정도면적당하다. 각각의 픽셀 조명은 메쉬를한번더 그리게 되므로, 절대 많은 수의 픽셀 조명을 사용하지 말것!
  • 3. Combining 씬내에 많은 수의 오브젝트들 – bad. 근접해 있는 오브젝트들간에 combine – good. “너무 많은 combine” – bad again.
  • 4. Good Combining Combined objects are close to each other and use the same meterial Combine의 쉬운 예시로써는 집에 있는 방들 배치 같은경우 Often requires using texture sheets! 오브젝트 크기와 포인트/SPOT 라이트 크기가 같은 경우
  • 5. Bad Combining 서로간에 멀리떨어진 오브젝트의 경우 절대 하지 말것. If light shines only on part of object, whole object needs to be drawn. 만약 조명이 오브젝트의 부분에만 드리워지면전체 오브젝트는 그려져야만 함. If camera sees only a tiny corner of object, 만약 카메라가 오브젝트 코너에 작은 영역만을 보는 경우 Whole object needs to be drawn. 전체 오브젝트가 그려질 필요가 있는경우
  • 9. Lights are for? 동적라이팅과정적라이트맵을합치는것. 라이트맵은 월드상에 고정적 빛 요소를 모두 제거 해준다. 빠르고 비주얼도 좋다. 그럼 동적 빛은 언제 써야할까? 로켓, 횟불, 동적 그림자등.. Culling masks!
  • 10. Raycasting 레이캐스팅은 느려지며 각 프레임 별로 레이 캐스트 남용하지 말것. 컬링 마스크를 사용함으로써 레이캐스팅을 미리 방지 할 수 있다. 3프레임당 한번씩만 레이캐스팅을하는것은 어떨까? 컬링 마스크 = GUI : Layername부여.
  • 11. Finding objects FindObjectsOfType, FindGameObjectWithTag, GameObject.Find Avoid doing it too much. It’s convenient but those calls can quickly add up. Use static variable 모든 활성화된 컴포넌트들을 static ArrayList와 OnEnable/OnDisable을 사용해서 저장 할 것.
  • 12. Only Update nearby objects Don’t run scripts at all, when far away. Function Update() { if(far away) return; }does NOT count.Use enabled = false; Use triggers for finding out when player is close by or use coroutine that updates every seconds. 오브젝트가 근접했는지를 알아내기 위하여 Trigger를 사용또는 매초마다코-루틴 사용
  • 13. Math Add, substract, multiply: a couple cycles. Divide : 30-40 cycles. Square root, sin, cos:60-100cycles Sqrt, Normalize In inner loops avoid Sqrt and Normalize. They are faily expensive. (Normalize internally uses Sqrt) Normalize = vec / sqrt(vec.x^2 + vec.y^2 + vec.z^2); use sqrMagnitude instead. If(distance > dif.magnitude) Bad! If(distance*distance > dif.sqrMagnitude)
  • 14. Total Boids Demo Slow- 1.9FPS
  • 15. Total Boids Demo Slow - code // Slow var neighbors = GameObject.FindGameObjectsWithTag("Vehicle"); // Slow varavgVelocity = Vector3.zero; for (var i=0;i<neighbors.Length;i++) { avgVelocity += neighbors[i].GetComponent(VehicleTags).velocity; } function ApplySeparation () { // Slow var neighbors = GameObject.FindGameObjectsWithTag("Vehicle"); // Slow var separate = Vector3.zero; for(var i=0; i<neighbors.Length; i++) { varposDiff = transform.position - neighbors[i].transform.position; separate += posDiff.normalized * (1.0 / (posDiff.sqrMagnitude + 0.5)); } separate.Normalize(); separate *= separateForce; steeringForce += separate; }
  • 16. Total Boids Demo 1.Built-in array – 13.1FPS
  • 17. Total Boids Demo 1.Built-in array – 13.1FPS function ApplySeparation () { /// OPTIMIZATION /// Use builtin array containing the vehicles instead of FindWithTag var separate = Vector3.zero; for(var i=0; i<allVehicles.Length; i++) { varposDiff = transform.position - allVehicles[i].transform.position; separate += posDiff.normalized * (1.0 / (posDiff.sqrMagnitude + 0.5)); } separate.Normalize(); separate *= separateForce; steeringForce += separate; }
  • 18. 1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS Total Boids Demo
  • 19. 1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS Total Boids Demo static function UpdateCachedPositions () { if (cachedPosition == null) cachedPosition = new Vector3[allVehicles.length]; for (var i=0;i<cachedPosition.length;i++) { cachedPosition[i] = allVehicles[i].transform.position; } } function ApplySeparation () { var separate = Vector3.zero; /// Optimizations /// * Cache position of our selves (no transform.position) /// * Cache position of other in an array updated once per frame (no transform.position) var position = transform.position; for(var i=0; i<allVehicles.Length; i++) { varposDiff = position - cachedPosition[i]; separate += posDiff.normalized * (1.0 / (posDiff.sqrMagnitude + 0.5)); } … }
  • 20. 1.Built-in array – 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS Total Boids Demo
  • 21. 1.Built-in array – 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS Total Boids Demo function ApplySeparation () { var separate = Vector3.zero; /// OPTIMIZATION /// * Don't use Sqrt in innner loops var position = transform.position; for(var i=0; i<cachedPosition.Length; i++) { // Don't use Sqrt in innner loops // Save 1 division, 1 sqr root varposDiff = position - cachedPosition[i]; separate += posDiff / (posDiff.sqrMagnitude + 0.5); } … }
  • 22. 1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS 4.Precompute optimazation – 64.3FPS Total Boids Demo
  • 23. 1.Built-in array - 13.1FPS 2.CachePosition – 33.5FPS 3.Magnitude optimazation – 46.5FPS 4.Precompute optimazation – 64.3FPS Total Boids Demo static function UpdateCachedPositions () { if (cachedPosition == null) cachedPosition = new Vector3[allVehicles.length]; avgVelocity = Vector3.zero; for (var i=0;i<cachedPosition.length;i++) { cachedPosition[i] = allVehicles[i].transform.position; avgVelocity += allVehicles[i].velocity; } avgVelocity /= allVehicles.Length; } function ApplyAlignment () { /// Optimizations /// Precompute average velocity once per frame, no need to go through array var align = avgVelocity - velocity; align.Normalize(); align *= alignmentForce; steeringForce += align; }