Loading...
Loading...
Write Unity 6 C# gameplay scripts: the MonoBehaviour lifecycle (Awake/OnEnable/Start/Update/FixedUpdate/LateUpdate), GameObject and component access, coroutines, and Inspector serialization. Use when creating or editing .cs scripts in a Unity project, or when the user mentions MonoBehaviour, Start/Update, GetComponent, SerializeField, coroutines, or "Unity script".
npx skill4agent add gamedev-skills/awesome-gamedev-agent-skills unity-csharp-scriptingMonoBehaviour*.csAssembly-CSharp*.asmdefProjectSettings/unity-physicsunity-input-systemunity-scriptableobjectsunity-animationAwakeOnEnableStartAwakeUpdateFixedUpdateLateUpdateOnDisableOnDestroyAwakeGetComponent[SerializeField] privateTime.deltaTimeUpdateTime.fixedDeltaTimeFixedUpdateStartCoroutineUpdateusing UnityEngine;
[RequireComponent(typeof(Rigidbody))] // auto-adds the dependency, prevents null refs
public class PlayerController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 6f; // editable in Inspector, private in code
private Rigidbody _rb; // cached, not fetched per frame
private void Awake() => _rb = GetComponent<Rigidbody>(); // cache once on load
private void Update()
{
// Per-frame, non-physics work. Scale by deltaTime so it is frame-rate independent.
transform.Rotate(0f, 90f * Time.deltaTime, 0f);
}
private void FixedUpdate()
{
// Physics work belongs here (fixed timestep). See the unity-physics skill.
_rb.MovePosition(_rb.position + transform.forward * moveSpeed * Time.fixedDeltaTime);
}
}TryGetComponent// Avoids allocating a null and is clearer than GetComponent + null check.
if (other.TryGetComponent<Health>(out var health))
health.Apply(-10);[SerializeField, Range(0f, 1f)] private float volume = 0.8f; // slider
[SerializeField] private string playerName = "Hero"; // private but serialized
[System.Serializable] // REQUIRED for a plain class to serialize/show
public class Stats { public int hp = 100; public int mana = 50; }
[SerializeField] private Stats stats = new(); // nested struct-like data in the Inspectorprivate void Start() => StartCoroutine(FlashThenHide());
private System.Collections.IEnumerator FlashThenHide()
{
yield return new WaitForSeconds(0.5f); // wait half a second of game time
GetComponent<Renderer>().enabled = false;
yield return null; // resume next frame
}GetComponentUpdateAwakeStartUpdateRigidbodyMovePositionFixedUpdateUpdateFixedUpdateStartStartAwakeStartStartAwakepublic[SerializeField] privategameObject.tag == "Enemy"gameObject.CompareTag("Enemy")StartCoroutineOnEnableUpdateStartUpdateStartCustomYieldInstructionWaitUntilWaitWhilereferences/lifecycle-and-coroutines.mdhttps://docs.unity3d.com/Manual/execution-order.htmlScriptReference/MonoBehaviourunity-physicsRigidbodyFixedUpdateunity-input-systemunity-scriptableobjects