반응형



How to get a List<> from GetComponents?

GetComponents returns a []. Is there any one-liner way to convert that to a Generic (List or whatever)?





Answer by ArkaneX 

With LINQ (requires using System.Linq;):

  1. var list = GetComponents<SomeComponent>().ToList();

Without LINQ:

  1. var list = new List<SomeComponent>(GetComponents<SomeComponent>());

Code in C#.





ref : https://answers.unity.com/questions/630680/how-to-get-a-list-from-getcomponents.html

반응형
반응형

비주얼 어시스트 언리얼엔진이 생겼습니다




매크로 관련하여 생겼는데 기존에 다른 방법으로 추가 할수 있는방법 이 있었지만 본격적으로 지원을 하기 시작하네요



반응형
반응형

Can Rigidbody 2D collide with 3D Colliders?

Reading the extra details that this page talks about the colliders, http://docs.unity3d.com/Documentation/Components/class-Rigidbody2D.html, it seems that this 2d Rigid body can only collide with other 2D objects and not 3D objects. I've tried to make the player using a rigid 2d body collide with the regular 3d box collider but it keeps passing through. It does collide with the 2d box collider object below so I know I'm using the rigidbody 2d correctly at least.

Does anyone have any input on this?

2 Replies

 · Add your reply
avatar image
11

Answer by MiaN KhaLiD 

I stumbled upon this issue myself recently, and have found out that its not possible for a 2D object to collide with 3D object and vice versa. Reason being unity uses PhysX for 3D and Box2D for 2D, which are exclusive of each other.

So what options do we have, if we want a hybrid

There are 2 ways we can achieve collision between the 2 systems:

  1. To your 3D object add an empty game object as a child, with RigidBody2D (GravityScale set to 0) & a BoxCollider2D matching the width of the 3D Object. Then receive the collision event in the OnCollisionEnter2D(Collision2D collision) function.

  2. Or you can add a RigidBody and a 3D Collider (say BoxCollider) to your 2D object and receive the collision event in the OnCollisionEnter (Collision collision) function.

Hope it answers the question :)

avatar image
0

Answer by J0hn4n 

Or just make 2 childs one to handle 2d collision events and another one to handle 3d events, EZ. another alternative its just handle your own system already if you dont need physic its EZ too.


ref : https://answers.unity.com/questions/580769/can-rigidbody-2d-collide-with-3d-colliders.html

반응형
반응형

Box Collider 2D -failed verification- warning even when the size is reasonable

I have a script that is executed in Edit Mode, it creates various gameobjects with a Box Collider 2D component attached to each one of them, and rotates their transforms based on a logic in my game. The problem is that some of those Box Collider 2D components fire this warning after they're set:

The collider did not create any collision shapes as they all failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under certain rotations or very small scaling. "

As I change the rotation from the inspector of some of those created GOs, the Box Collider 2D component works again, so the warning is due to their rotations. Also note that the scale isn't the problem as it's set to 1.

My question is, what do the "working angles" have in common? I can take into account this information in my script to only include those specific angles and therefore generating working Box Colliders. It would be better if there was a solution for this problem regardless of the transform's rotation.



avatar image
2

Answer by Dewald_Bodenstein 

I've just found that, as soon as the rotation is about 90 degrees around the Y or X axis, the BoxCollider2D breaks. As I understand, this would be because its like scaling the collider down on one axis and it ends up being too small.

I am using 3d objects in my scene so the rotation can be necessary. The solution would be to attach the 3d object to a child and rotate the child instead.

avatar image
0

Answer by qateef20031 

I added a Rigidbody2D component and it worked.

ref : https://answers.unity.com/questions/580769/can-rigidbody-2d-collide-with-3d-colliders.html






반응형
반응형



PlayerPrefs 


- 데이터를 간단하게 저장할 수 있게 해주는 클래스

- key값과 데이터를 넣어 저장할 수 있고 , 반대로 key값을 넣어 데이터를 꺼낼 수도 있다.


저장 가능한 데이터 타입

int , float , string


1. 데이터 세팅 방법

PlayerPrefs.SetInt("hero_hp",10); // hero_hp 라는 key 값으로 10의 정수형 데이터를 집어 넣음

이런식으로 SetFloat, SetString 으로 float 와 String 의 값을 넣으면 된다.


2. 데이터 얻어오는 방법

PlayerPrefs.GetInt("hero_hp"); // hero_hp key에 대응하는 값을 돌려준다. key 가 없을경우 기본값을 돌려준다. ( 0 )

마찬가지로 GetFloat , GetString 도 해주면 된다.


3. 데이터 삭제

 ㄱ PlayerPrefs.DeleteKey("hero_hp"); // key값을 넣어 해당 key값을 가진 값을 삭제

 ㄴ PlayerPrefs.DeleteAll();                // 모든 데이터를 삭제


4. 데이터의 유무 체크

PlayerPrefs.HasKey("hero_hp"); 

key값이 존재한다면 true를 반환, 없다면 false 반환



5. 저장 방법

PlayerPrefs.Save();를 호출하면 된다.


6. 저장되는 공간

ㄱ Mac일 경우 : 

 ~/Library/Preferences 폴더에 unity.[company name].[product name].plist 이름으로 저장된다.

ㄴ Windows일 경우 :

 HKCU\Software\[company name]\[product name] 레지스트리에 저장된다.


ㄷ Mac , Web일 경우

~/Library/Preferences/Unity/WebPlayerPrefs  바이너리 파일 아래에 저장된다.

Windows , Web일 경우


 %APPDATA%\Unity\WebPlayerPrefs 에 저장된다.

* Web 에서는 1mb의 용량제한이 있고 웹 플레이어 URL당 하나의 파일을 사용할 수 있다.

 제한이 초과될 경우 PlayerPrefsException 을 던진다.



6. 보안 문제

다른 플랫폼은 테스트해보지 못했으나 맥에선 해당 plist를 열어볼 수 있다. ( 수정은 불가능하지만 )

일단 열어볼 수 있다는 것 하나만으로 보안이 그렇게 높은건 같지 않고, 정 사용하려면 key 값과 데이터를 암호화 해서 사용하는게 좋을듯 하다.



PlayerPrefs

class in UnityEngine

Description

게임 세션(session)사이에 플레이어 preference를 저장하고, preference에 접근합니다.

Mac OS X 에서 PlayerPrefs는 ~/Library/Preferences 폴더에 unity.[company name].[product name].plist의 파일이름으로 저장되며,

On Mac OS X PlayerPrefs are stored in ~/Library/Preferences folder, in a file named unity.[company name].[product name].plist, where company and product names are the names set up in Project Settings. Windows 독립 플레이어에서 PlayerPrefs는 @@HKCU
Software
[company name]
[product name]@@ 키 아래의 레지스트리에 저장되며 standalone players.

웹 플레이어에서 PlayerPrefs는 Mac OS X에서 ~/Library/Preferences/Unity/WebPlayerPrefs아래에 HKCU\Software\[company name]\[product name] key, where company and product names are 웹 플레이어 URL 당, 한개의 preference 파일이 존재하며, 파일 크기는 1메가 바이트로 제한됩니다. 파일 크기가 이 제한 값을 초과하는 경우,

On Linux, PlayerPrefs can be found in ~/.config/unity3d/[CompanyName]/[ProductName] again using the company and product names specified in the Project Settings.

On Windows Store Apps, Player Prefs can be found in %userprofile%\AppData\Local\Packages\[ProductPackageId]>\LocalState\playerprefs.dat

On Windows Phone 8, Player Prefs can be found in application's local folder, See Also: Windows.Directory.localFolder

On Android data is stored (persisted) on the device. The data is saved in SharerPreferences. C#/JavaScript, Android Java and Native code can all access the PlayerPrefs data. The PlayerPrefs data is physically stored in /data/data/pkg-name/shared_prefs/pkg-name.xml.

WebPlayer

On Web players, PlayerPrefs are stored in binary files in the following locations:

Mac OS X: ~/Library/Preferences/Unity/WebPlayerPrefs

Windows: %APPDATA%\Unity\WebPlayerPrefs

웹 플레이어에서 PlayerPrefs는 Mac OS X에서 ~/Library/Preferences/Unity/WebPlayerPrefs아래에

There is one preference file per Web player URL and the file size is limited to 1 megabyte. If this limit is exceeded, SetInt, SetFloat and SetString will not store the value and throw a PlayerPrefsException.

Static Functions

DeleteAllpreference에서 모든 key와 값들을 제거합니다. 사용 시 경고가 뜹니다.
DeleteKey키와 대응하는 값을 삭제합니다.
GetFloatPreference 파일에 존재하는 /key/에 대응하는 값을 반환합니다.
GetIntPreference 파일에 존재하는 /key/에 대응하는 값을 반환합니다.
GetStringPreference 파일에 존재하는 /key/에 대응하는 값을 반환합니다.
HasKey키가 존재하는지 확인합니다.
Save수정된 모든 preferences를 디스크에 씁니다.
SetFloat/key/로 식별된 Preference의 값을 설정합니다.
SetInt/key/로 식별된 Preference의 값을 설정합니다.
SetString/key/로 식별된 Preference의 값을 설정합니다.


ref : http://moonausosigi.tistory.com/entry/%EC%A0%95%EB%A6%AC-playerprefs

ref : https://docs.unity3d.com/kr/530/ScriptReference/PlayerPrefs.html


반응형
반응형



에러 내용 (유니티에서 페이스북(facebook) SDK 추가 후)


Your  Android setup is not correct. See Settings in Facebook menu.

UnityEngine.Debug:LogError(Object)

Facebook.Unity.Editor.XCodePostProcess:OnPostProcessBuild(BuildTarget, String)

UnityEditor.HostView:OnGUI()



위 오류를 해결하기 위해서는 Open SSL 설치하여야 합니다.

(JavaSDK도 없으시면 설치하고요.)



둘 다 없다고 가정하고 진행하겠습니다.

먼저, Open SSL을 아래 홈페이지 접속하여 받아주세요.


1. https://code.google.com/archive/p/openssl-for-windows/downloads

(최신버전 아니고 0.9.8 버전 - 안정적)


2. http://slproweb.com/products/Win32OpenSSL.html

 (공식페이지 최신 버전 받을 수 있음)


위 두 가지 중 선택하여 받으시면 됩니다.

저는 최신 버전에도 버그가 있다기에 0.9.8버전 받았습니다.


다운로드 받고, 설치하거나, 압축을 풀어줍니다.

(설치 시 설치되는 위치가 어딘지 확인해주세요.)


그리고 운영체제 환경과 맞는 걸로 받아야겠죠?

win 64 - 윈도우64비트 / win 32 - 윈도우32비트

일반적으로 win 64일 것 같습니다.



JavaSDK는 아래 오라클 홈페이지에서 받을 수 있습니다.


http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html


마찬가지로 작업환경과 맞는 파일 받아서 설치해주시고요.




두 파일 모두 설치했다면, 다음 단계로 진행하겠습니다.


이번에 설치한 OpenSSL와 JDK에  관한

환경변수를 새로 등록해줘야 합니다.


차근차근 봐볼까요?

먼저 탐색기를 켠 후,

왼쪽에 있는 '내 PC' 위에서 우측 클릭을 하면 위와 같은 설정창이 나옵니다.

거기서 속성을 선택해주세요.


이렇게 화면이 나올 텐데요.

여기서 좌측에 있는 '고급 시스템 설정'을 마우스 좌클릭해주시면 됩니다.


그러면 이렇게 화면이 나왔나요?

여기서 '환경 변수(N)'를 마우스 좌클릭해주세요.


환경 변수 탭에서는

아래쪽에 있는 시스템 변수 중

변수 Path를 찾으셔서 좌클릭해보면

위 사진처럼 파란줄이 되며 선택이 될 것 입니다.

그리고, 편집(I) 버튼을 눌러주세요.


이런식으로 나올 텐데,

여기에 환경 변수를 등록해줘야 합니다.


조금 전에 설치했던 OpenSSL의 bin 위치를 등록해줘야합니다.

(만약 위와 같이 JavaSDK도 등록 안 되어 있다면 같이 등록해주면 됩니다!)


C드라이브에 설치했던 위치를 찾아 등록하면 됩니다.

현재 저는 OpenSSL의 C드라이브에 설치했고,

C:\OpenSSL\bin 위치를 찾아가

그대로 복사하여 환경 변수에 추가해줬습니다.


이렇게요.


만약, OpenSSL 최신 설치하여 OpenSSL-Win64같은 이름이였다면,

'C:\OpenSSL-Win64\bin' 같은식으로 등록해주면 되겠죠?

(설치하여 저장된 위치 기준으로 등록해주시면 됩니다. - 역시 한글이 들어간 루트는 피해주시는 게 좋겠네요.)


마찬가지로 jdk도 등록이 안 되어있다면,

등록된 위치를 찾아가 등록해주세요.

(위에 제가 등록해둔 게 기본 위치입니다!

일반적으로

C:\Program Files\Java\jdk1.8.0_111\bin 같이 프로그램파일스 하위 자바 하위에 있습니다!)



그렇게 환경변수가까지 등록을 잘 마쳤다면,

컴퓨터를 껐다 켠(재시작) 후

유니티에 접속하여 빌드를 다시 시도해보면.

이렇게 오류 없이 정상적으로 빌드되는 것을 확인할 수 있습니다!


(제가 오류 해결하려고 찾아 해결한 방법 기준으로 했기에,

유사하지만 위 방법으로 처리가 안 되신다면 구글링을 더 거쳐보신다면 좋겠네요!)


위와 같은 오류로 안 되던 몇몇 분들께 도움이 되었으면 좋겠습니다.



ref : http://prosto.tistory.com/255 [Prosto]

반응형
반응형

다중 씬 편집(Multi Scene Editing)


다중 씬 편집을 사용하면 에디터에서 한 번에 여러 씬을 열 수 있으며 런타임 시 더욱 간편하게 씬을 관리할 수 있습니다.

에디터에서 여러 씬을 열면 대규모 스트리밍 월드를 생성할 수 있으며 공동으로 씬을 편집할 때 워크플로가 개선됩니다.

이 페이지는 다음 항목을 설명합니다.

  • 에디터에서 다중 씬 편집 통합
  • 에디터 스크립팅 및 런타임 스크립팅 API
  • 현재 알려진 문제

에디터에서

새 씬을 열어서 계층의 현재 씬 리스트에 추가하려면 씬 에셋의 컨텍스트 메뉴에서 씬 애디티브 열기를 선택하거나 프로젝트 창에서 하나 이상의 씬을 계층 구조 창으로 드래그하는 방법을 쓸 수 있습니다.

씬 애디티브 열기는 선택된 씬 에셋을 계층 구조가 보이는 현재 씬에 추가합니다
씬 애디티브 열기는 선택된 씬 에셋을 계층 구조가 보이는 현재 씬에 추가합니다

에디터에 여러 씬을 열어놓으면 각 씬의 콘텐츠가 계층 구조 창에 개별적으로 나타납니다. 각 씬의 콘텐츠는 씬의 이름과 저장 상태를 보여주는 씬 디바이더 바 아래에 표시됩니다.

여러 씬이 동시에 열려 있음을 보여주는 계층 구조 창
여러 씬이 동시에 열려 있음을 보여주는 계층 구조 창

씬은 계층에서 로드되거나 언로드되어 각 씬에 포함된 게임 오브젝트를 나타내거나 숨길 수 있습니다. 계층 구조 창에서 이를 추가 및 제거하는 것과는 다릅니다.

씬 디바이더는 많은 씬이 로드되어 있을 경우 계층 구조 탐색에 도움을 주는 씬 콘텐츠로 숨길 수 있습니다.

여러 씬을 작업할 때 수정된 각 씬의 변경사항은 추후에 저장되어야 하므로 저장되지 않은 여러 씬이 동시에 열려있는 상황이 발생할 수 있습니다. 저장되지 않은 변경사항이 있는 씬은 씬 디바이더 바에서 이름 옆에 별표가 뜹니다.

