개발일지

[유니티] monobehaviour 스크립트 new 로 선언하지말아야할 경우.

훗냥이 2022. 9. 22. 19:31
728x90

에러메세지 :
you are trying to create a monobehaviour using the 'new' keyword. this is not allowed. monobehaviours can only be added using addcomponent(). alternatively, your script can inherit from scriptableobject or no base class at all

monobehaviour 스크립트는 gameobject가 할당되어야 한다고 함.

예를들어(나의 경우)
프리팹에 들어있는 TraineeTr 스크립트의 경우
TraineeTr tr = new TraineeTr();
이런 식으로 불러올 수 없음.


나는 Trainee_Tr 이 프리팹에 연동되어있기 때문에 monobehaviour를 지울 수도,
다른 스크립트에서 new로 선언하기 때문에 gameobject를 붙이거나 Addcomponent 할 수 없어 아래와 같이 해결함.


TraineeTr 스크립트에
public class TraineeTr_baby{}
라는 클래스를 추가해준 뒤 새롭게 할당할 때 기존 클래스 말고
TraineeTr_baby tr = new TraineeTr_baby(); 이렇게 생성해줌.

필요에 따라 baby 클래스 안에 값들을 생성해서 원래 쓰고 있는 스크립트와 연결해줌.
또 baby 클래스 안에 mom 클래스도 선언해서 서로 이어지게 해줌.

이..게..되..네..?


예시)
public class Trainee_Tr_baby
{
public int MyN;
public bool CanOpenDetail;
public bool CanSetBookmark;
public bool CanCheck;
public Trainee_Tr MyMomTr;
}
public class Trainee_Tr : MonoBehaviour
{
}

728x90