블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2735)
Unity3D (815)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-18 00:09

[Unity3D] Attributes 설명 모음

알고 있으면 생산, 작업 효율성을 매우 높일 수 있는 attribute들을 unity에서 제공한다.

1) AddComponentMenu 
기본적으로 스크립트는 유니티의 Component->Scripts 메뉴에 자동추가된다.
자동추가말고 아무데나 맘대로 넣고 싶으면 AddComponentMenu를 사용한다.

[AddComponentMenu("Transform/Follow Transform")]
public class FollowTransform : MonoBehaviour
{
}

2) ContextMenu 
스크립트를 우클릭시 뜨는 context menu에 커맨드를 추가할 수 있다.

public class ContextTesting : MonoBehaviour {
/// Add a context menu named "Do Something" in the inspector
/// of the attached script.
[ContextMenu ("Do Something")]
void DoSomething () {
Debug.Log ("Perform operation");
}
}
이렇게 하면 컨텍스트 메뉴에 Do Something이 나타나고, 선택하면
ContextTesting.DoSomething() 메소드가 호출된다.

3) ExecuteInEditMode 
기본적으로 play mode일 때만 스크립트가 실행되나,
이 attribute를 사용하면 edit mode일 때도 스크립트가 실행되게 한다.
(Update, FixedUpdate, and OnGUI functions)
예제는 이렇다.

using UnityEngine;
using System.Collections;
[ExecuteInEditMode]public class example : MonoBehaviour {
public Transform target;
void Update() {
if (target)
transform.LookAt(target);
}
}

4) HideInInspector 
inspector에서 안보이게 한다.

using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
[HideInInspector]public int p = 5;
}
더이상 p를 inspector에서 볼 수 없다.
하지만 이전에 이미 inspector를 통해 세팅한 값이 있다면 그 값은
그대로 유지된다.

5) NonSerialized 
앞서 HideInInspector는 값을 유지하지만, 이건 그냥 리셋하여 디폴트값
으로 바꾼다.

class Test 
{
// p will not be shown in the inspector or serialized
[System.NonSerialized]public int p = 5;
}

6) RPC 네트워크 관련된 거라서 당장 필요없으므로 대충 스킵.

7) RequireComponent 
함께 필요한 다른 컴포넌트가 자동으로 추가된다.

[RequireComponent (typeof (Rigidbody))]
public class PlayerScript : MonoBehaviour {
void FixedUpdate() {
rigidbody.AddForce(Vector3.up);
}
}
이렇게 하면 작성하면, PlayerScript추가할 때 Rigidbody도 
같이 추가된다.

8) Serializable
일단 코드를 보면 대충 이런 상황이다.
class Sample : MonoBehaviour {
   public Test aa;
}
class Test
{
  public int p = 5;
  public Color c = Color.white;
}
보통 inspector에서 Sample::a.p, Sample::a.c 요놈들은
안보여서 편집할 수가 없는데,
[System.Serializable]
class Test
{
  public int p = 5;
  public Color c = Color.white;
}
이렇게 해주면 inspector에서 편집가능하다.

9) SerializeField
private필드를 강제로 serialize한다.
그러므로 inspector에서도 편집이 가능해진다.
예제코드는 아래와 같다.

using UnityEngine;
public class SomePerson : MonoBehaviour {
//This field gets serialized because it is public.
public string name = "John";
//This field does not get serialized because it is private.
private int age = 40;
//This field gets serialized even though it is private
//because it has the SerializeField attribute applied.
[SerializeField]
private bool hasHealthPotion = true;
void Update () {
}
}





공식홈페이지 링크


http://unity3d.com/support/documentation/ScriptReference/20_class_hierarchy.Attributes.html


AddComponentMenu : 유니티 메뉴 추가.

// C# example:
[AddComponentMenu("Transform/Follow Transform")]
public class FollowTransform : MonoBehaviour
{
}


ContextMenu : 우클릭 메뉴 추가.

// C# example:
public class ContextTesting : MonoBehaviour {
    /// Add a context menu named "Do Something" in the inspector
    /// of the attached script.
    [ContextMenu ("Do Something")]
    void DoSomething () {
        Debug.Log ("Perform operation");
    }
}


ExecuteInEditMode : 에디트 모드에서 스크립트 실행.

using UnityEngine;
using System.Collections;

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


HideInInspector : 인스펙터에서 속성 감추기, 이전 세팅값은 유지.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    [HideInInspector]
    public int p = 5;
}


NonSerialized : 인스펙터에서 속성 감추기, 이전 세팅값은 무시.

// C# Example
class Test {
    // p will not be shown in the inspector or serialized
    [System.NonSerialized]
    public int p = 5;
}


RPC : 원격지 호출 함수로 지정, 보내는 쪽과 받는 쪽 모두 다 존재해야 함.

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public Transform cubePrefab;
    void OnGUI() {
        if (GUILayout.Button("SpawnBox")) {
            NetworkViewID viewID = Network.AllocateViewID();
            networkView.RPC("SpawnBox", RPCMode.AllBuffered, viewID, transform.position);
        }
    }
    [RPC]
    void SpawnBox(NetworkViewID viewID, Vector3 location) {
        Transform clone;
        clone = Instantiate(cubePrefab, location, Quaternion.identity) as Transform as Transform;
        NetworkView nView;
        nView = clone.GetComponent<NetworkView>();
        nView.viewID = viewID;
    }
}


RequireComponent : 컴포넌트 자동 추가.

[RequireComponent (typeof (Rigidbody))]
public class PlayerScript : MonoBehaviour {
    void FixedUpdate()  {
        rigidbody.AddForce(Vector3.up);
    }
}


Serializable : 인스펙터에 인스턴스의 하위 속성 노출.

// C# Example
[System.Serializable]
class Test
{
    public int p = 5;
    public Color c = Color.white;
}

class Sample : MonoBehaviour 
{
    public Test serializableObj; // 인스펙터에 p, c가 노출된다.
}


SerializeField : 인스펙터에 비공개 멤버 노출.

//C# example
using UnityEngine;

public class SomePerson : MonoBehaviour {
    //This field gets serialized because it is public.
    public string name = "John";

    //This field does not get serialized because it is private.
    private int age = 40;

    //This field gets serialized even though it is private
    //because it has the SerializeField attribute applied.
    [SerializeField]
    private bool hasHealthPotion = true;

    void Update () {
    }
}



출처 : http://smilejsu.tistory.com/432


반응형

'Unity3D > Script' 카테고리의 다른 글

특정시간 뒤에 함수 호출하도록 설정하기 (WaitForSeconds)  (0) 2012.11.21
AnimationEvent 추가 방법  (0) 2012.11.21
WaitForSeconds()  (0) 2012.11.21
애니메이션 스크립팅(Animation Scripting)  (2) 2012.11.16
FadeInOut  (0) 2012.10.31
Posted by blueasa
, |