씬 디바이더의 별표는 해당 씬에 저장되지 않은 변경사항이 있음을 나타냅니다.
씬 디바이더의 별표는 해당 씬에 저장되지 않은 변경사항이 있음을 나타냅니다.

각 씬은 디바이더 바의 컨텍스트 메뉴를 통해 개별적으로 저장될 수 있습니다. 파일 메뉴에서 “씬 저장”을 선택하거나 Ctrl/Cmd + S를 누르면 열려 있는 모든 씬의 변경사항이 저장됩니다.

씬 디바이더 바의 컨텍스트 메뉴로 선택된 씬의 기타 동작을 수행할 수도 있습니다.

로드된 씬의 씬 디바이더 메뉴

Set Active Scene어떤 씬에 새로운 게임 오브젝트를 생성하거나 인스턴스화할지 지정할 수 있습니다. 항상 하나의 씬을 액티브 씬으로 표시해야 합니다.
Save Scene선택된 씬의 변경사항만 저장합니다.
Save Scene As선택된 씬(과 현재의 수정사항)을 새로운 씬 에셋으로 저장합니다.
Save All모든 씬의 변경사항을 저장합니다.
Unload Scene씬을 언로드하나 해당 씬을 계층 구조 창에 유지합니다.
Remove Scene씬을 계층 구조 창에서 언로드하고 제거합니다.
Select Scene Asset프로젝트 창에서 씬의 에셋을 선택합니다.
GameObject선택된 씬에서 게임 오브젝트를 생성하게 해주는 서브 메뉴를 제공합니다. 메뉴는 Unity의 메인 게임 오브젝트 메뉴에서 생성가능한 아이템을 미러링합니다. (아래 참조)
씬 디바이더 바 메뉴의 게임 오브젝트 서브 메뉴
씬 디바이더 바 메뉴의 게임 오브젝트 서브 메뉴

언로드된 씬의 씬 디바이더 메뉴

Load Scene씬의 콘텐츠를 로드합니다.
Remove Scene계층 구조 창에서 씬을 제거합니다.
Select Scene Asset프로젝트 창에서 씬의 에셋을 선택합니다.

여러 씬에서 라이트맵(Lightmaps) 베이킹

여러 씬의 Lightmap data를 한 번에 베이크하려면 베이크할 씬을 열고 라이팅 창에서 “자동” 모드를 해제한 후 조명을 빌드하기 위해 빌드 버튼을 클릭합니다.

조명 산출의 입력은 모든 씬에서의 정적 지오메트리와 광원입니다. 따라서 섀도우와 GI 광원 바운스는 모든 씬에서 작동합니다. 하지만 라이트맵과 리얼타임 GI 데이터는 각 씬마다 개별적으로 로드/언로드되는 데이터로 분리됩니다. 라이트맵과 리얼타임 GI 데이터 아틀라스는 씬별로 나뉩니다. 이는 씬별 라이트맵이 공유되지 않으며 씬을 언로딩할 때 안전하게 언로드될 수 있음을 의미합니다. 현재 라이트 프로브 데이터는 언제나 공유되며 함께 베이크된 모든 씬에서 라이트 프로브 전체가 동시에 로드됩니다.

아니면 에디터 스크립트의 Lightmapping.BakeMultipleScenes 함수로 여러 씬에서 라이트맵 빌딩을 자동화할 수 있습니다.

여러 씬에서 내비메시(Navmesh) 데이터 베이킹

여러 씬에서 한 번에 Navmesh data를 만들려면 베이크할 씬을 열고 내비게이션 창에서 베이크 버튼을 클릭합니다. 내비메시 데이터는 하나의 에셋으로 베이크되며 로드된 모든 씬에서 공유됩니다. 데이터는 현재 사용 중인 씬의 이름과 일치하는 폴더에 저장됩니다(예를 들어, ActiveSceneName/NavMesh.asset). 로드된 모든 씬은 내비메시 에셋을 공유합니다. 내비메시를 베이크한 후 영향을 받은 씬은 씬에서 내비메시로 참조가 유지되도록 저장해야 합니다.

아니면 에디터 스크립트의 NavMeshBuilder.BuildNavMeshForMultipleScenes 함수로 여러 씬에서 내비메시 데이터 빌딩을 자동화할 수 있습니다.

플레이모드(Playmode)

플레이모드에서 여러 씬이 계층 구조에 있는 상태로 DontDestroyOnLoad라는 추가 씬이 나타납니다.

Unity 5.3 이전에는 “DontDestroyOnLoad”로 표시된 플레이모드에서 인스턴스화하는 모든 오브젝트가 여전히 계층 구조에 표시되어 있습니다. 이러한 오브젝트는 특정 씬의 일부로 간주되진 않지만 Unity가 계속 오브젝트를 보여주고 사용자가 확인할 수 있도록 이제는 DontDestroyOnLoad 씬의 일부로 나타납니다.

DontDestroyOnLoad 씬에 액세스할 필요는 없으며 런타임 시에는 가능하지 않습니다.

씬별 설정

일부 설정은 각 씬에 지정되며, 예시는 다음과 같습니다.

  • RenderSettings 및 LightmapSettings(둘 다 라이팅 창에 있음)
  • 내비메시 설정
  • 오클루전 컬링 창의 씬 설정

각 씬은 자체 설정을 관리하고 해당 씬에 관련된 설정만 씬 파일에 저장되는 방식으로 작동합니다.

여러 씬이 열려 있으면 렌더링과 내비메시에 사용되는 설정은 active scene의 설정입니다. 씬의 설정을 변경하려는 경우 하나의 씬만 열어서 설정을 바꾸거나 해당 씬을 액티브 씬으로 만들어 설정을 변경해야 합니다.

에디터 또는 런타임 시점에 액티브 씬을 전환하면 새로운 씬의 모든 설정이 적용되며 이전 설정을 모두 대신합니다.

스크립팅

에디터 스크립팅(Editor Scripting)

에디터 스크립팅용으로 Scene struct와 EditorSceneManager API, SceneSetup 유틸리티 클래스를 제공합니다.

Scene struct는 에디터와 런타임 모두에서 가능하며 씬 자체에 관련된 이름, 에셋 경로 등 읽기 전용의 프로퍼티 일부를 포함합니다.

EditorSceneManager class는 에디터에서만 가능합니다. SceneManager에서 유래되며 에디터 스크립팅을 통해 위에 설명한 모든 다중 씬 편집 기능을 구현할 수 있는 함수를 보유합니다.

SceneSetup class는 현재 계층 구조에 있는 씬에 대한 정보를 저장하는 소규모 유틸리티 클래스입니다.

Undo와 PrefabUtility 클래스는 여러 씬을 지원하도록 확장됐습니다. 이제는 주어진 씬에서 프리팹을 [PrefabUtility.InstantiatePrefab]으로 인스턴스화할 수 있습니다. 또한 (Undo.MoveGameObjectToScene)[ScriptRef:Undo.MoveGameObjectToScene]를 활용해 실행 취소 가능한 방식으로 오브젝트를 씬의 루트로 옮길 수 있습니다.

참고Undo.MoveGameObjectToScene를 사용하려면 게임 오브젝트가 이미 현재의 씬 루트에 위치하는지를 확인해야 합니다.

런타임 스크립팅(Runtime Scripting)

런타임 시점의 스크립팅과 관련하여 LoadScene과 UnloadScene처럼 여러 씬에 작동하는 함수는 SceneManager 클래스에서 볼 수 있습니다.

참고

파일 메뉴에서 다른 이름으로 저장은 액티브 씬만 저장합니다. 씬 저장은 제목 없는 씬이 있다면 이름을 지정하는 작업을 포함하여 수정된 모든 씬을 저장합니다.

프로젝트 창의 생성 메뉴에서 새로운 씬 에셋 만들기
프로젝트 창의 생성 메뉴에서 새로운 씬 에셋 만들기

팁과 요령

씬을 계층 구조에 추가하는 한편 드래그할 때 Alt 키를 눌러 언로드된 상태를 유지할 수 있습니다. 이러한 경우 나중에 원할 경우 씬을 로딩할 수 있는 옵션이 주어집니다.

새 씬은 프로젝트 창의 생성 메뉴에서 생성됩니다. 새 씬은 게임 오브젝트의 디폴트 설정을 포함합니다.

Unity를 새로 시작할 때마다 계층 구조를 설정해야 하는 상황을 피하거나 서로 다른 설정을 손쉽게 저장할 수 있도록 EditorSceneManager.GetSceneManagerSetup을 활용하여 현재 설정을 기술하는 SceneSetup 오브젝트 리스트를 얻을 수 있습니다. 그리고 이를 씬 설정에 저장할 기타 정보와 더불어 ScriptableObject 등으로 직렬화할 수 있습니다. 계층을 복원하려면 SceneSetups 리스트를 다시 생성하고 EditorSceneManager.RestoreSceneManagerSetup를 활용하십시오.

런타임 동안 로드된 씬의 리스트를 얻으려면 sceneCount를 받은 후 GetSceneAt를 씬에 반복적으로 적용합니다.

게임 오브젝트가 속한 씬을 GameObject.scene으로 얻을 수 있으며 SceneManager.MoveGameObjectToScene을 활용해 게임 오브젝트를 씬의 루트로 옮길 수 있습니다.

씬에서 남겨두기 원하는 게임 오브젝트를 지속적으로 관리하는 데 DontDestroyOnLoad를 사용하는 것은 권장하지 않습니다. 대신 모든 매니저가 있는 manager scene을 생성하고 게임 프로세스를 관리할 때 SceneManager.LoadScene(<path>, LoadSceneMode.Additive)SceneManager.UnloadScene을 활용하십시오.

알려진 사항

  • 크로스씬 레퍼런스는 지원되지 않지만 사용할 수 없는 것은 아닙니다. 씬을 저장할 수 없으므로 편집 모드에서는 크로스씬 레퍼런스를 사용할 수 있습니다.
  • Umbra의 오클루전 컬링 데이터는 추가로 로드되지 않습니다.


ref : https://docs.unity3d.com/kr/current/Manual/MultiSceneEditing.html

반응형
반응형



WaitUntil

Description

Suspends the coroutine execution until the supplied delegate evaluates to true. (이건 조건이 true 면 WaitUntil 종료)

WaitUntil can only be used with a yield statement in coroutines.

Supplied delegate will be executed each frame after script MonoBehaviour.Update and before MonoBehaviour.LateUpdate. When the delegate finally evaluates to true, the coroutine will proceed with its execution.

using UnityEngine;
using System.Collections;

public class WaitUntilExample : MonoBehaviour { public int frame;

void Start() { StartCoroutine(Example()); }

IEnumerator Example() { Debug.Log("Waiting for princess to be rescued..."); yield return new WaitUntil(() => frame >= 10); Debug.Log("Princess was rescued!"); }

void Update() { if (frame <= 10) { Debug.Log("Frame: " + frame); frame++; } } }

Constructors

WaitUntilInitializes a yield instruction with a given delegate to be evaluated.

Inherited Members

Properties

keepWaitingIndicates if coroutine should be kept suspended.





WaitWhile



Description

Suspends the coroutine execution until the supplied delegate evaluates to false(이건 조건이 false 이면 WiatWhile 종료)

WaitWhile can only be used with a yield statement in coroutines.

The supplied delegate will be executed each frame after MonoBehaviour.Update and before MonoBehaviour.LateUpdate. When the delegate finally evaluates to false, the coroutine will proceed with its execution.

using UnityEngine;
using System.Collections;

public class WaitWhileExample : MonoBehaviour { public int frame;

void Start() { StartCoroutine(Example()); }

IEnumerator Example() { Debug.Log("Waiting for prince/princess to rescue me..."); yield return new WaitWhile(() => frame < 10); Debug.Log("Finally I have been rescued!"); }

void Update() { if (frame <= 10) { Debug.Log("Frame: " + frame); frame++; } } }

Constructors

WaitWhileInitializes a yield instruction with a given delegate to be evaluated.

Inherited Members

Properties

keepWaitingIndicates if coroutine should be kept suspended.



ref : https://docs.unity3d.com/ScriptReference/WaitWhile.html

ref : https://docs.unity3d.com/ScriptReference/WaitUntil.html


반응형
반응형

이벤트 함수 실행 순서(Execution Order of Event Functions)

Unity 이벤트 함수는 사전에 정해진 순서대로 실행됩니다. 실행 순서는 다음과 같습니다.

에디터

  • Reset: 오브젝트에 처음 연결하거나 Reset 커맨드를 사용할 때 스크립트의 프로퍼티를 초기화하기 위해 Reset을 호출합니다.

첫 번째 씬 로드

다음 함수는 씬이 시작할 때(씬에서 오브젝트마다 한 번) 호출됩니다.

  • Awake: 이 함수는 항상 Start 함수 전에 호출되며 프리팹이 인스턴스화 된 직후에 호출됩니다. 게임 오브젝트가 시작하는 동안 비활성 상태인 경우 Awake 함수는 활성화될 때까지 호출되지 않습니다.
  • OnEnable: (오브젝트가 활성화된 경우에만): 오브젝트 활성화 직후 이 함수를 호출합니다. 레벨이 로드되거나 스크립트 컴포넌트를 포함한 게임 오브젝트가 인스턴스화될 때와 같이 MonoBehaviour를 생성할 때 이렇게 할 수 있습니다.
  • OnLevelWasLoaded: 이 함수는 세 레벨이 로드된 게임을 통지하기 위해 실행됩니다.

씬에 추가된 모든 오브젝트에 대해 Start, Update 등 이전에 호출된 모든 스크립트를 위한 Awake 및 OnEnable 함수가 호출됩니다. 

원래 오브젝트가 게임플레이 도중 인스턴스화될 때 실행되지 않습니다.


