it leader

[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 : 유니티 메뉴 추가.

1
2
3
4
5
// C# example:
[AddComponentMenu("Transform/Follow Transform")]
public class FollowTransform : MonoBehaviour
{
}


ContextMenu : 우클릭 메뉴 추가.

1
2
3
4
5
6
7
8
9
// 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 : 에디트 모드에서 스크립트 실행.

1
2
3
4
5
6
7
8
9
10
11
12
using UnityEngine;
using System.Collections;
 
[ExecuteInEditMode]
public class example : MonoBehaviour {
    public Transform target;
    void Update() {
        if (target)
            transform.LookAt(target);
         
    }
}


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

1
2
3
4
5
6
7
using UnityEngine;
using System.Collections;
 
public class example : MonoBehaviour {
    [HideInInspector]
    public int p = 5;
}


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

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 : 컴포넌트 자동 추가.

1
2
3
4
5
6
[RequireComponent (typeof (Rigidbody))]
public class PlayerScript : MonoBehaviour {
    void FixedUpdate()  {
        rigidbody.AddForce(Vector3.up);
    }
}


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

1
2
3
4
5
6
7
8
9
10
11
12
// C# Example
[System.Serializable]
class Test
{
    public int p = 5;
    public Color c = Color.white;
}
 
class Sample : MonoBehaviour
{
    public Test serializableObj; // 인스펙터에 p, c가 노출된다.
}


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//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 () {
    }
}


profile

it leader

@dev__pixui

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!