본문 바로가기

코딩/Unity

Unity 스크립트가 비활성화되어도 작동하는 함수

반응형

댓글과 공감클릭은 더 좋은 글을 위한 큰 힘이 되니, 댓글과 공감 클릭 부탁드립니다!!

 

Unity로 게임개발을 진행하던 도중,

어떤 게임오브젝트에 붙어있는 스크립트를 비활성화(enabled = false;)시켜야 하는 상황이 생겼다.

이 스크립트에는 OnCollisionEnter함수도 있었는데, 이 함수도 게임 로직 상 비활성화가 돼야 했었다.

 

<문제상황>

나는 처음에는 스크립트 자체를 비활성화시키면,

당연히 그 스크립트 내에 있는 OnCollisionEnter도 비활성화가 될 줄 알았다.

그러나 스크립트 자체를 비활성화시켰음에도, 그 스크립트의 OnCollisionEnter함수가 작동하는 것이 아닌가.

 

그래서 이 내용에 대해 구글링한 결과, 그 이유를 알게 되었다.

 

Unity의 스크립트를 비활성화시키면 그 스크립트의 모든 함수가 비활성화되는 것이 아니다.

아래 함수들만 비활성화된다.

Start()
Update()
FixedUpdate()
LateUpdate()
OnGUI()
OnDisable()
OnEnable()

 

이 외의 모든 함수들은 스크립트가 비활성화되어도 작동을 한다.

그래서, 스크립트를 비활성화시켜도 OnCollisionEnter함수가 작동하는 것이었다.

 

<해결방안>

해당 오브젝트의 스크립트를 비활성화할 때,

해당 오브젝트에 붙어있는 Collider도 비활성화해줌으로써, OnCollisionEnter함수의 작동을 방지했다.

 

<참고자료>

https://docs.unity3d.com/ScriptReference/MonoBehaviour.html

 

Unity - Scripting API: MonoBehaviour

MonoBehaviour offers life cycle functions that make it easier to develop with Unity. MonoBehaviours always exist as a Component of a GameObject, and can be instantiated with GameObject.AddComponent. Objects that need to exist independently of a GameObject

docs.unity3d.com

https://forum.unity.com/threads/oncollisionenter-running-when-script-is-disabled.168400/

 

OnCollisionEnter Running when script is disabled

I was under the impression that if a component is attached to an object, but disabled, then no functions inside should be running. However,...

forum.unity.com

 

댓글과 공감클릭은 더 좋은 글을 위한 큰 힘이 되니, 댓글과 공감 클릭 부탁드립니다!!

반응형