[첨부]

  • (오브젝트 두개 A, B 추가해 놓고 각각 다른 스크립트를 붙여 놓은 후 awake, onenable, start  실행 순서의 관계를 보면 Awake 와 OnEnalbe 의 경우 
    동일한 오브젝트의 Awake 와 OnEnalbe 이 호출되는 순서를 보인다, 
    즉 A 오브젝트에 붙인 스크립트에 Awake ,가 호출된 후 OnEnalbe 이호출 되고
    B 오브젝트에 붙인 스크립트에 Awake ,가 호출된 후 OnEnalbe 이호출 되는 Awake 와 OnEnable 의 세트적인? 경향을 보이고 다음
    Awake 와 OnEnalbe 의 호출이 다른 오브젝트 들에서 모두 완료 된 이후에 각각 한번씩 Start 함수가 호출되기 시작한다


첫 번째 프레임 업데이트 전에

  • Start: 스크립트 인스턴스가 활성화된 경우에만 첫 번째 프레임 업데이트 전에 호출됩니다.

씬에 추가된 모든 오브젝트에 대해 Update 등 이전에 호출된 모든 스크립트를 위한 Start 함수가 호출됩니다. 원래 오브젝트가 게임플레이 도중 인스턴스화될 때 실행되지 않습니다.

프레임 사이

  • OnApplicationPause: 이 함수는 일시 정지가 감지된 프레임의 끝, 실질적으로는 일반 프레임 업데이트 사이에 호출됩니다. 게임에 일시정지 상태를 가리키는 그래픽스를 표시하도록 OnApplicationPause 가 호출된 후에 한 프레임이 추가로 실행됩니다.

업데이트 순서

게임 로직, 상호작용, 애니메이션, 카메라 포지션의 트랙을 유지할 때, 사용 가능한 몇몇 다른 이벤트가 존재합니다. 일반적인 패턴은 Update 함수에 대부분의 작업을 수행하는 것이지만, 사용할 수 있는 다른 함수도 있습니다.

  • FixedUpdate: FixedUpdate 는 종종 Update 보다 더 자주 호출됩니다. 프레임 속도가 낮은 경우 프레임당 여러 번 호출될 수 있으며 프레임 속도가 높은 경우 프레임 사이에 호출되지 않을 수 있습니다. 모든 물리 계산 및 업데이트는 FixedUpdate 후 즉시 발생합니다. FixedUpdate 의 움직임 계산을 적용할 때 Time.deltaTime 만큼 값을 곱할 필요가 없습니다. FixedUpdate 가 프레임 속도와 관계없이 신뢰할 수있는 타이머에서 호출되기 때문입니다.

  • Update: Update 는 프레임당 한 번 호출됩니다. 프레임 업데이트를 위한 주요 작업 함수입니다.

  • LateUpdate: LateUpdate 는 Update 가 끝난 후 프레임당 한 번 호출됩니다. Update 에서 수행된 모든 계산은 LateUpdate 가 시작할 때 완료됩니다. LateUpdate 는 일반적으로 다음의 3인칭 카메라에 사용합니다. 캐릭터를 움직이고 Update 로 방향을 바꾸게 하는 경우 LateUpdate 에서 모든 카메라 움직임과 로테이션 계산을 수행할 수 있습니다. 이렇게 하면 카메라가 포지션을 추적하기 전에 캐릭터가 완전히 움직였는지 확인할 수 있습니다.

렌더링

  • OnPreCull: 카메라가 씬을 컬링하기 전에 호출됩니다. 컬링은 어떤 오브젝트를 카메라에 표시할지 결정합니다. OnPreCull은 컬링 발생 직전에 호출됩니다.
  • OnBecameVisible/OnBecameInvisible: 오브젝트가 카메라에 표시되거나/표시되지 않을 때 호출됩니다.
  • OnWillRenderObject: 오브젝트가 표시되면 각 카메라에 한 번 호출됩니다.
  • OnPreRender: 카메라가 씬 렌더링을 시작하기 전에 호출됩니다.
  • OnRenderObject: 모든 일반 씬 렌더링이 처리된 후 호출됩니다. 이 때 커스텀 지오메트리를 그리는 데에 GL 클래스 또는 Graphics.DrawMeshNow를 사용할 수 있습니다.
  • OnPostRender: 카메라가 씬 렌더링을 마친 후 호출됩니다.
  • OnRenderImage: Called after scene rendering is complete to allow post-processing of the image, see Post-processing Effects.
  • OnGUI: GUI 이벤트에 따라 프레임당 여러 번 호출됩니다. 레이아웃 및 리페인트 이벤트는 우선 처리되며 각 입력 이벤트에 대해 레이아웃 및 키보드/마우스 이벤트가 다음으로 처리됩니다.
  • OnDrawGizmos: 시각화 목적으로 씬 뷰에 기즈모를 그릴 때 사용됩니다.

코루틴

일반적인 코루틴 업데이트는 Update 함수가 반환된 후 실행됩니다. 코루틴은 주어진 YieldInstruction이 완료될 때까지 실행을 중단(양보)할 수 있는 함수입니다. 코루틴의 다른 사용법은 다음과 같습니다.

  • yield 코루틴은 모든 Update 함수가 다음 프레임에 호출된 후 계속됩니다.
  • yield WaitForSeconds 지정한 시간이 지난 후, 모든 Update 함수가 프레임에 호출된 후 계속됩니다.
  • yield WaitForFixedUpdate 모든 FixedUpdate가 모든 스크립트에 호출된 후 계속됩니다.
  • yield WWW WWW 다운로드가 완료된 후 계속됩니다.
  • yield StartCoroutine 코루틴을 연결하고 MyFunc 코루틴이 먼저 완료되기를 기다립니다.

오브젝트를 파괴할 때

  • OnDestroy: 오브젝트 존재의 마지막 프레임에 대해 모든 프레임 업데이트를 마친 후 이 함수가 호출됩니다. 오브젝트는 Object.Destroy 또는 씬 종료에 대한 응답으로 파괴될 수 있습니다.

종료 시

다음 함수는 씬의 활성화된 모든 오브젝트에서 호출됩니다.

  • OnApplicationQuit: 이 함수는 애플리케이션 종료 전 모든 게임 오브젝트에서 호출됩니다. 에디터에서 사용자가 플레이 모드를 중지할 때 호출됩니다.
  • OnDisable: 동작이 비활성화되거나 비활성 상태일 때 이 함수가 호출됩니다.

스크립트 수명 주기 플로우차트

다음 다이어그램은 스크립트의 수명 동안 이벤트 함수의 호출 순서에 대한 요약입니다.





이전까지는 일반 업데이트와 물리 업데이트 이 이후부턴 주로 렌더링 위주의 업데이트




ref : https://docs.unity3d.com/kr/current/Manual/ExecutionOrder.html






MonoBehaviour 실행순서



오브젝트 생성 순서와 상관없이 컴포넌트 추가 시점에서 가장 나중에 추가 된것이 가장 먼저 실행됩니다.


ScriptExcution Order 에서 컴포넌트 종류단위로 조정 가능하지만

동일 컴포넌트 경우에 시간 순서가 결과에 영향을 준다면 나중에 실행되고 있는것을 삭제후 다시 추가하면 최우선으로 실행됩니다.
(그 반대는 으왕)

[복수 선택후 일괄 컴포넌트 추가시] Hierarchy 에 보이는것과 상관 없이

GameObject가 생성된 순서 역순으로 컴포넌트가 추가됩니다 
(가급적이면 이런 시간 의존관계가 없도록 설계하는것이 좋겠지요)



여러 컴포넌트가 추가된경우 별도로 강제 order 변경이 없다면 
이것역시 컴포넌트 종류 상관없이 가장 나중에 추가 된것부터 시간 역순으로 실행


첨부 파일은 

1. GameObject 생성한 순서대로 추가한경우

2. GameObject 생성순서 역순으로 추가한 경우

3. 트리구조 변경후 다수선택후 일괄추가

4. 순서 변경후 다수선택후 일괄추가


ref : http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_Lecture&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=hit&desc=asc&no=411
 


반응형
반응형
Invoke와 StartCoroutine 의 차이는 오브젝트 비활성화일때의 실행여부


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
void OnEnable()
{
   InvokeRepeating("Func1"01.0f);
 
   StartCoroutine(Func2());
 
}
 
void Func1()
{
  Debug.Log("Invoke");
}
 
 
IEnumerator Func2()
{
 
  while (true)
  {
    Debug.Log("Coroutine");
    yield return new WaitForSeconds(1.0f);
 }
}
 



컴포넌트가 활성화 됐을 때 Func1 과 Func2 를 각각 InvokeRepeating 과 StartCoroutine 으로 호출하고 있다.




이 상태에서 컴포넌트가 비활성화 되더라도 Func1 과 Func2 는 계속 수행된다. 단 게임 오브젝트가 비활성화되면 Coroutine 은 일시 정지하도록 되어 있기 때문에 Func2 는 수행되지 않고 Func1 은 여전히 호출된다.




다시 컴포넌트가 활성화가 됐다고 해보자. 결과는 Func1 과 Func2 가 매번 두 번씩 중복 호출된다. Invoke 혹은 Coroutine 모두 같은 함수에 대해 개별적인 호출로 본다.




이렇게 중복 호출되는 것을 막기 위해서 OnDisable 을 아래처럼 구현해주면 된다.




void OnDisable()


{


CancelInvoke();


StopAllCoroutines();


}




CancelInvoke 와 StopAllCoroutines 는 "현재 컴포넌트"에 존재하는 모든 Invoke 및 Coroutine 을 종료시킨다.




ref : http://cacodemon.tistory.com/entry/Invoke-와-Coroutine-주의사항








[invoke 관련 함수들]



오늘은 간단한 딜레이를 주고, 반복작업을 할때는 Coroutine보다 더 간편한 invoke함수에 대해서 알아보겠습니다.


invoke 함수는 총 4가지 함수만 알아두면 유용하게 사용할수있습니다.


1.Invoke 


위의 함수를 보시면 Invoke구문의 간단한 사용 예를 볼수있습니다. 

Invoke("실행하고자하는 함수" , 딜레이시간) 구문으로 간단하게 원하는 함수를 일정 시간 딜레이 후에

실행시킬 수있습니다. 위에 예에서는 LaunchProjectile 함수를 2초후에 실행시키는 구문을 보여주고있습니다.


2.InvokeRepeating



단순히 일정시간후에 함수를 실행시키는 것에서 더 나아가 딜레이후에  일정시간마다 함수를 반복적으로 실행시켜

주고싶을때 InvokeRepeating 함수를 사용합니다. 위의 Invoke함수에서와 달라진것은 0.3 의 float값이 들어간것인데

위의 예에서는 LaunchProjectile함수를 2초 딜레이후에 실행시킨후 0.3초마다 반복하여 실행시켜주는 구문입니다.


3.CancelInvoke


Invoke함수는 실행만큼이나 취소또한 쉽습니다. CancleInvoke함수르 간단하게 실행되고있는모든 Invoke함수를

취소시킬수있습니다. 위의 예에서는 Fire버튼을 누르면 실행되고있는 Invoke함수가 취소되는 것을 알수있습니다.


4.IsInvoking


 

현재 Invoke함수가 실행되고있는지 파악해 줄수있는 구문이 바로  IsInvoking함수입니다. 현재 invoke가 실행중일때 혹은 실행중이지 않을때를

판단하여 어떤 작업을 수행하려 할때 사용하는 함수로써.

위의 예시에서는 invoke함수가 실행중이지 않을때 , 스페이스 버튼을 누르면 Invoke함수가 실행되도록 작성되어있습니다.


이전포스팅의 Coroutine과 invoke 를 자유자재로 다룰수있다면 원하는 함수를 원하는 시간에 작동시키는것은

복잡한 쓰레딩을 익히지 않더라고 충분히 가능한 일일것입니다.



ref : http://blog.naver.com/enzymek/220273562019



반응형
반응형


 유니티에서 버튼에 CallBack을 등록시키기 위해서 에디터에서 클래스와 메쏘드를 지정하는 방법이 있고, 스크립트에서 직접 등록하는 방법이 있다.

이 때 등장하는 것이 UnityEvent이다. UnityEvent는 MonoBehavior를 상속받는 모든 클래스에 사용가능하다. 일단 선언이 되면 Editor에서 CallBack 함수를 등록하는 GUI가 추가되는 것을 볼 수 있다.


간단하기야 당연히 이렇게 Editor에서 Class의 Method를 지정해 주는 것이 간단하지만, 실제로는 에셋과 스크립트 간의 버젼 충돌을 피하고 원활한 업데이트를 위해서 스크립트로 이벤트를 집어 넣어주는 경우가 많다. 그 때 쓰이는 함수가 AddListener이다.

인자로 들어가는 것이 Events.UnityAction인데 이 UnityAction은 유니티에서 엔진에서 사용하려고 미리 만들어 놓은  C# Delegate이다. 정의는 아래와 같이 void부터 4개의 인자를 가지는 Delegate까지 커버한다. 


 그렇다면 해당 Delegate를 등록받는 onClick 이라는 녀석은 무엇일까?
바로 이 onClick이 UnityEventBase를 상속받는 UnityEvent 클래스의 Instance이다.  즉, 이 Class의 Instance에 UnityAction을 Register하는 것이다. 그런 다음 해당 클래스의 Invoke 메소드가 호출되면서 모든 등록된 Delegate들이 실행되게 된다.

 

UnityEvent가 UnityAction을 취하는 방법을 살펴 보면, 

위 코드에서 A키를 8회 눌렀을 때 출력은 아래와 같다. 순서대로 찍히고 마지막에 다 찍힌다.

 

동일한 기능을 하는 코드를  UnityEvent와 UnityAction을 이용하면 아래와 같이 구현할 수 있다. 

이렇게 하면 코드량은 조금 더 길어 보일 지 모르나, 각 이벤트에 등록된 UnityAction의 추가(AddListener) 및 삭제(RemoveListener)가 동적으로 자유로우므로, 마치 Observer Pattern을 적용한 느낌도 나면서 훨씬 더 유연한 코드 작성이 가능하다. (사실 UnityEvent는 미리 구현하여 내장된 Observer Pattern으로 보는 것이 맞을 것이다.)


아래와 같이 추상 클래스인 UnityEvent<T0>를 상속하여 선언함으로써 인자를 넘겨 주는 타입의 UnityAction을 호출할 수도 있다. 인자를 4개 받는 것까지 확장 가능하다.


Unity에서 사용하는 Mono 2.x는 C# 3.0까지는 안전하게 지원하므로, C# 3.0 버젼의 Lambda를 이용할 수 있다. Lambda expression은 anonymous function의 일종으로 이를 이용하면 간단히 delegate를 생성 가능하다.  따라서, 아래와 같이 동일 기능을 더 간단히 구현할 수 있다. Lambda 정의 Ref

또한, C# 2.0에서부터 도입된, delegate-method-group-conversion에 의해서 바로 Method name을 Delegate에 Assign할 수도 있다. 

이러한 모든 방법들을 다 Event를 거는데 활용해보면, 결과적으로 다음 코드와 같이 다양한 형태를 받는 AddListener가 나올 수 있게 된다.

 

출력은 아래와 같고 버튼 클릭 시에 모두 잘 동작한다. 

UnityEvent와 UnityAction에 대한 이러한 이해를 기반으로 Unity Official Tutorial 에 나와있는 EventManager Tutorial를 살펴보면 이해가 훨씬 쉽다.

 


ref : http://rapapa.net/?p=2936



반응형
반응형
씬을 비동기 로딩하면서 progressbar 로 상태를 표시하고 싶을때 allowSceneActivation = false  로 

로딩할 씬이 실제 활성화 될때까지 기다리게 할 수 있고  AsyncOperation.progress 값이 0.9 가 될때

allowSceneActivation = true 로 변경하게되면 isDone 이 true 로 변경되며  AsyncOperation.progress 또한

1.0f 로 되어 비동기 로딩처리를 할 수 있다






Allow scenes to be activated as soon as it is ready.

When used in combination with LoadLevelAsync & LoadLevelAdditiveAsync it allows you to delay the actual activation of the scene. (And unloading of the previous scene).

When allowSceneActivation is set to false then progress is stopped at 0.9. The isDone is then maintained at false. When allowSceneActivation is set to true isDone can complete.


ref : https://docs.unity3d.com/kr/current/ScriptReference/AsyncOperation-allowSceneActivation.html

반응형
반응형

//ExecuteInEditMode : 스크립트가 에디터모드에서 동작하도록 설정합니다.

//RequireComponent 속성은 요구되는 의존 컴포넌트를 자동으로 추가해줍니다.

[ExecuteInEditMode, RequireComponent(typeof(CanvasGroup))]

public class UI___Bar : MonoBehaviour 

{

}



ExecuteInEditMode


Description

스크립트가 에디터모드에서 동작하도록 설정합니다.

기본 설정으로, 스크립트 컴포넌트는 플레이 모드에서만 동작하도록 설정되어 있습니다. 이 어트리뷰트(attribute)를 추가 하면, 각 스크립트 컴포넌트들 역시 플레이모드가 아닌 에디터 모드에서 해당 콜백 함수를 수행할 수 있습니다.

The functions are not called constantly like they are in play mode.
Update is only called when something in the scene changed.
OnGUI is called when the Game View recieves an Event.
- 씬뷰 또는 게임뷰에서 repaint호출이 있을 때 마다 OnRenderObject 와 또다른 렌더링 콜백 함수들이 호출됩니다.

using UnityEngine;
using System.Collections;

[ExecuteInEditMode] public class ExampleClass : MonoBehaviour { public Transform target; void Update() { if (target) transform.LookAt(target); } }


RequireComponent


Description

RequireComponent 속성은 요구되는 의존 컴포넌트를 자동으로 추가해줍니다.

RequireComponent를 사용하는 스크립트를 추가하면, 요구되는 컴포너트가 자동으로 해당 게임오브젝트에 추가됩니다. 설정 오류를 피하는 데 유용합니다. 예를 들어, 리지드 바디가 요구되는 스크립트가, 항상 같은 게임오브젝트에 첨부되는 경우. RequireComponent를 사용하면 이 작업이 자동으로 이루어 지기 때문에, 설정에 대한 실수를 할 염려가 없습니다. Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject. Existing instances of the component whose GameObject lacks the new dependencies will not have those dependencies automatically added.

using UnityEngine;

// PlayerScript requires the GameObject to have a Rigidbody component [RequireComponent (typeof (Rigidbody))] public class PlayerScript : MonoBehaviour { Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { rb.AddForce(Vector3.up); } }



ref : https://docs.unity3d.com/kr/530/ScriptReference/ExecuteInEditMode.html

ref : https://docs.unity3d.com/kr/530/ScriptReference/RequireComponent.html






반응형
반응형

avatar image
0
Question by martchz · '15년 Feb월 25일 AM 06시 19분 · inputsubmit

UnityException: Input Button Submit is not setup.

Hello, everyone!

Why does Unity want me to set up Input Button "Submit", although I don't actually use it? It started after I removed all default inputs, save those that I use in my game. Does Unity use some of them in some behind the curtain processes?

Thanks in advance!

-Martch

1 Reply

 · Add your reply
avatar image
6
Best Answer

Answer by goliathmb 

If you are using the new UI, there is typically an EventSystem object in the scene. It has a component called the StandAloneInputModule that has a Submit button specified by default in its setting.




https://answers.unity.com/questions/909138/unityexception-input-button-submit-is-not-setup.html







Unity를 사용하다보면, 갑자기 이런 에러가 런타임에 발생하는 경우가 있다.


그리고 이 녀석을 클릭하면, Inspector에서 다음과 같은 것을 볼 수 있다.


Standalone Input Module이라는 것이 있는데, 자세히 보면 Submit Button이라는 게 있다.

아까 에러 메시지에서 "Input Button Submit is not setup"이라고 했는데,

그러면 "Submit"이라는 녀석이 설정 안 된 것이 아닐까?


[Edit> Project Setting> Input] 메뉴로 들어가면, 상태가 어떤지 확인할 수 있다.

아하! 과연 Submit이라는 이름의 버튼이 없다.

결국 이 문제는 Submit 버튼을 정의하지 않아서 생긴 것이다.


따라서 적당히 Submit, Cancel 버튼을 만들어주면 문제는 사라진다.


실행해보면 더 이상 문제가 발생하지 않음을 알 수 있다.



http://hdnua.tistory.com/38

반응형
반응형

NavMeshAgent and collision

Hey guys, im new here, so sorry for stupid question :)

