Unity
[Unity] 10가지 팁 by TaroDev
성엽이
2022. 11. 15. 11:22
https://www.youtube.com/watch?v=Ic5ux-tpkCE
1. Serializing Components
직렬화(Serialized Field)가 붙은 변수에 컴포넌트가 붙어있는 Prefabs 을 생성해줄 경우 굳이 GameObject 를 만든후 컴포넌트를 붙이지 않아도 된다.
2. Drowing Scene Gizmos
Gizmos Tracking 이 중요하다. 그려놓고 보면 바로 보임
3. Initialization Order
초기화 순서 중요. static pattern 에서 Awake 에서 초기화를 하면 겹침.
[DefaultExecutionOrder(-1)]
public class SensorManager : MonoBehaviour
{
...
}
최근에 알게된 DefaultExecutionOrder
4. Stop using public field
굳이 쓰려면 getter setter 같은 property 를 쓰자.
5. Modulo(%) to loop collections
산술연산자 % 를 잘 활용하자.
public class Cow : MonoBehaviour
{
[SerializeField] private AudioSource _source;
[SerializeField] private AudioClip[] _clips;
private int _clipIndex;
private void OnMouseDown()
{
_source.clip = _clips[_clipIndex++];
_source.Play();
if (_clipIndex >= _clips.Length) _clipIndex = 0;
}
}
To Fixed
public class Cow : MonoBehaviour
{
[SerializeField] private AudioSource _source;
[SerializeField] private AudioClip[] _clips;
private int _clipIndex;
private void OnMouseDown()
{
// Option 1
_source.clip = _clips[_clipIndex++ % _clips.Length];
_source.Play();
// Option 2 - PlayClipAtPoint(AudioClip clip, Vector3 position, float volume = 1.0F)
AudioSource.PlayClipAtPoint(_source.clip, transform.position, 1f);
}
}
6. PlayClipAtPoint 한줄로
7. Limit extern calls with SetPositionAndRotation
transform.position , transform.rotation 을 초기화할 때 SetPositionAndRotation 같은 API 로 한줄로
8. Operator overloading
public struct Stats
{
public int AttackPower;
public int Health;
public static Stats operator +(Stats a, Stats b)
{
return new Stats
{
AttackPower = a.AttackPower + b.AttackPower,
Health = a.Health + b.Health
};
}
}
public class Something
{
public Something()
{
var baseStats = new Stats
{
AttackPower = 69,
Health = 420
};
var leveledStats = new Stats
{
AttackPower = 123,
Health = 456
};
// from
var finalStats = new Stats
{
AttackPower = baseStats.AttackPower + leveledStats.Health,
Health = baseStats.AttackPower + leveledStats.Health
};
// to
var finalStats = baseStats + leveledStats;
}
}
9. Composition
구성방식 - 필요에 따라서 독립성과 종속성을 지켜가면서 구성하기
10. Don't use lazy naming conventions
변수이름 편하게 적지말고, 정확하게 적기