I am using NavMeshAgent for my player character and wanted to make so that when player is close enough to an enemy, enemy starts to attack him.

I was trying to use an internal to enemy unit collider (screenshot), but OnCollisionEnter/OnTriggerEnter events do not fire.

What am i doing wrong?

  1. public class Creature : MonoBehaviour
  2. {
  3. void OnTriggerEnter(Collider other) {
  4. Debug.Log ("yyy " + other.gameObject.name);
  5. }
  6. void OnCollisionEnter(Collision collision) {
  7. Debug.Log ("xxx " + collision.other.name);
  8. }
  9. }

alt text






You should attach a Rigidbody (set Kinematic on) and a collider on your navmesh agent, and you will receive OnTrigger callbacks.



https://answers.unity.com/questions/1213909/navmeshagent-and-collision.html

반응형
반응형

AnimationState.normalizedTime


설명

애니메이션의 표준화(Normalized)된 시간.

1은 애니메이션의 끝을 의미합니다. 0.5는 애니메이션의 중간점을 의미합니다.

JavaScript
// 애니메이션의 중간지점으로 빨리감습니다.
animation["Walk"].normalizedTime = 0.5;



http://www.devkorea.co.kr/reference/Documentation/ScriptReference/AnimationState-normalizedTime.html

반응형
반응형

EventSystem.IsPointerOverGameObject

public bool IsPointerOverGameObject ();
public bool IsPointerOverGameObject (int pointerId);

Parameters

pointerIdPointer (touch / mouse) ID.

Description

Is the pointer with the given ID over an EventSystem object?

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class MouseExample : MonoBehaviour { void Update() { // Check if the left mouse button was clicked if (Input.GetMouseButtonDown(0)) { // Check if the mouse was clicked over a UI element if (EventSystem.current.IsPointerOverGameObject()) { Debug.Log("Clicked on the UI"); } } } }
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class TouchExample : MonoBehaviour { void Update() { // Check if there is a touch if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { // Check if finger is over a UI element if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { Debug.Log("Touched the UI"); } } } }

If you use IsPointerOverGameObject() without a parameter, it points to the "left mouse button" (pointerId = -1); therefore when you use IsPointerOverGameObject for touch, you should consider passing a pointerId to it.

Note that for touch, IsPointerOverGameObject should be used with OnMouseDown() or Input.GetMouseButtonDown(0) or Input.GetTouch(0).phase == TouchPhase.Began.



매개 변수없이 IsPointerOverGameObject()를 사용하면 "마우스 왼쪽 버튼"(pointerId = -1)을 가리 킵니다. 따라서 touch에 IsPointerOverGameObject를 사용할 때는 pointerId를 전달하는 것을 고려해야합니다.


touch의 경우 IsPointerOverGameObject는 OnMouseDown () 또는 Input.GetMouseButtonDown (0) 또는 Input.GetTouch (0) .phase == TouchPhase.Began과 함께 사용해야합니다.





오버로드는 다음처럼 정의되어있다



        //

        // 요약:

        //     ///

        //     Is the pointer with the given ID over an EventSystem object?

        //     ///

        //

        // 매개 변수:

        //   pointerId:

        //     Pointer (touch / mouse) ID.

        public bool IsPointerOverGameObject(int pointerId);

        //

        // 요약:

        //     ///

        //     Is the pointer with the given ID over an EventSystem object?

        //     ///

        //

        // 매개 변수:

        //   pointerId:

        //     Pointer (touch / mouse) ID.

        public bool IsPointerOverGameObject();


반응형

'게임엔진(GameEngine) > Unity3D' 카테고리의 다른 글

NavMeshAgent and collision  (0) 2018.01.14
AnimationState.normalizedTime  (0) 2018.01.14
Important lightmap setting  (0) 2018.01.06
Unity3D - 최적화를 위한 CombineMesh  (0) 2018.01.06
Material doesn't have stencil properties  (1) 2017.12.29
반응형

if Lightmap size is more bigger than previous it, you should check following options.



Lightmap settings

Property:Function:
Scale in LightmapThis value specifies the relative size of the object’s UVs within a lightmap. A value of 0 will result in the object not being lightmapped, but still contribute to lighting other objects in the scene. A value greater than 1.0 increases the number of pixels (ie, the lightmap resolution) used for this object while a value less than 1.0 decreases it. You can use this property to optimise lightmaps so that important and detailed areas are more accurately lit. For example: an isolated building with flat, dark walls will use a low lightmap scale (less than 1.0) while a collection of colourful motorcycles displayed close together warrant a high scale value.
Prioritize illuminationCheck this box to tell Unity to always include this object in lighting calculations. Useful for objects that are strongly emissive to make sure that other objects will be illuminated by this object.
Lightmap ParametersAllows you to choose or create a set of Lightmap Parameters for the this object.


file:///F:/Program%20Files/Unity/Editor/Data/Documentation/en/Manual/class-MeshRenderer.html


반응형
반응형

클라이언트 성능 최적화에서 고려해볼만한 것입니다.

하나의 Material을 공유하는 MeshFilter - MeshRenderer 인 GameObject들을 몰아놓고, CombineMesh를 

하면 DrawCall이 획기적으로 줄어들어서 성능이 많이 올라가네요.


바로 Merge 하는 함수 보여드릴께요.


public void Merge()

{

MeshFilter meshFilter = GetComponent<MeshFilter>();

meshFilter.mesh.Clear();

                             

MeshFilter [] meshFilters = GetComponentsInChildren<MeshFilter>( true );

transform.GetComponent<MeshRenderer>().material = 

      meshFilters[0].renderer.sharedMaterial;     

              

CombineInstance[] combine = new CombineInstance[meshFilters.Length-1];

              

int i = 0;

int ci = 0;

while ( i < meshFilters.Length )

{

if( meshFilter != meshFilters[i] )

{

combine[ci].mesh = meshFilters[i].sharedMesh;

combine[ci].transform = meshFilters[i].transform.localToWorldMatrix;

++ci;

}

meshFilters[i].gameObject.active = false;//.renderer.enabled = false;

i++;

}          

meshFilter.mesh.CombineMeshes( combine );

transform.gameObject.active = true;

 

transform.gameObject.GetComponent<MeshCollider>().sharedMesh =

transform.gameObject.GetComponent<MeshFilter>().mesh;        

}

Unity3d에서 소개한 사용 방법과는 조금 다른데요. Unity3D에서는 CombineMeshes를 호출 하기 전에 mesh를 New 하는 과정이 있는데, 제 코드에서는 Merge할 때 new Mesh 하지 않고, 기존 MeshFilter의 Mesh의 Clear() 함수를 해주고 그대로 재 사용 했습니다. Merge 할 때 마다 new Mesh 해버리면 VBO가 계속 올라가고 줄어들지 않는 현상이 생겨 버리더군요. 자원 관리자에서 메모리를 봐도 상당히 많은 양의 메모리가 지속적으로 증가하는 것을 확인 할 수 있었습니다. 언제나 그렇듯 이유는 잘 모르겠구요.


이상! 매트리얼을 공유하는 Mesh들이 많은 경우 효과 만빵인 최적화 방법이었습니다.


http://drago7.tistory.com/89


반응형
반응형

Shader error: Material doesn't have stencil properties ??

This is a new shader error for us with Unity 5:

Material doesn't have stencil properties

What is causing this? We are using a stencil buffer in the shader but AFAIK there is nothing else in the Unity docs that talk about a stencil property.



저런 에러(워닝)가 뜨면 아래 코드를 붙여넣으면 된다



(answering my own question)

There seems to be a magic property called _Stencil, which is supposed to be used for the unique stencil buffer id.

_Stencil ("Stencil Ref", Float) = 0

in full ...

  1. // these six unused properties are required when a shader
  2. // is used in the UI system, or you get a warning.
  3. // look to UI-Default.shader to see these.
  4. _StencilComp ("Stencil Comparison", Float) = 8
  5. _Stencil ("Stencil ID", Float) = 0
  6. _StencilOp ("Stencil Operation", Float) = 0
  7. _StencilWriteMask ("Stencil Write Mask", Float) = 255
  8. _StencilReadMask ("Stencil Read Mask", Float) = 255
  9. _ColorMask ("Color Mask", Float) = 15
  10. // see for example
  11. // http://answers.unity3d.com/questions/980924/ui-mask-with-shader.html

So I'm using the UI-default shader as a starting point for my sprite shader, and if I have the _ColorMask property my sprite doesn't render at all. Removing the property allows the sprite to render but then it doesn't clip properly. Even if I remove the code where the color mask is being used, just having the property still breaks the shader.

I would recommend using the Sprites-Default or Sprites-Diffuse shader as a basis - why use UI-default? Without seeing your code, can't really suggest anything else

Small note: If you have spaces in your shader name, this does not seem, to work.


반응형
반응형

Unity 2017.3 is here

, 12월 19, 2017

sdfsdf

We’re excited to share all the great new and improved features available today with Unity 2017.3. Before drilling down into the details, though, we wanted to look back at Unity 2017. (If you can’t wait, just jump straight to the What’s new section below.)

With the new Unity 2017 cycle, we doubled down on our effort to help artists, designers and developers create and collaborate more efficiently. Powerful visual tools like Timeline, Cinemachine and Unity FBX Exporter free artists to do more.

We continued to improve graphics quality and runtime performance to help you stay ahead of the curve on the latest emerging platforms (desktop, console, mobile, VR, AR, smart TVs) and to take advantage of the latest GPU and native Graphics APIs. A great example of this is the award-winning Adam demo-film series.

Other features, like the updated 2D tools and Unity Teams, help you get better results, faster. Finally, we’ve given you new ways to use powerful data (in the Ads, IAP and Live-Ops Analytics solutions) to optimize game performance in real-time and maximize your revenue.

Unity 2017.1, 2017.2 and 2017.3 delivered many key features supporting these goals. Here’s a summarized recap:

We’re also excited to share some of the Unity 2017.x productions released or in progress:

 

Oats Studios / ADAM: The Mirror & Episode 3

Spiraloid / Nanite Fulcrum
KO_OP / GNOG

Baobab Studio / Asteroid!

EpicHouse Studios / Phased

Cybernetic Walrus / Antigraviator

Rebel Twin / Dragons Hill 2

Slow Bros / Harold Halibut

WITHIN / Life of Us

Seriously / Best Fiends

Monomi Park / Slime Rancher

 Videogyan / TooToo Boy

 

And finally before jumping to 2017.3 details, check out this highlight video of Unity 2017.x titles and some of the new & improved features:

What’s new in Unity 2017.3

As the year comes to an end, we are happy to announce that Unity 2017.3, the final release in our 2017 cycle, is now available. 2017.3 introduces several new features and improvements across the board for both artists and developers, and we’re particularly excited about sharing our improved toolset for creating interactive 360-video experiences.

We’re finishing 2017 strong with a huge change log of new features, including the following highlights:

Panoramic 360/180 video

We are particularly excited to bring you improvements to panoramic 360/180 and 2D/3D video workflowsYou can now easily bring in various styles of 2D or 3D video in Unity and play it back on the Skybox to create 360-video experiences targeting standalone, mobile and XR runtimes.

Particle System improvements

Improvements include new Unlit and Surface particle shaders and ribbonized particle trails. These allow particles to be connected based on their age. Since each point on these ribbonized trails is represented by a particle, they can be animated, for example, by using them in conjunction with the Noise Module.

Script compilation – User-defined managed assemblies

You will be able to define your own managed assemblies based on scripts inside a folder. By splitting your project’s scripts into multiple assemblies, script compilation times in the editor can be greatly reduced for large projects. 

Managed Memory Profiler support
You can now take advantage of Mono/.NET 2.0 support for the APIs required to take managed memory snapshots. This makes it possible to take memory snapshots directly inside the editor.

The updated Crunch Library

The Crunch Library can now compress DXT textures up to 2.5 times faster, while providing about 10% better compression ratio. But more importantly, the updated library is now capable of compressing ETC_RGB4 and ETC2_RGBA8 textures, which makes it possible to use Crunch compression on iOS and Android devices.

Graphics improvements

There is now support for HDR compressed lightmaps (BC6H) on PC, Xbox One and PlayStation 4. We also made a number of GPU instancing improvements, and we’re adding Dynamic Resolution as an engine feature debuting on the Xbox One platform with other platforms to follow later.

Lighting improvements

We are introducing Lighting modes for the Progressive Lightmapper (Baked Indirect, Shadowmask and Subtractive), LOD support with realtime probes providing a more intuitive workflow, and HDR encoding support for baked lightmaps for higher visual quality.

VR device info

To help you optimize VR experiences, you can now capture VR-device refresh rate, dimensions, aspect ratio, HMD-tracking and controller-tracking as part of device info and device status events.

Physics

Improvements include cloth self-collision and inter-collision technology and improved constraint painting.

Animation

We are introducing Playable scheduling, which allows you to prefetch the data before it is actually played. The first implementation affects AudioClipPlayables, but in the future, the scheduling will be used by other assets: audio, video and timeline.  We added support for integer and enum animation parameters defined within an Animator Controller. This enables you to access and assign values from scripts giving you even better control over the flow of the animation state machine. We are also introducing a New “2D” mode button in the animation Preview window. Finally, it is now possible to zoom, frame and autofit in the Animator window!

Xbox One X Support

We added support for the new Xbox One X console from Microsoft. Use Quality Settings to enable support for 4K HDR rendering, or use the extra power in other ways such as improving framerate or increasing graphical fidelity. Xbox One X support is available in all 2017.x versions of Unity.

Xiaomi: easily publish Android apps into China (Xiaomi) through the editor.

In November 2016, Unity and Xiaomi announced a partnership to help developers bring games to Xiaomi’s 200 million customers in China, the largest Android store in this region. Since then a number of early-adopter games have gone live on Xiaomi’s store. At the end of November, the push-to-store service offering for Xiaomi’s brand-new portal went live! To get started, check out the FAQ and getting started guides on this site.

Standard Events

Standard Events is now officially out of beta, and you can access it directly from the Unity Editor in 2017.3. We’re also introducing funnel templates, which together with Standard Events, allow you to create common funnels that can reveal key insights with just a few clicks.

Editor/engine

Script compilation – Assembly definition files

Unity automatically defines how scripts compile to managed assemblies. Typically, compilation times in the Unity Editor for iterative script changes increase as you add more scripts to the Project increasing compilation time.

Now, you can use an assembly definition file to define your own managed assemblies based on the scripts in a folder. Separating project scripts into multiple assemblies with well-defined dependencies ensures that only the required assemblies are rebuilt when you make changes in a script. This reduces compilation times and is particularly useful for large projects.

Each managed assembly can be thought of as a single library within the Unity Project.

The figure above illustrates how to split the project scripts into several assemblies. Because only the scripts are changed in the Main.dll, none of the other assemblies are recompiled. And since the Main.dll contains fewer scripts, it compiles faster than the Assembly-CSharp.dll.

Similarly, script changes in only Stuff.dll cause Main.dll and Stuff.dll to recompile.

You can read more about how to use assembly definition files in our feature preview blog post.

Memory Profiler support for Mono .NET 2.0

Back in 2015, we released an experimental managed memory profiler with support for IL2CPP. The memory profiler started as a Unity Hackweek project and was since released on BitBucket as an open source project. See the memory profiler project page on Bitbucket for details and a demo video.

We’ve added Mono/.NET 2.0 support for the APIs required by the memory profiler to take managed memory snapshots. This makes it possible to take memory snapshots inside in the editor.


Transform Tool

The Transform Tool is a multitool, that contains the functionality of the standard three: Move, Rotate and Scale tools. The Transform Tool is not meant to replace the three standard tools, but rather, to provide a tool for situations where you would want all of the three tools present without having to switch back and forth between them.

World gizmo

With the pivot rotation set to “Global” mode, you can translate and rotate the GameObject along the global axes.

Axis translation, Plane translation.

 

Axis rotation, Screen Space rotation, Free rotation.

 

Global scaling.

 

Local gizmo

When the pivot rotation is in “Local” mode, you can also scale along local axes.

Local axis scaling.

 

Screen Space Gizmo

If you keep the “SHIFT” key pressed, the gizmo enters Screen Space mode.

In this mode, you can translate and rotate in screen space.

Axis translation, Plane translation, Axis rotation and Global scaling.

 

Snapping

When you keep the “CTRL” (Win) or “Command” (OSX) key pressed, the unit snapping is activated for:

  • Axes translations
  • Plane translations
  • Axes rotations
  • Axes scaling
  • Global scaling

 

Plane translation, Axis translation, Global scaling, Axis rotation.

Vertex Snapping

When you keep the “V” key pressed, the gizmos enter Vertex Snapping mode.

This enables you to translate your gameobject so one of its vertexes is placed on the vertex of another object.


Cinemachine camera system

Cinemachine, our camera system for in-game cameras, cinematics, cutscenes, film pre-visualization and virtual cinematography, also includes a number of new features and improvements.

Improvements include:

  • Support for the Post-Processing Stack v2 beta
  • A new Collider implementation that replaces curb feelers with a clever camera-repositioning algorithm, which preserves camera height or distance from target
  • A New Framing Transposer that respects composition and framing rules by moving the camera without rotating it
  • The New Cinemachine MixingCamera, which drives a continuous blend of up to 8 virtual cameras from timeline or game logic. You can use it to create complex rigs with custom blends and expose them as ordinary vcams.

Other new features and improvements include dolly cam behavior and POV, a 1st-person shooter type, aim component, and much more.

For a complete list of all the features and improvements, check out our official forum thread.

The Cinemachine feature set is distributed via the Asset Store. Download the latest version to your project.

Graphics

Progressive Lightmapper (preview)

Lighting modes support

In Unity, it is possible to control lighting pre-computation and composition in order to achieve a given effect by assigning various modes to a Light (Realtime, Mixed and Baked). Using Mixed mode significantly reduces realtime shadow distance increasing performance. Higher visual fidelity can also be achieved as far distance shadows are supported along with realtime specular highlights.

In Unity 2017.3, you can do the same thing with the Progressive Lightmapper choosing from among the following Lighting modes:

In Baked Indirect mode, Mixed lights behave like realtime dynamic lights with additional indirect lighting sampled from baked lightmaps and light probes. Effects like fog can be used passed realtime shadow distance where shadowing would otherwise be missing.

In Shadowmask mode, Mixed lights are realtime, and shadows cast from static objects are baked into a shadowmask texture and into light probes. This allows you to render shadows in the distance drastically reducing the amount of rendered shadow casters based on the Shadowmask Mode from the quality settings.

In Subtractive mode, direct lighting is baked into the lightmaps, and static objects will not have specular or glossy highlights from mixed lights. Dynamic objects will be lit at realtime and receive precomputed shadows from static objects via light probes. The main directional light allows dynamic objects to cast a subtractive realtime shadow on static objects.

To try out the lighting modes in the Progressive Lightmapper, make sure that you have a Mixed Light in your scene and then, in the Lighting Window, select a Lighting Mode.


Light LODs with real-time probes and baked lightmaps

 We’ve added the ability to generate lighting for level of detail (LOD) objects with real-time light probes in addition to baked lightmaps, offering a more intuitive workflow for users to author their lighting. The LOD allows you to have meshes in lower complexity when the camera is far away and higher complexity when the camera is closer. That way you can reduce the level of computation when rendering faraway objects. When you use Unity’s LOD system in a scene with baked lighting and Realtime GI, the system lights the most detailed model out of the LOD Group as if it is a regular static model. It uses lightmaps for the direct and indirect lighting, and separate lightmaps for Realtime GI.

However, for lower LODs in an LOD Group, you can only combine baked lightmaps with Realtime GI from Light Probes or Light Probe Proxy Volumes, which you must place around the LOD Group.

To allow the baking system to produce real-time or baked lightmaps in 2017.3, simply check that Lightmap Static is enabled in the Renderer component of the relevant GameObject.

This animation shows how realtime ambient color affects the Realtime GI used by lower level LODs:


HDR support in the lightmap pipeline

We’ve added support for HDR compressed lightmaps (BC6H) on PC, Xbox One and PlayStation 4 for achieving even better quality visuals. The advantage of using High Quality lightmaps is that they don’t encode lightmap values with RGBM, but use a 16-bit floating point value instead. As a result, the supported range goes from 0 to 65504. The BC6H format is also superior to DXT5 + RGBM combination as it doesn’t produce any of the banding artifacts associated with RGBM encoding and color artifacts coming from DXT compression. Shaders that need to sample HDR lightmaps are a few ALU instructions shorter because there is no need to decode the sampled values, and the BC6H format has the same GPU memory requirements as DXT5.

The HDR is easily enabled by setting the Lightmap Encoding option in the Player Settings to High Quality.

Choosing High Quality will enable HDR lightmap support, whereas Normal Quality will switch to RGBM encoding.

When lightmap Compression is enabled in the Lighting Window, the lightmaps will be compressed using the BC6H compression format. 

GPU instancing improvements

GPU Instancing was introduced in 5.6 to reduce the number of draw calls used per scene by rendering multiple copies of the same Mesh simultaneously, and thus significantly improving rendering performance.

There are a number of improvements to GPU instancing, including Per-instance properties which are now packed into a structure data type with instancing constant buffer containing only one array of such structures.

For most platforms, the instancing array sizes are now calculated automatically and no longer need to be specified by user (maximum allowed constant buffer size/size of the above-mentioned structure type). Instancing batch sizes are therefore improved on OpenGL and Metal, and instancing shader variants compile much faster and potentially cost less in terms of CPU-GPU data bandwidth.

Crunch compression library update

The updated Crunch library, introduced in Unity 2017.3, can compress DXT textures up to 2.5 times faster with a 10% improvement in compression ratio. More importantly, the updated library is now capable of compressing ETC_RGB4 and ETC2_RGBA8 textures, which makes it possible to use Crunch compression on iOS and Android devices.

Crunch is a lossy texture compression format, which is normally used on top of DXT texture compression. Crunch compression helps to reduce the size of the textures in order to use less disk space and to speed up downloads. The original Crunch compression library, developed by Richard Geldreich, is available on GitHub. Support for Crunch texture format was first added in Unity 5.3 and in Unity 2017.3, we are now introducing an updated version of the Crunch compression library.

Textures compressed with Crunch are first decompressed to DXT and then uploaded to the GPU at runtime. Crunched textures not only use less space, but they can be also decompressed really fast. This makes the Crunch format very efficient for distributing textures. At the same time, Crunched textures can take quite a lot of time to compress, which is a major drawback when using Crunch (for a big project, compression of all the textures into Crunch format can take several hours in the Unity Editor).

This should help you reduce the build sizes of your mobile games, and thus make it easier to comply with App Store over-the-air size limitations, ultimately letting you reach a wider audience with your content.

To use Crunch compression on Android, iOS and tvOS platforms, you simply select either the “RGB Crunched ETC” or “RGBA Crunched ETC2” format for your textures in the Inspector window. If you enable the “Use Crunch Compression” option in the Default tab, all the textures on the Android platform will be compressed with ETC Crunch by default.

Below you can see examples of textures compressed with Crunch using default quality settings. Note that the artifacts on the final textures are introduced both by Crunch compression and selected GPU texture format (DXT or ETC).

Original image
24 bits/pixel

DXT
4 bits/pixel

Crunched DXT
1.24 bits/pixel

Original image
24 bits/pixel

ETC
4 bits/pixel

Crunched ETC
1.33 bits/pixel

If you are interested in knowing more about the updated Crunch texture compression library, visit this blog post, which includes more examples of size and performance comparison.

Dynamic Resolution debuting on Xbox One platform

As its name suggests, Dynamic Resolution refers to dynamically scaling some or all of the render targets to reduce workload on the GPU. Dynamic Resolution can be triggered automatically when performance data indicates that the game is about to drop frames due to being GPU bound. In such a case, gradually scaling down the resolution can help maintain a solid frame rate. It can also be triggered manually if the user is about to experience a particularly GPU intensive part of gameplay. If scaled gradually, Dynamic Resolution can be virtually unnoticeable.

360 Video Player

The new video player introduced earlier this year, made it possible to use 360 videos and make them truly interactive by adding CG objects, ambisonic audio, visual effects, and more.

In 2017.3, you can now bring a 2D or 3D 360-video into Unity and play it back on the Skybox to create standalone 360-video experiences targeting VR platforms.

Unity offers built-in support for both 180 and 360-degree videos in either an equirectangular layout (longitude and latitude) or a cubemap layout (6 frames).

Equirectangular 2D videos should have an aspect ratio of exactly 2:1 for 360-degree content, or 1:1 for 180-degree content.

Equirectangular 2D video

Cubemap 2D videos should have an aspect ratio of 1:6, 3:4, 4:3, or 6:1, depending on the face layout:

 

Cubemap 2D video

To use the panoramic video features in the Unity Editor, you must have access to panoramic video clips, or know how to author them. Check our documentation pages for a step-by-step guide on how to display any panoramic video in the Unity Editor.

Keep in mind that many desktop hardware video decoders are limited to 4K resolutions and mobile hardware video decoders are often limited to 2K or less, which affects the resolution of playback in real-time on those platforms.

ARCore SDK Preview 2 for Unity

Technical improvements introduced with the new developer preview include a C API for Android NDK, functionality to pause and resume AR sessions allowing users to pause and continue tracking after app is resumed, improved runtime efficiency and finally, improved trackable and anchor interface across anchor, plane finding, and point cloud. Learn more about ARCore Developer Preview

Vuforia 7 support

With Unity 2017.3 support for Vuforia 7, you can build cross-platform AR apps. Vuforia 7 introduces Model Targets, a new way to place digital content on specific objects using pre-exiting 3D models. Also new is Vuforia Ground Plane, a capability that allows you to place digital content on a horizontal surface such as a floor or table. Ground Plane will support an expanding range of iOS and Android devices, taking advantage of platform enablers such as ARKit where available. Learn more about Vuforia in Unity 2017.

Ground Plane (available for free) place digital content on floors or tables.Model Targets. Recognize a new class of objects based on their geometry used for example for placing AR content on top of industrial equipment, vehicles or home appliances.

 


OctaneRender for Unity now available from Otoy

We are excited to welcome OTOY’s path-traced GPU-accelerated render engine for the Unity Editor. OctaneRender for Unity is available for free, or at $20 or $60 for packages that unlock more GPUs and OctaneRender plugins for leading 3D authoring tools. Born on GPUs, OctaneRender is an unbiased render engine, tracing each ray of light in a scene with physics-grade precision to deliver unrivaled photorealism in CG and VFX. Octane Render for Unity works with Unity 2017.1 and above.  Learn more about OctaneRender for Unity.

Made with Unity scene rendered with OctaneRender for Unity available on the Asset Store for free. 

 

2017.3 Particle system

Speed Modifier

The Velocity over Lifetime module now contains a new curve, which allows particle speeds to be controlled over the duration of a particle’s lifetime. This makes it possible to change the speed of particles without affecting the direction they are traveling in. It also includes support for negative speeds, which is useful for creating gravity/vortex effects.


Standard Particle Shaders

We are releasing surface and unlit shaders for use with particles. They provide all the core particle functionality that you would expect, via a similar interface to our existing Standard Shader. It is now easy to configure blend modes, alpha testing thresholds, soft particle distances, and many more features. Support for blended flipbooks and distortion effects is also built in. The surface shader also makes it easy to support Normal Mapping and PBR lighting.


Ribbonized Particle Trails

There is a new option in the Trails Module called Ribbon Mode, which allows particles to be connected based on their age, allowing you to avoid each particle leaving trails behind it. Because each point on the trail is represented by a particle, it is possible to use this mode to create animated trails, for example, by using it in conjunction with the Noise Module.

 


Other Particle System improvements

When using meshes in the Shape Module, it is now possible to use meshes whose primitive type is Line or LineStrip. This makes it easy to spawn particles along lines, instead of only on the surface of a mesh.

Unity has added support for 32-bit meshes in Unity 2017.3, finally dropping the constraint for meshes to have 65,536 or fewer vertices. This support has been fully integrated for Particle Systems, meaning you can spawn on the surface of these new large meshes. Although it is likely to have high-performance costs, you can now render particle meshes with 32-bit indices as well.

We’ve also made some improvements to the editor in order to improve your workflow when authoring effects:

  • The debug checkboxes have been moved from the Inspector to the Scene View Overlay to make them more accessible (Resimulate and Show Bounds).
  • There is a new dropdown menu in the Scene View Overlay called “Simulate Layers,” which you can use to preview all looping effects, rather than only the selected ones. Use the Layer Mask to decide which effects to preview.
  • The Scene View FX dropdown menu has a new option for rendering Particle Systems. This allows you to show/hide Particle Systems as a way of decluttering your Scene view.


Cloth improvements

There are a number of improvements to Cloth physics, including better in-editor tools for authoring Cloth with more of PhysX internals exposed. This gives you more options for collisions, self-collisions, etc.

You can now paint constraints on to the cloth using a brush-based method and update. You can also enable intercollision to make different cloth objects collide.

You can find more information on how to get started using the cloth improvements here.

 

Platforms

Facebook segmented upload feature

There is now support for Facebook’s new segmented upload feature for Game Room. Previously, a single file with a max size of around 250MB was uploaded to Facebook. Now, only those parts that were changed are uploaded (divided into segments of 10 MB).

Unity has supported Facebook’s gaming desktop app, Game Room, since Unity 5.6. Supporting the Windows-native client allows players to experience both web games and native games built exclusively for the platform. Learn more about how to reach up to two billion users on Facebook.


XR

Oculus Dash Depth Support

Witch Oculus introducing its new Oculus Dash menu and UI in it’s latest Rift’s update, we have included Oculus Dash Depth support and exposed camera-depth information, so that Oculus Dash can partially occlude world-space overlays.

Terrain Trees for VR

We’ve added the possibility to use Unity’s terrain trees in VR experiences. Check the documentation for details on populating your world with trees.

Stereo Instancing for PSVR

In 2017.2, we delivered Stereo Instancing for VR PC based platforms; we’re now expanding to PSVR. Stereo Instancing is an exciting rendering advancement that unlocks hardware optimizations for rendering stereo images. This means that developers will be able to do more while maintaining a smooth framerate

Deprecation of platforms

In order to focus our efforts latest versions of DirectX, Unity 2017.3 (both the Unity Editor and the Standalone player) will no longer support DirectX 9 (which was originally released in 2002). You can read more about how to continue to support Windows XP on our blog.

Finally, as originally announced in October 2017, Unity will no longer include Samsung Tizen and SmartTV from version 2017.3. However, Unity stills provides 12 months of support, including patches and security updates starting from the release of 2017.2 (October 12 2017). To get the latest info on Tizen and SmartTV for Unity, visit the partner page for Samsung or contact Samsung directly at support@samsungdevelopers.com.

Unity Teams

Unity Teams features are now available for purchase, so teams of all sizes can save, share and sync their projects easily within Unity. Unity Teams Basic is free and is great for small teams that are just getting started. More features and capacity are available with Unity Teams Advanced, which starts at at $9 per month. You can add more team members, cloud storage, or more automated builds, paying only for what you need. Details at unity3d.com/teams.

If you’ve been using Unity Teams features (Collaborate, Cloud Build), you can upgrade to a paid subscription by January 9, 2018 to prevent interruption in service. Furthermore, it’s a great time to upgrade to Plus and Pro. All Unity Plus and Pro subscriptions that are active as of January 31, 2018, are entitled to Unity Teams Advanced at no additional cost. Learn more about this offer.

Unity Analytics

Standard Events

Unity Analytics Standard Events helps track users’ behavior and answer critical questions specific to your game. They are a curated set of events focused on five different areas of user experience: OnboardingApplication, Progression, Engagement, and Monetization. With 2017.3, Standard Events are now built right into Unity.

Along with this release, we are excited to introduce you to funnel templates.

Together with Standard Events, funnel templates allow you to create common funnels that can reveal key insights with just a few clicks.

Learn more about Standard Events.

LiveStream

For Plus and Pro users, LiveStream now displays instantaneous metrics broken down over the preceding 30 minutes. IAP revenue is displayed when verified, making income reporting more accurate. There are also options for filtering New Installs, Sessions, and Verified IAP Revenue in the Activity view.

Learn more about LiveStream.

Release notes

As always, refer to the release notes for the full list of new features, improvements and fixes.

That’s all the new features of the last Unity release of the  year! Dive in and download Unity 2017.3 right here.


반응형
반응형

네비게이션 개요

이 섹션에서는 씬에 NavMesh(네비 메쉬)를 만들고 NavMesh Agent(네비 메쉬 에이전트)와 NavMesh Obstacle(네비 메쉬의 장애물), Off-Mesh Link(오프-메쉬 링크)를 만드는 방법에 대한 자세한 내용을 알려드립니다.






The Navigation System allows you to create characters which can navigate the game world. It gives your characters the ability to understand that they need to take stairs to reach second floor, or to jump to get over a ditch. The Unity NavMesh system consists of the following pieces:

  • NavMesh (short for Navigation Mesh) is a data structure which describes the walkable surfaces of the game world and allows to find path from one walkable location to another in the game world. The data structure is built, or baked, automatically from your level geometry.
  • NavMesh Agent component help you to create characters which avoid each other while moving towards their goal. Agents reason about the game world using the NavMesh and they know how to avoid each other as well as moving obstacles.
  • Off-Mesh Link component allows you to incorporate navigation shortcuts which cannot be represented using a walkable surface. For example, jumping over a ditch or a fence, or opening a door before walking through it, can be all described as Off-mesh links.
  • NavMesh Obstacle component allows you to describe moving obstacles the agents should avoid while navigating the world. A barrel or a crate controlled by the physics system is a good example of an obstacle. While the obstacle is moving the agents do their best to avoid it, but once the obstacle becomes stationary it will carve a hole in the navmesh so that the agents can change their paths to steer around it, or if the stationary obstacle is blocking the path way, the agents can find a different route.



귀찮으니 구글 번역(번역 상태가 살짝 이상하지만 직역?된걸 생각하면서 보면 이해할 수 있을 정도입니다)


네비게이션 시스템을 사용하면 게임 세계를 탐색 할 수있는 캐릭터를 만들 수 있습니다. 그것은 당신의 캐릭터에게 그들이 2 층에 도착하기 위해 계단을 잡거나 도랑을 뛰어 넘기 위해 뛰어 올라야 할 필요가 있음을 이해하는 능력을줍니다. Unity NavMesh 시스템은 다음과 같이 구성됩니다.

  • NavMesh (Navigation Mesh의 약자)는 게임 세계의 걷기 좋은 표면을 설명하고 게임 세계에서 걷기 좋은 곳에서 다른 곳으로가는 길을 찾을 수있는 데이터 구조입니다. 데이터 구조는 레벨 지오메트리에서 자동으로 빌드되거나 구워집니다.
  • NavMesh Agent 구성 요소는 목표를 향해 움직이는 동안 서로를 피하는 문자를 만들 수 있도록 도와줍니다. 요원들은 NavMesh를 사용하여 게임 세계에 대해 논하고 그들은 서로를 피하고 움직이는 장애물을 피하는 방법을 알고 있습니다.
  • Off-Mesh Link 구성 요소를 사용하면 걷기 쉬운 표면을 사용하여 표현할 수없는 탐색 바로 가기를 통합 할 수 있습니다. 예를 들어 도랑이나 담장을 뛰어 넘거나 걸어 가기 전에 문을 여는 것은 모두 오프 메쉬 링크라고 할 수 있습니다.
  • NavMesh 장애물 구성 요소를 사용하면 세계를 탐색하는 동안 에이전트가 피해야하는 움직이는 장애물을 설명 할 수 있습니다. 물리 시스템에 의해 제어되는 배럴 또는 상자는 장애물의 좋은 예입니다. 장애물이 움직이는 동안 요원이 그것을 피하기 위해 최선을 다하고 있지만 일단 장애물이 정지하면 navmesh에 구멍을 뚫어 요원이 경로를 변경하여 주변을 조종하거나 고정 된 장애물로 인해 경로가 차단되는 경우 에이전트는 다른 경로를 찾을 수 있습니다.




우선 네이게이션 만들어보기






네비게이션을 적용할 오브젝트를 모두 선택 합시다.








인스펙터 창에 오른쪽 상단에 보면 Static이라고 있습니다.


그 옆에 세모 단추가 있는데 눌러서 Navigation Static을 눌러줍시다.


※ 구역을 만들기 위해서 지형을 미리 올려두어 계산하게끔 해야되기 때문에 필요한 과정입니다.







유니티 메뉴창 - > Window -> Navigation을 누르시면 오른쪽에 네비게이션 관련 창이 나옵니다.


그 창에 상단을 보시면


Object | Bake | Areas 가 있는데요


Bake를 눌러줍시다. ( 나머지 2개는 신경 안써도 됩니다.)


그러면 이미지와 같은 화면이 나옵니다.




이것이 무엇을 뜻하냐면은


간단히 말해서 '길'로 설정할 범위를 정하라는 겁니다.




Agent Radius: 길로 만들 땅의 반 지름의 크기는 어느정도? ( 값 만큼 외각 여백 결정. )


Agent Height: 어느 높이까지 허용할 거냐? ( 최대 등산 각도. 계단 높이에 영향을 줌 )


Max Slope : 경사는 어느 지점까지 길로 허용할 거냐?


Step Height: : 어느 높이까지 길로 만들거냐? ( 계단 높이. )




모든 셋팅이 다 끝났으면 오른쪽 제일 하단 Bake를 눌러줍시다.






오브젝트 위에 하늘색으로 칠해진곳이 '길'로 허용된 범위 입니다.


캐릭터는 저 범위만 돌아다닐수 있습니다.







플레이어가 될 캐릭터를 맵 맘에 드는곳에 적당히 배치 합니다.







플레이어 캐릭터가 길찾기(Navigation) 수행을 하려면 한 가지 컴포넌트가 필요합니다.


Nav Mesh Agent라는 컴포넌트인데요.




플레이어 캐릭터를 선택한 상태로


유니티 메뉴를 보시면 Component -> Navigation -> Nav Mesh Agent를 누르면


컴포넌트가 하나 추가 됩니다.




터치한 부분까지 캐릭터를 이동시키기 위한 스크립트도 필요한데요.


미리 만들어서 넣어놓읍시다.





컴포넌트의 속성을 보면 여러가지 나와있는데요


Agent Size


- Radius: 충돌 범위( 가로 )


- Height: 충돌 범위( 세로 )


- Base Offset : 기본 출력




Steering


- Speed: 길찾기 이동 수행 스피드 ( 캐릭터 이동 속력 )


- Angular Speed: 회전 스피드 ( 캐릭터 회전 속력 )


- Acceleration: 가속력.


- Stopping Distance: 정지 거리.




※ 캐릭터에 네비 메쉬 에이전트( Nav Mesh Agent) 컴포넌트를 추가하면 기존에 있던


콜라이더(Collider)의 범위는 포함되지 않고, 네비 메쉬 에이전트의 범위로 체크 됩니다.






바로 스크립트를 작성합시다.


설명은 스크립트를 참고합시다.


using UnityEngine;

using System.Collections;

 

public class Nav : MonoBehaviour

{

    public Camera camera;   // 카메라 정보를 얻어오기 위한 변수.

    Animation Ani;          // 애니메이션을 실행 해주기 위한 애니메이션 변수.

    NavMeshAgent Navi;      // 네비게이션을 사용하기 위한 네비게이션 변수.

 

    void Awake()

    {

        Navi = GetComponent<NavMeshAgent>();    // 네비게이션에 대한 컴포넌트를 캐싱

        Ani  = GetComponent<Animation>();       // 애니메이션에 대한 컴포넌트를 캐싱

    }

 

    void Update()

    {

        PlayerTouchMove();  // 화면에 터치 했을 때 이동한다.

    }

 

    void PlayerTouchMove()

    {

        // 매계변수 - 0:왼쪽 1:오른쪽 2:휠

        if (Input.GetMouseButton(0))    // 마우스 왼쪽 버튼을 게속 누르고 있다면.

        {

            Ray ray = camera.ScreenPointToRay(Input.mousePosition);

            // 카메라가 바라보고있는 스크린에서 마우스 위치 정보를 ray에 저장.

            RaycastHit Hit;

            // 충돌에 대한 정보를 저장하기 위한 변수.

 

            // (마우스 위치정보, 충돌에 대하여 값을 담을 변수, 마우스 위치 지점까지 레이저를 얼마만큼의 길이로 쏠것인가?)

            if (Physics.Raycast(ray, out Hit, Mathf.Infinity)) 

            {

                Navi.SetDestination(Hit.point);

                // 매계변수의 위치까지 이동 시켜준다.

            }

        }

 

        // 네비게이션의 목표지점과 현재 캐릭터의 위치가 같으면 함수를 빠져나간다.

        // 쓸때없는 연산을 줄이기 위하여 사용.

        if (transform.position == Navi.destination) return;

        

        // 네비게이션 목표지점과 현재 캐릭터의 위치 사이의 거리를 구한다.

        float dis = Vector3.Distance(Navi.destination, transform.position);

 

        if (dis < 0.1) 

        {

            Ani.CrossFade("Idle");

            transform.position = Navi.destination;

 

            // 목표 지점까지의 거리가 0.1보다 작다면 캐릭터 애니메이션 Idle

            // 캐릭터의 현재 위치를 목표 지점과 완벽하게 일치 시킨다.

        }

        else

            Ani.CrossFade("Run2");

    }

}








Off Mesh Link 만들기






위 그림에서 바닥, 그리고 두 개의 큐브가 있고 이들을 Bake 한 네비게이션 메시들을 볼 수 있다.Off Mesh Link 는 위처럼 떨어져 있는 네비게이션 메시들끼리 연결해주는 개념으로, 두 가지 빙식이 있다.




먼저 첫 번째 방식을 알아보자. 첫 번째 방식은 Bake 시점에 네비게이션 메시들끼리의 높낮이 차이, 떨어진 거리의 차이로부터 연결을 생성하는 방식이다. 높낮이의 경우, 두 네비게이션 메시끼리의 높낮이 차이가 특정 값 이하인 경우 높은 네비게이션 메시에서 낮은 네비게이션 메시로 연결이 생성된다. 이를 직접 눈으로 확인해보자. 왼쪽 큐브를 선택한 후 Navigation Window 에서 다음처럼 설정해준다.






Drop Height 의 경우 상황에 맞게 적당한 값을 넣어준다. 이 상태로 Bake 를 하면 다음과 같은 연결이 생성됨을 확인할 수 있다.




이러한 연결이 생기면 해당 큐브 위의 물체가 바닥의 특정 목표점으로 이동할 수 있는 경로가 만들어진 것이다.




거리의 차이로부터 연결을 생성하는 것은 높낮이 차이의 그것과 크게 다르지 않다. 단지 Drop Height 대신 Jump Distance 가 사용된다는 차이가 있다. 위 상태에서 Jump Distance 에도 적당한 값을 넣어서 Bake 해보면 다음과 같은 결과를 얻을 수 있다.






이번엔 옆 큐브 쪽의 네비게이션 메시로 연결이 생성됐다.



이제 두 번째 방식을 알아보자. 두 번째 방식은 연결되길 원하는 두 지점을 직접 지정하는 방식으로, 컴포넌트를 이용하기 때문에 Bake 할 필요가 없다. 먼저 두 개의 게임 오브젝트를 만들고 연결되길 원하는 각 지점에 배치한다. 이제 또 다른 게임 오브젝트에 Off Mesh Link 컴포넌트를 추가하고 Start, End 에 방금의 오브젝트들을 연결해준다.






두 지점이 네비게이션 메시와 어느 정도 근접해 있어야 연결이 생성된다. 에디터 상에서 두 지점을 이리저리 움직여가며 연결을 만들어보자.





위와 같이 연결을 생성할 수 있다. 두 지점을 변경할 때마다 연결은 새로 갱신된다.







ref : https://docs.unity3d.com/kr/current/Manual/nav-NavigationSystem.html

ref : http://illusionbattle.tistory.com/214

ref : http://cacodemon.tistory.com/entry/Off-Mesh-Link

반응형
반응형

현재 유니티는 2017 버전인데 시기가 지나서 옵션들의 위치나 기능들이 보이고 안보이는것들이 자잘하게 있으나

개념상 도움이 될만한 슬라이드입니다





슬라이드 링크 : https://www.slideshare.net/illustor/devtree-lightmapping-unity521stday

반응형
반응형

Benefits and Costs

Although it is possible to simultaneously use Baked GI lighting and Precomputed Realtime GI, be wary that the performance cost of rendering both systems simultaneously is exactly the sum of them both. Not only do we have to store both sets of lightmaps in video memory, but we also pay the processing cost of decoding both in shaders.

The cases in which you may wish to choose one lighting method over another depend on the nature of your project and the performance capabilities of your intended hardware. For example, on mobile where video memory and processing power is more limited, it is likely that a Baked GI lighting approach would be more performant. On ‘standalone computers’ with dedicated graphics hardware, or recent games consoles, it is quite possible to use Precomputed Realtime GI or even to use both systems simultaneously.

The decision on which approach to take will have to be evaluated based on the nature of your particular project and desired target platform. Remember that when targeting a range of different hardware, that often it is the least performant which will determine which approach is needed.

Enabling Baked GI or Precomputed Realtime GI

By default, both Precomputed Realtime GI and Baked GI are enabled in Unity’s Lighting panel (Lighting>Scene). With both enabled, which technique is used can then be controlled by each light individually (Inspector>Light>Baking).

Using both Baked GI and Precomputed Realtime GI together in your scene can be detrimental to performance. A good practise is to ensure that only one system is used at a time, by disabling the other globally. This can be done by unchecking the box next to either Precomputed Realtime GI or Baked GI from Unity’s lighting panel (Lighting>Scene). Now only the checked option will be present in your scene, and any settings configured per-light will be overridden.

Per-Light Settings

The default baking mode for each light is ‘Realtime’. This means that the selected light(s) will still contribute direct light to your scene, with indirect light handled by Unity’s Precomputed Realtime GI system.

However, if the baking mode is set to ‘Baked’ then that light will contribute lighting solely to Unity’s Baked GI system. Both direct and indirect light from those lights selected will be ‘baked’ into lightmaps and cannot be changed during gameplay.




Point light with the per-light Baking mode set to ‘Realtime’.

Selecting the ‘Mixed’ baking mode, GameObjects marked as static will still include this light in their Baked GI lightmaps. However, unlike lights marked as ‘Baked’, Mixed lights will still contribute realtime, direct light to non-static GameObjects within your scene. This can be useful in cases where you are using lightmaps in your static environment, but you still want a character to use these same lights to cast realtime shadows onto lightmapped geometry.





Baked lighting

Baked Lights are Light components which have their Mode property set to Baked.

Use Baked mode for Lights used for local ambience, rather than fully featured Lights. Unity pre-calculates the illumination from these Lights before run time, and does not include them in any run-time lighting calculations. This means that there is no run-time overhead for baked Lights.

Unity bakes direct and indirect lighting from baked Lights into light maps (to illuminate static GameObjects) and Light Probes (to illuminate dynamic Light GameObjects). Baked Lights cannot emit specular lighting, even on dynamic GameObjects (see Wikipedia: Specular highlight for more information). Baked Lights do not change in response to actions taken by the player, or events which take place in the Scene. They are mainly useful for increasing brightness in dark areas without needing to adjust all of the lighting within a Scene.

Baked Lights are also the only Light type for which dynamic GameObjects cannot cast shadows on other dynamic GameObjects.

Advantages of baked lighting

  • High-quality shadows from statics GameObjects on statics GameObjects in the light map at no additional cost.

  • Offers indirect lighting.

  • All lighting for static GameObjects can be just one Texture fetched from the light map in the Shader.

Disadvantages of baked lighting

  • No real-time direct lighting (that is, no specular lighting effects).

  • No shadows from dynamic GameObjects on static GameObjects.

  • You only get low-resolution shadows from static GameObjects on dynamic GameObjects using Light Probes.

  • Increased memory requirements compared to real-time lighting for the light map texture set, because light maps need to be more detailed to contain direct lighting information.

Technical details

For baked Lights, Unity precomputes the entire light path, except for the path segment from the Camera to the Surface. See documentation on Light Modes for more information about light paths.







ref : https://unity3d.com/kr/learn/tutorials/topics/graphics/choosing-lighting-technique?playlist=17102

ref : file:///F:/Program%20Files/Unity/Editor/Data/Documentation/en/Manual/LightMode-Baked.html




반응형
반응형


on a scene that has been lightmapping lovely in 5.4 when I updated to 5.6 and tried to use the preview setup, in the console window I got this error message (about 500 times before I stopped it..)

[PathTracer] AddInstanceProperties job with hash: ce62aefc8a3f22e61195f7c7bfa3e55a failed with exit code 5.

can anybody let me know what I did wrong?



Fedaykin542 said: 

I'm getting the same error.

[PathTracer] UpdateInstanceTransforms job with hash: 333deab6c8a92acff9f081bd396fa3e5 failed with exit code 1.

Tried deleting lightmap cache, tried clearing baked data, opened and closed Unity several times, restarted my computer, but error persists.

I have 16GB memory and when using the progressive lightmapper, memory usage on my PC goes from 2GB to 15.9GB and then Unity crashes, so it must to be a memory issue, like you say.


ref : https://forum.unity.com/threads/exit-code-5.464988/


반응형
반응형


Build Settings > Player Settings > 안드로이드 아이콘 > Resolution





기본이 Portrait로 되어 있다.

그래서 Landscape Left로 바꿔주었음.

자동으로 가로 방향 회전만 필요할 시,

Auto Rotation로 지정하고

Landscape Right, Landscape Left 만 체크해주면 된다.



ref : http://vividmani.blogspot.kr/2014/06/blog-post_4702.html

반응형
반응형

텍스쳐를 선택하고 Inspector 뷰로 들어가면 텍스쳐와 관련된 메뉴들이 보인다.

 

여기서 Texture Type 메뉴를 클릭해보자. 뭔가 주르륵~ 나타난다.




 

Texture        : 물체의 표면에 이미지를 입히는 용도로 텍스쳐를 설정한다. 기본적인 설정.

Normal Map : 이미지를 노멀 정보를 제공하는 텍스쳐로 설정한다. 주로 범프맵(BumpMap)효과에 사용.

GUI             : 이미지를 확대 축소 없이 있는 그대로 표현하기 위해 사용. 주로 2D Game 이나 GUI 에 사용.

Cursor         : 커서를 표현하는데 사용.

Reflection    : 일반 2D 이미지 텍스쳐를 반사 환경에 사용되는 3D 큐브맵 텍스쳐로 변환한다.

Cookie        : 텍스쳐를 쿠키를 생성하는 용도로 사용한다. 

Lightmap     : 표면에 빛을 계산한 결과가 저장된 라이트맵 텍스쳐로 사용한다.

Advanced    : 세부적인 텍스쳐 기능을 조절. (다음 단락에서 정리할것임.)








Non Power of 2           : 텍스쳐 크기가 2의 n승 크기가 아닐 경우 어떤 방식으로 처리할지 결정한다. 

Generate Cubemap     : 텍스쳐를 기반으로 큐브맵을 생성. 큐브맵에 대한것은 이후에 따로 서술.

Read/Write Enabled    : 텍스쳐를 쓸 수 있게 설정. 활성화하면 프로그램을 통해 텍스쳐의 내용을 변경할 수 있다.

Import Type                : 이미지를 사용하는 용도를 지정한다. (Default : 일반적인 이미지, Normal Map : 노멀 맵, Lightmap : 라이트맵)

Alpha from Grayscale  : 현재 이미지의 무채색 정보를 기반으로 알파 채널을 생성.

Bypass RGB Sample   : 텍스쳐를 감마 보정에서 선형 보정으로 변환하지 않게 설정.

Create from Grayscale : 이미지의 무채색 정보로부터 노멀 매핑을 위한 RGB 채널을 생성.

Generate Normal Map  : 이미지의 무채색 정보로부터 노멀 매핑을 위한 텍스쳐를 생성.

Bumpiness           : 튀어 나온 정도를 조절.

In Linear Space       : 밉맵을 생성할 때 감마 보정을 수행하지 않습니다.

Border Mipmaps      : 작은 밉맵에서 가장자리로 색상이 침투하는 현상을 방지.

Mipmap Filtering     : 밉맵 생성 방식을 결정한다. (Box : 이미지가 부드럽게 작아짐, Kaiser : 이미지가 날카롭게 작아짐)

Fade Out Mips       : 밉맵 레벨이 낮아질수록 점점 희미하게 회색으로 처리. 왼쪽 화살표는 희미하게 시작하는 밉맵 단계, 오늘쪽은 희미해져 회식이 되는 밉맵 단계.



ref : http://nuberus.blog.me/50183069159





반응형
반응형

오클루전 컬링은 다른 오브젝트에 가려져 카메라에 비치지 않게 되어 버린 오브젝트의 렌더링을 무효화하는 기능입니다.


오클루전 컬링

오클루전 컬링은 다른 오브젝트에 가려져 카메라에 비치지 않게 되어 버린 오브젝트의 렌더링을 무효화하는 기능입니다. 3D 컴퓨터 그래픽의 세계에서는 대부분의 경우 카메라에서 먼 오브젝트에서 먼저 그려지며, 더 가까이 있는 오브젝트가 차례차례 덮어써지게 됩니다(“오버 드로우”라고 부릅니다). 오클루전 컬링은 그만큼 당연한 기능이 아닙니다. 오클루전 컬링은 절두체 컬링(Frustum Culling)과는 다릅니다. 절두체 컬링은 카메라의 표시 영역에서 벗어난 오브젝트의 렌더링을 비활성화하는 것이고, 오클루전 컬링과 같이 오버 드로우에 의해 안 보이게 되는 오브젝트 렌더링은 무효화하지 않습니다. 또한, 오클루전 컬링을 사용하면서 동시에 절두체 컬링의 혜택을 누릴 수 있습니다.

A maze-like indoor level. This normal scene view shows all visible Game Objects.
A maze-like indoor level. This normal scene view shows all visible Game Objects.
Regular frustum culling only renders objects within the cameras view. This is automatic and always happens.
Regular frustum culling only renders objects within the camera’s view. This is automatic and always happens.
Occlusion culling removes additional objects from within the camera rendering work if they are entirely obscured by nearer objects.
Occlusion culling removes additional objects from within the camera rendering work if they are entirely obscured by nearer objects.

오클루전 컬링 처리에서는 먼저 가상 카메라를 사용하여 가시 상태가 될 수 있는 오브젝트의 계층 구조가 생성됩니다. 게임 실행시에는 각 카메라가 이 데이터를 이용하여 가시 여부를 확인합니다. 그 확인 결과를 이용하여 Unity는 가시 상태의 오브젝트만을 렌더링합니다. 그 결과, 드로우콜 수가 감소하고 게임 성능이 향상됩니다.

오클루전 컬링에 사용되는 데이터는 셀(Cell)로 구성되어 있습니다. 각 셀은 씬 전체의 바운딩 볼륨(Bounding Volume)을 분할한 것입니다. 그리고 보다 상세하게는,이 셀은 이진 트리(Binary tree)를 구성하고 있습니다. 오클루전 컬링은 두개의 트리 구조 데이터를 사용합니다. 하나는 View Cells(정적 오브젝트용)이고 다른 하나는 Target Cells(동적 오브젝트용)입니다. View Cells는 가시의 정적 오브젝트용의 인덱스에 연결되어 있어, 정적 오브젝트에 대한 더 정확한 컬링 결과를 제공하기 위해 사용됩니다.

게임 오브젝트를 만들 때는 이 셀을 명심해두면 좋을 것입니다. 왜냐하면 게임 오브젝트와 셀의 크기의 좋은 밸런스를 위해 필요하기 때문입니다. 가능한한, 오브젝트에 ​​대해 너무 작은 셀이나, 여러 셀을 포함하는 오브젝트를 만들어서는 안 됩니다. 큰 개체를 작은 조각으로 분할하여 컬링의 효과를 향상시킬 수 있습니다. 그러나 다른 한편으로는 드로우콜을 줄이기 위해 작은 오브젝트를 병합할 수 있습니다. 그리고 동일한 셀에 포함된 오브젝트끼리는 오클루전 컬링의 효과는 발동하지 않는다는 점도 주의가 필요합니다. 어떤 셀이 어느 셀에서 보고 표시 상태가 되는지에 대한 판정에 사용되는 셀 표시 정보를, 통틀어서 PVS (PotentiallyVisibleSet)이라고 합니다.

You can use the ‘overdraw’ scene rendering mode to see the amount of overdraw that is occuring, and the stats information pane in the game view to see the amount of triangles, verts, and batches that are being rendered. Below is a comparison of these before and after applying occlusion culling.

Notice in the Overdraw scene view, a high density of overdraw as many rooms beyond the visible walls are rendered. These arent visible in the game view, but nonetheless time is being taken to render them.
Notice in the Overdraw scene view, a high density of overdraw as many rooms beyond the visible walls are rendered. These aren’t visible in the game view, but nonetheless time is being taken to render them.
With occlusion culling applied, the distant rooms are not rendered, the overdraw is much less dense, and the number of triangles and batches being rendered has dropped dramatically, without any change to how the game view looks.
With occlusion culling applied, the distant rooms are not rendered, the overdraw is much less dense, and the number of triangles and batches being rendered has dropped dramatically, without any change to how the game view looks.

오클루전 컬링 설정

오클루전 컬링을 이용함에 있어 몇 가지 수작업이 필요합니다. 먼저 레벨의 지오메트리를 적당한 크기의 조각으로 분할해야 합니다. 한층 더 레벨이 명확하게 정의된, 가능한 한 작은 영역마다 정리되는 대로 배치하는 것도 좋습니다. 또한, 벽, 빌딩 등의 거대한 오브젝트들로부터 가려진 영역을 소규모로 정의된 영역에 레벨을 배치하는게 도움이 됩니다. 이 개념은 개별 메쉬가 오클루전의 데이터를 기반으로 활성화 또는 비활성화된다는 것입니다. 따라서 예를 들면, 당신의 레벨에 단 하나의 오브젝트 밖에 없고, 게다가 그 안에 방과 모든 가구의 메쉬가 포함된 경우에는 모두가 컬링되거나 또는 아무것도 컬링되지 않거나의 두 개의 선택이 되어 버립니다. 이래서는 의미가 없습니다. 또한 가구의 파트마다 메쉬를 나누어 각 부분이 카메라의 관점에 기초하여 컬링되도록 하는 것도 마찬가지로 의미가 없습니다.

씬 안에서 오클루전을 적용하는 모든 오브젝트는 Inspector에서 Occluder Static 태그를 붙일 필요가 있습니다. 이렇게 하는 빠른 방법은, 오클루전의 계산에 포함할 오브젝트를 다중 선택하고 Occluder Static 및 Occludee Static 체크 마크를 붙이는 것입니다.

오브젝트의 오클루전에 대해 마킹
오브젝트의 오클루전에 대해 마킹

Occludee Static 을 어떤 경우에 사용할 수 있는지 설명합니다. 다른 오브젝트를 가로막는 것이 없는 투명한 오브젝트와 작은 오브젝트는 Occluders 대신 Occludees의 확인란을 선택해야 합니다. 체크된 오브젝트는 다른 오브젝트에 의한 가림 판정시에 고려되어, 가려진 측면으로 판정시에는 무시됩니다. 이에 따라 계산 비용이 낮아집니다.

오클루전 컬링 창

대부분의 오클루전 컬링 처리에 대해서는, Occlusion Culling 창 (Window->Occlusion Culling) 을 사용 해야 합니다.

Occulusion Culling 창에서는 가리는 쪽이 될 메쉬의 설정이나, Occlusion Areas 설정이 가능합니다.

Occlusion Culling window의 Object 탭을 표시 중이고 씬에서 [Mesh Renderer](class- MeshRenderer)를 선택하는 경우, 그것에 Static 관련 플래그를 변경할 수 있습니다.

메쉬 렌더러 용 Occlusion Culling 창
메쉬 렌더러 용 Occlusion Culling 창

Occlusion Culling window의 Object 탭을 표시 중이고 Occlusion Area를 선택하는 경우에는 오클루전 영역 관련 프로퍼티를 변경할 수 있습니다 (자세한 내용은 Occlusion Area를 참조하십시오).

오클루전 영역의 Occlusion Culling 창
오클루전 영역의 Occlusion Culling 창

참고: 오클루전 영역을 하나도 만들지 않으면 기본값으로 씬 전체에 오클루전 컬링이 적용됩니다.

참고: 카메라가 오클루전 영역 외에 있는 경우, 오클루전 컬링은 적용되지 않습니다. 따라서 카메라가 이동할 수 있는 위치를 모두 커버하도록 오클루전 영역을 설정하는 것이 중요합니다. 그러나 오클루전 영역이 너무 크면 이번에는 베이크 처리에 시간이 걸리게 되어 버립니다.

오클루전 컬링 - Bake

오클루전 컬링 인스펙터의 Bake 탭
오클루전 컬링 인스펙터의 Bake 탭

The occlusion culling bake window has a “Set Default Parameters” button, which allows you to reset the bake values to Unity’s default values. These are good for many typical scenes, however you’ll often be able to get better results by adjusting the values to suit the particular contents of your scene.

프로퍼티

프로퍼티기능
Smallest OccluderThe size of the smallest object that will be used to hide other objects when doing occlusion culling. Any objects smaller than this size will never cause objects occluded by them to be culled. For example, with a value of 5, all objects that are higher or wider than 5 meters will cause hidden objects behind them to be culled (not rendered, saving render time). Picking a good value for this property is a balance between occlusion accuracy and storage size for the occlusion data.
Smallest HoleThis value represents the smallest gap between geometry through which the camera is supposed to see. The value represents the diameter of an object that could fit through the hole. If your scene has very small cracks through which the camera should be able to see, the Smallest Hole value must be smaller than the narrowest dimension of the gap.
Backface ThresholdUnity’s occlusion uses a data size optimization which reduces unnecessary details by testing backfaces. The default value of 100 is robust and never removes backfaces from the dataset. A value of 5 would aggressively reduce the data based on locations with visible backfaces. The idea is that typically, valid camera positions would not normally see many backfaces - for example, the view of the underside of a terrain, or the view from within a solid object that you should not be able to reach. With a threshold lower than 100, Unity will remove these areas from the dataset entirely, thereby reducing the data size for the occlusion.

bake 탭의 하단에는 Clear와 Bake 버튼이 있습니다. 오클루전 컬링 데이터를 생성하기 위해서 Bake 버튼을 클릭합니다. 한번 데이터가 생성되고나면, Visualization 탭을 이용하여 오클루전 컬링을 테스트할 수 있습니다. 만약 결과가 만족스럽지 않은 경우, Clear 버튼을 클릭하면 이전의 계산 결과를 지우고, 셋팅을 조절하고, 다시 구울(bake) 수 있습니다.

오클루전 컬링 - Visualization

오클루전 컬링 인스펙터의 Visualization 탭
오클루전 컬링 인스펙터의 Visualization 탭

바운딩 볼륨의 크기는 씬 내의 모든 오브젝트에 영향을 받기 때문에 가능한 모든 오브젝트가 씬의 가시 영역에 맞도록 하십시오.

오클루전 데이터를 생성할 준비가 끝나면 Bake 버튼을 클릭하십시오. 그 때, Bake 탭에 있는 Memory Limit 값을 올바르게 선택합시다. 이 값이 작을수록 데이터의 생성 속도가 빨라지며, 내용은 정확하지 않게 됩니다. 반대로 값이 클수록 릴리즈를 위한 제품 레벨의 퀄리티에 다가갑니다.

오클루전 데이터의 생성에 걸리는 시간은 셀의 정보와 데이터 크기, 선택한 퀄리티에 좌우된다는 점에 유의하십시오. Unity는 메인 윈도우 하단에 PVS 생성의 상태를 표시합니다.

생성 처리가 완료되면 뷰 영역에 다채로운 색상의 큐브들이 표시됩니다. 이같은 색으로 표시된 영역은 같은 오클루전 데이터를 공유하고 있습니다.

Clear 버튼을 클릭하면 오클루전 컬링을 위해 미리 계산된 데이터를 지울 수 있습니다.

오클루전 영역

오클루전 컬링을 적용하기 위해서는 Occlusion Area를 만들고 이동하는 오브젝트가 배치될 위치가 되도록 크기를 수정해야 합니다(당연히, 이동하는 오브젝트를 Static으로 할 수는 없습니다). Occlusion Area를 만들려면, 빈 게임 오브젝트에Occlusion Area 컴포넌트를 추가합니다. (메뉴에서 Component -> Rendering -> Occlusion Area)

Occlusion Area를 만든 후, IsTargetVolume 확인란을 선택하여 움직이는 오브젝트를 오클루전(무시)합니다.

프로퍼티:기능:
Size오클루전 영역의 크기를 정의
Center오클루전 영역의 중심을 설정합니다. 기본적으로 (0,0,0)이고, 박스의 중앙에 위치하고 있습니다.
Is View Volume카메라를 배치할 위치를 정의합니다. Occlusion Area 에 있는 Static 오브젝트를 오클루전할 때 활성화 합니다.
움직이는 오브젝트에 대한 오클루전 영역 프로퍼티.
움직이는 오브젝트에 대한 오클루전 영역 프로퍼티.

Occlusion Area를 만든 후 상자를 셀 분할하는 방법을 확인해야 합니다. Occlusion Area가 어떻게 산출되었는지 확인하기 위해서는 Occlusion Culling Preview Panel 에서 Edit를 선택하고 View 를 토글하여 선택하십시오 .

생성된 오클루전 테스트

오클루전을 설치한 후, Occlusion Culling 을 선택하고 (Visualize mode의 Occlusion Culling Preview Panel에서) Main Camera를 씬 뷰 안으로 이동함으로써 테스트할 수 있습니다.

씬 뷰의 오클루전 뷰 모드
씬 뷰의 오클루전 뷰 모드

메인 카메라를 이동하는데 맞추어 (Play 모드가 아닌 경우에도) 오브젝트가 비활성화(disable)가 되는 것을 확인할 수 있습니다. 오클루전 데이터에 오류가 나오지 않는 것을 확인할 필요가 있습니다. 이동함에 따라 오브젝트가 뷰에 끼어 들어 오면 오류로 인식할 수 있습니다. 이 경우 오류를 해결하기 위해 옵션으로는 화면 해상도를 변경(Target Volumes를 변경한 경우)하거나, 오브젝트를 이동하여 오류가 나오지 않게 하는 방법이 있습니다. 오클루전에서 디버깅을 하기 위해서는 메인 카메라를 문제가 있는 위치로 이동하여 집중 검사를 할 수 있습니다.

처리가 완료되면 뷰 영역에서 컬러풀한 큐브를 확인할 수 있습니다. 파란 큐브는 Target Volumes(Target Volume)의 셀 분할을 의미합니다. 흰색 큐브는View Volumes(View Volume)의 셀 분할을 의미합니다. 만약 파라미터가 올바르게 설정되어 있으면 일부 오브젝트는 렌더링되지 않습니다. 그 이유는 카메라의 뷰 프러스텀의 외부에 있거나 다른 오브젝트의 배치에 의해 무시되었을 것입니다.

오클루전이 완료된 후, 씬에서 아무것도 오클루전되지 않은 경우, 오브젝트를 더 작은 부분으로 분해하여 그 오브젝트가 셀 안에 들어가는 크기로 되어 집니다.




오클루전 영역

오클루전 컬링을 적용하기 위해서는 Occlusion Area를 만들고 이동하는 오브젝트가 배치될 위치가 되도록 크기를 수정해야 합니다(당연히, 이동하는 오브젝트를 Static으로 할 수는 없습니다). Occlusion Area를 만들려면, 빈 게임 오브젝트에Occlusion Area 컴포넌트를 추가합니다. (메뉴에서 Component -> Rendering -> Occlusion Area)

Occlusion Area를 만든 후, IsTargetVolume 확인란을 선택하여 움직이는 오브젝트를 오클루전(무시)합니다.

프로퍼티:기능:
Size오클루전 영역의 크기를 정의
Center오클루전 영역의 중심을 설정합니다. 기본적으로 (0,0,0)이고, 박스의 중앙에 위치하고 있습니다.
Is View Volume카메라를 배치할 위치를 정의합니다. Occlusion Area 에 있는 Static 오브젝트를 오클루전할 때 활성화 합니다.
움직이는 오브젝트에 대한 오클루전 영역 프로퍼티.
움직이는 오브젝트에 대한 오클루전 영역 프로퍼티.

Occlusion Area를 만든 후 상자를 셀 분할하는 방법을 확인해야 합니다. Occlusion Area가 어떻게 산출되었는지 확인하기 위해서는 Occlusion Culling Preview Panel 에서 Edit를 선택하고 View 를 토글하여 선택하십시오 .

생성된 오클루전 테스트

오클루전을 설치한 후, Occlusion Culling 을 선택하고 (Visualize mode의 Occlusion Culling Preview Panel에서) Main Camera를 씬 뷰 안으로 이동함으로써 테스트할 수 있습니다.

씬 뷰의 오클루전 뷰 모드
씬 뷰의 오클루전 뷰 모드

메인 카메라를 이동하는데 맞추어 (Play 모드가 아닌 경우에도) 오브젝트가 비활성화(disable)가 되는 것을 확인할 수 있습니다. 오클루전 데이터에 오류가 나오지 않는 것을 확인할 필요가 있습니다. 이동함에 따라 오브젝트가 뷰에 끼어 들어 오면 오류로 인식할 수 있습니다. 이 경우 오류를 해결하기 위해 옵션으로는 화면 해상도를 변경(Target Volumes를 변경한 경우)하거나, 오브젝트를 이동하여 오류가 나오지 않게 하는 방법이 있습니다. 오클루전에서 디버깅을 하기 위해서는 메인 카메라를 문제가 있는 위치로 이동하여 집중 검사를 할 수 있습니다.

처리가 완료되면 뷰 영역에서 컬러풀한 큐브를 확인할 수 있습니다. 파란 큐브는 Target Volumes(Target Volume)의 셀 분할을 의미합니다. 흰색 큐브는View Volumes(View Volume)의 셀 분할을 의미합니다. 만약 파라미터가 올바르게 설정되어 있으면 일부 오브젝트는 렌더링되지 않습니다. 그 이유는 카메라의 뷰 프러스텀의 외부에 있거나 다른 오브젝트의 배치에 의해 무시되었을 것입니다.

오클루전이 완료된 후, 씬에서 아무것도 오클루전되지 않은 경우, 오브젝트를 더 작은 부분으로 분해하여 그 오브젝트가 셀 안에 들어가는 크기로 되어 집니다.




ref : https://docs.unity3d.com/kr/current/Manual/OcclusionCulling.html

ref : https://docs.unity3d.com/kr/current/Manual/class-OcclusionArea.html


반응형
반응형

에셋 번들에서 오브젝트를 로드, 언로드

다운로드 한 데이터에서 만든 에셋 번들에서 오브젝트가 있으면 세 가지 방법으로 오브젝트를 로드할 수 있습니다 :

  • [AssetBundle.LoadAsset](ScriptRef : AssetBundle.LoadAsset.html)에서 이름 식별자를 파라미터로 사용하여 오브젝트를 로드합니다. 이름은 프로젝트 뷰에 표시되는 것입니다. 선택적으로 오브젝트 타입을 파라미터로 Load 메소드에 전달하여 로드된 오브젝트가 특정 타입인지 여부를 확인할 수 있습니다.

  • [AssetBundle.LoadAssetAsync](ScriptRef : AssetBundle.LoadAssetAsync.html)는 위의 Load 메소드처럼 작동하지만, 에셋이 로드될 때 메인 스레드를 차단하지 않습니다. 따라서 이 메소드는 큰 에셋이나 여러 에셋을 동시에 로드할 때 응용 프로그램이 정지하는 것을 피하는 데에 유용합니다.

  • [AssetBundle.LoadAllAssets](ScriptRef : AssetBundle.LoadAllAssets.html)에 의해 에셋 번들에 포함된 모든 오브젝트를 로드합니다. AssetBundle.LoadAsset과 마찬가지로 오브젝트를 타입에 따라 필터링 할 수 있습니다.

에셋을 언로드하려면 [AssetBundle.Unload](ScriptRef : AssetBundle.Unload.html)를 사용해야 합니다. 이 메소드는 boolean 인수로 Unity에서 모든 데이터를 언로드 할 지(로드된 에셋의 오브젝트를 포함), 다운로드 한 번들에서 압축된 데이터만 언로드 할 지 여부를 지정합니다. 만약 응용프로그램에서 에셋 번들의 어떤 오브젝트를 사용하고 있고, 메모리를 확보하려는 경우, False를 전달하여 메모리에서 압축된 데이터를 언로드 할 수 있습니다. 만약 에셋 번들에서 완전히 모두를 언로드하려면 True를 전달하여 에셋 번들에서 로드된 에셋을 삭제합니다.

에셋 번들로부터 오브젝트를 비동기 로드

[AssetBundle.LoadAssetAsync](ScriptRef : AssetBundle.LoadAssetAsync.html) 메소드를 사용하여 오브젝트를 비동기 로드함으로써 응용 프로그램에 끊기는 현상(hiccup)이 생길 가능성을 줄입니다.

using UnityEngine;

// Note: This example does not check for errors. Please look at the example in the DownloadingAssetBundles section for more information
IEnumerator Start () {
    while (!Caching.ready)
        yield return null;
    // Start a download of the given URL
    WWW www = WWW.LoadFromCacheOrDownload (url, 1);

    // Wait for download to complete
    yield return www;

    // Load and retrieve the AssetBundle
    AssetBundle bundle = www.assetBundle;

    // Load the object asynchronously
    AssetBundleRequest request = bundle.LoadAssetAsync ("myObject", typeof(GameObject));

    // Wait for completion
    yield return request;

    // Get the reference to the loaded object
    GameObject obj = request.asset as GameObject;

        // Unload the AssetBundles compressed contents to conserve memory
        bundle.Unload(false);

        // Frees the memory from the web stream
        www.Dispose();
}







인터넷에 아래처럼 에셋번들 빌드하는게 돌아 다니는데 이걸로 하면 최근 버전에선 사용되지 않는 옵션들로 변경되어 있다

BuildAssetBundleOptions.CollectDependencies |  BuildAssetBundleOptions.CompleteAssets |


이거 대신에 


BuildAssetBundleOptions.None 을 쓰면 됨



BuildPipeline.BuildAssetBundles("저장위치", BuildAssetBundleOptions.None, BuildTarget.Android);



반응형
반응형
Unity 2017 New Features - Sprite atlas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
 
 
 
public class AtlasTest : MonoBehaviour {
 
 
 
    [SerializeField]
    private SpriteAtlas atlas;
 
    private SpriteRenderer myRenderer;
 
 
    // Use this for initialization
    void Start () {
        myRenderer = GetComponent<SpriteRenderer>();        //Get Sprite renderer into sprite object(2D Object -> Sprite) in unityeditor Hierachy
        myRenderer.sprite = atlas.GetSprite("snow");        //SpriteAtlas is created by "Create -> Sprite Atlas" and "Snow" is one of atla sprite image names.
 
    }
    
    // Update is called once per frame
    void Update () {
        
    }
 
    private void ChangeSprite()
    {
 
    }
 
}
 
cs



ref : https://youtu.be/3a-Ymcp_s-k

반응형

+ Recent posts