作为一个Unity开发者,掌握多种代码技巧可以让你的游戏开发过程更加高效和有趣。以下是30个精心挑选的Unity代码示例,涵盖了多种功能和场景,从简单的物体移动到复杂的物理交互,每个示例都有详细的介绍和注释,帮助你更好地理解和应用这些代码。
1. 简单的物体移动
这个简单的移动脚本可以让物体根据玩家的输入在场景中移动。通过调整speed
变量,可以控制移动速度。
using UnityEngine;
public class SimpleMovement : MonoBehaviour
{
public float speed = 5.0f;
// Update is called once per frame
void Update()
{
// 获取水平和垂直方向的输入
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// 计算移动方向
Vector3 movement = new Vector3(horizontal, 0, vertical);
// 移动物体
transform.Translate(movement * speed * Time.deltaTime, Space.World);
}
}
2. 平滑旋转
这个脚本使物体可以平滑地根据鼠标输入旋转,适用于第一人称或第三人称视角的相机控制。
using UnityEngine;
public class SmoothRotation : MonoBehaviour
{
public float rotationSpeed = 100.0f;
void Update()
{
// 获取鼠标输入
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
// 创建一个旋转向量
Vector3 rotation = new Vector3(-mouseY, mouseX, 0);
// 平滑旋转物体
transform.Rotate(rotation * rotationSpeed * Time.deltaTime);
}
}
3. 物体跳跃
这个脚本使物体在按下空格键时跳跃。通过调整jumpForce
可以控制跳跃高度。
using UnityEngine;
public class Jump : MonoBehaviour
{
public float jumpForce = 5.0f;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
// 检测空格键按下
if (Input.GetKeyDown(KeyCode.Space))
{
// 应用向上力,使物体跳跃
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
4. 碰撞检测
这个脚本在物体碰撞时改变其颜色,碰撞结束时恢复颜色,可以用于简单的碰撞反馈。
using UnityEngine;
public class CollisionExample : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
// 当与另一个物体碰撞时,改变物体颜色
Renderer rend = GetComponent<Renderer>();
rend.material.color = Color.red;
}
void OnCollisionExit(Collision collision)
{
// 当碰撞结束时,恢复物体颜色
Renderer rend = GetComponent<Renderer>();
rend.material.color = Color.white;
}
}
5. 触发器事件
这个脚本展示了如何使用触发器事件来检测物体进入、停留和退出触发器区域。
using UnityEngine;
public class TriggerExample : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
// 当进入触发器范围时,打印信息
Debug.Log("Entered trigger with: " + other.gameObject.name);
}
void OnTriggerStay(Collider other)
{
// 当在触发器范围内时,持续输出信息
Debug.Log("Inside trigger with: " + other.gameObject.name);
}
void OnTriggerExit(Collider other)
{
// 当退出触发器范围时,打印信息
Debug.Log("Exited trigger with: " + other.gameObject.name);
}
}
6. 物体跟随
这个脚本使一个物体(如相机)平滑地跟随另一个物体(如玩家角色)。
using UnityEngine;
public class ObjectFollow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 0.125f;
// LateUpdate is called after all Update functions
void LateUpdate()
{
// 计算目标位置
Vector3 targetPos = new Vector3(target.position.x, target.position.y, transform.position.z);
// 平滑移动到目标位置
transform.position = Vector3.Slerp(transform.position, targetPos, smoothSpeed);
}
}
7. 随机移动
这个脚本使物体在场景中随机移动,适用于NPC或敌人的简单移动逻辑。
using UnityEngine;
using System.Collections;
public class RandomMovement : MonoBehaviour
{
public float moveSpeed = 2.0f;
public float waitTime = 1.0f;
private Vector3 targetPosition;
private float remainingWaitTime;
void Start()
{
SetRandomTarget();
remainingWaitTime = 0f;
}
void Update()
{
// 移动到目标位置
transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
// 检查是否到达目标位置
if (Vector3.Distance(transform.position, targetPosition) < 0.1f)
{
remainingWaitTime -= Time.deltaTime;
// 如果等待时间结束,设置新的目标位置
if (remainingWaitTime <= 0f)
{
SetRandomTarget();
remainingWaitTime = waitTime;
}
}
}
void SetRandomTarget()
{
// 设置随机目标位置
targetPosition = new Vector3(
Random.Range(-10f, 10f),
transform.position.y,
Random.Range(-10f, 10f)
);
}
}
8. 物体旋转到目标方向
这个脚本使物体始终面向目标物体,适用于摄像机、武器瞄准等。
using UnityEngine;
public class LookAtTarget : MonoBehaviour
{
public Transform target;
// Update is called once per frame
void Update()
{
// 旋转物体使其面向目标
transform.LookAt(target);
}
}
9. 随机生成物体
这个脚本定期在场景中随机生成物体,适用于生成敌人、道具等。
using UnityEngine;
using System.Collections;
public class RandomSpawn : MonoBehaviour
{
public GameObject[] objectsToSpawn;
public float spawnInterval = 1.0f;
public float spawnRange = 10.0f;
void Start()
{
// 开始协程,定期生成物体
StartCoroutine(SpawnRoutine());
}
IEnumerator SpawnRoutine()
{
while (true)
{
// 随机选择一个物体
int randomIndex = Random.Range(0, objectsToSpawn.Length);
GameObject objectToSpawn = objectsToSpawn[randomIndex];
// 随机生成位置
Vector3 spawnPosition = new Vector3(
Random.Range(-spawnRange, spawnRange),
1f,
Random.Range(-spawnRange, spawnRange)
);
// 对象实例化
Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);
// 等待一段时间再生成下一个物体
yield return new WaitForSeconds(spawnInterval);
}
}
}
10. 物体销毁
这个脚本使物体在一定时间后自动销毁,或者通过点击销毁,适用于临时存在的物体。
using UnityEngine;
public class DestroyObject : MonoBehaviour
{
public float destroyTime = 5.0f;
void Start()
{
// 设置物体在一定时间后销毁
Destroy(gameObject, destroyTime);
}
void OnMouseDown()
{
// 点击物体时立即销毁
Destroy(gameObject);
}
}
11. 简单的射击系统
这个脚本实现了一个简单的射击系统,适用于玩家角色的射击功能。
using UnityEngine;
public class ShootingSystem : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletSpeed = 20f;
public float fireRate = 0.5f;
private float nextTimeToFire = 0f;
void Update()
{
// 检查是否可以射击
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
// 射击并设置下一次射击时间
Shoot();
nextTimeToFire = Time.time + 1f / fireRate;
}
}
void Shoot()
{
// 实例化子弹
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
// 设置子弹速度
Rigidbody rb = bullet.GetComponent<Rigidbody>();
rb.velocity = rb.transform.forward * bulletSpeed;
}
}
12. 子弹销毁
这个脚本使子弹在碰到物体或达到最大生命周期时销毁。
using UnityEngine;
public class BulletDestroy : MonoBehaviour
{
public float bulletLifeTime = 3f;
void Start()
{
// 设置子弹在一定时间后销毁
Destroy(gameObject, bulletLifeTime);
}
void OnCollisionEnter(Collision collision)
{
// 子弹碰到物体时销毁
Destroy(gameObject);
}
}
13. 简单的动画控制
这个脚本通过动画控制器控制角色的行走和跳跃动画。
using UnityEngine;
public class AnimatorControl : MonoBehaviour
{
public Animator animator;
public string walkParameter = "IsWalking";
public string jumpParameter = "IsJumping";
void Update()
{
// 控制行走动画
float horizontal = Input.GetAxis("Horizontal");
animator.SetBool(walkParameter, Mathf.Abs(horizontal) > 0.1f);
// 控制跳跃动画
if (Input.GetKeyDown(KeyCode.Space))
{
animator.SetTrigger(jumpParameter);
}
}
}
14. 音效播放
这个脚本用于播放音效,适用于游戏中的音效需求。
using UnityEngine;
public class SoundEffectPlayer : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip jumpSound;
public AudioClip shootSound;
public void PlayJumpSound()
{
// 播放跳跃音效
audioSource.PlayOneShot(jumpSound);
}
public void PlayShootSound()
{
// 播放射击音效
audioSource.PlayOneShot(shootSound);
}
}
15. UI文本更新
这个脚本用于更新UI文本,显示游戏分数或其他信息。
using UnityEngine;
using UnityEngine.UI;
public class UITextUpdate : MonoBehaviour
{
public Text scoreText;
public int score = 0;
void Update()
{
// 更新UI文本显示分数
scoreText.text = "Score: " + score;
}
public void AddScore(int points)
{
// 增加分数
score += points;
}
}
16. 简单的触发器激活
这个脚本通过触发器控制目标物体的激活状态。
using UnityEngine;
public class TriggerActivation : MonoBehaviour
{
public GameObject objectToActivate;
public bool isActive = false;
void OnTriggerEnter(Collider other)
{
// 进入触发器时激活目标物体
if (other.CompareTag("Player"))
{
isActive = true;
objectToActivate.SetActive(true);
}
}
void OnTriggerExit(Collider other)
{
// 退出触发器时禁用目标物体
if (other.CompareTag("Player"))
{
isActive = false;
objectToActivate.SetActive(false);
}
}
}
17. 随机颜色变化
这个脚本使物体定期随机改变颜色,适用于视觉效果。
using UnityEngine;
public class RandomColorChange : MonoBehaviour
{
public float changeInterval = 1.0f;
private Renderer rendererComponent;
void Start()
{
rendererComponent = GetComponent<Renderer>();
// 开始协程,定期改变颜色
StartCoroutine(ChangeColorRoutine());
}
IEnumerator ChangeColorRoutine()
{
while (true)
{
// 设置随机颜色
rendererComponent.material.color = new Color(
Random.Range(0f, 1f),
Random.Range(0f, 1f),
Random.Range(0f, 1f)
);
// 等待一段时间
yield return new WaitForSeconds(changeInterval);
}
}
}
18. 物体缩放
这个脚本通过鼠标输入控制物体的缩放。
using UnityEngine;
public class ObjectScale : MonoBehaviour
{
public float scaleSpeed = 2.0f;
public float targetScale = 2.0f;
private Vector3 originalScale;
void Start()
{
originalScale = transform.localScale;
}
void Update()
{
// 根据鼠标输入缩放物体
float scaleX = originalScale.x + Input.GetAxis("Mouse X") * scaleSpeed * Time.deltaTime;
float scaleY = originalScale.y + Input.GetAxis("Mouse Y") * scaleSpeed * Time.deltaTime;
// 确保缩放不超过目标值
scaleX = Mathf.Clamp(scaleX, originalScale.x, targetScale);
scaleY = Mathf.Clamp(scaleY, originalScale.y, targetScale);
transform.localScale = new Vector3(scaleX, scaleY, originalScale.z);
}
}
19. 简单的物品收集系统
这个脚本实现了一个简单的物品收集系统,适用于游戏中的收集物。
using UnityEngine;
public class CollectItem : MonoBehaviour
{
public int itemValue = 1;
public string itemName = "Item";
public AudioClip collectSound;
private AudioSource audioSource;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider other)
{
// 当玩家碰到物品时收集
if (other.CompareTag("Player"))
{
// 播放收集音效
audioSource.PlayOneShot(collectSound);
// 通知玩家收集物品
PlayerInventory playerInventory = other.GetComponent<PlayerInventory>();
if (playerInventory != null)
{
playerInventory.AddItem(itemName, itemValue);
}
// 销毁物品
Destroy(gameObject);
}
}
}
20. 玩家背包系统
这个脚本实现了一个简单的玩家背包系统,用于存储和管理收集的物品。
using UnityEngine;
using System.Collections.Generic;
public class PlayerInventory : MonoBehaviour
{
public List<string> items = new List<string>();
public int totalValue = 0;
public void AddItem(string itemName, int value)
{
// 添加物品到背包
items.Add(itemName);
totalValue += value;
// 更新UI显示
if (GetComponent<UIInventory>() != null)
{
GetComponent<UIInventory>().UpdateUI();
}
}
public void RemoveItem(string itemName, int value)
{
// 从背包中移除物品
if (items.Contains(itemName))
{
items.Remove(itemName);
totalValue -= value;
// 更新UI显示
if (GetComponent<UIInventory>() != null)
{
GetComponent<UIInventory>().UpdateUI();
}
}
}
}
21. UI更新背包
这个脚本用于更新UI,显示玩家背包中的物品和总价值。
using UnityEngine;
using UnityEngine.UI;
public class UIInventory : MonoBehaviour
{
public Text itemsText;
public Text valueText;
private PlayerInventory inventory;
void Start()
{
inventory = GetComponent<PlayerInventory>();
UpdateUI();
}
public void UpdateUI()
{
// 更新UI显示背包内容
itemsText.text = "Items: " + string.Join(", ", inventory.items);
valueText.text = "Total Value: " + inventory.totalValue;
}
}
22. 简单的对话系统
这个脚本实现了一个简单的对话系统,用于游戏中的对话展示。
using UnityEngine;
using UnityEngine.UI;
public class DialogueSystem : MonoBehaviour
{
public Text dialogueText;
public string[] dialogueLines;
private int currentLine = 0;
void Start()
{
// 显示第一条对话
dialogueText.text = dialogueLines[currentLine];
}
void Update()
{
// 按空格键显示下一条对话
if (Input.GetKeyDown(KeyCode.Space))
{
currentLine++;
if (currentLine < dialogueLines.Length)
{
dialogueText.text = dialogueLines[currentLine];
}
else
{
// 对话结束,隐藏面板
gameObject.SetActive(false);
}
}
}
}
23. 粒子系统控制
这个脚本控制粒子系统的播放状态和发射速率,适用于视觉效果。
using UnityEngine;
public class ParticleControl : MonoBehaviour
{
public ParticleSystem particles;
public bool isPlaying = true;
void Update()
{
// 根据键盘输入控制粒子系统播放/暂停
if (Input.GetKeyDown(KeyCode.P))
{
if (isPlaying)
{
particles.Pause();
}
else
{
particles.Play();
}
isPlaying = !isPlaying;
}
// 根据滑轮输入调整粒子发射速率
ParticleSystem.MainModule main = particles.main;
float emissionRate = main.startLifetime;
emissionRate += Input.GetAxis("Mouse ScrollWheel") * 10;
emissionRate = Mathf.Clamp(emissionRate, 0, 100);
main.startLifetime = emissionRate;
}
}
24. 简单的摄像机抖动
这个脚本实现摄像机抖动效果,适用于爆炸或撞击场景。
using UnityEngine;
using System.Collections;
public class CameraShake : MonoBehaviour
{
public float duration = 1.0f;
public float magnitude = 0.5f;
private Vector3 originalPosition;
void Start()
{
originalPosition = transform.localPosition;
}
public void Shake()
{
// 开始摄像机抖动
StartCoroutine(ShakeRoutine());
}
IEnumerator ShakeRoutine()
{
float elapsed = 0f;
while (elapsed < duration)
{
// 随机抖动摄像机
float x = Random.Range(-1f, 1f) * magnitude;
float y = Random.Range(-1f, 1f) * magnitude;
transform.localPosition = originalPosition + new Vector3(x, y, 0f);
elapsed += Time.deltaTime;
yield return null;
}
// 恢复摄像机原始位置
transform.localPosition = originalPosition;
}
}
25. 简单的状态机
这个脚本实现一个简单状态机,用于控制角色的不同状态。
using UnityEngine;
public class SimpleStateMachine : MonoBehaviour
{
public enum State { Idle, Walking, Running, Jumping }
private State currentState = State.Idle;
void Update()
{
// 根据输入改变状态
switch (currentState)
{
case State.Idle:
if (Input.GetKeyDown(KeyCode.W))
{
currentState = State.Walking;
Debug.Log("State changed to Walking");
}
break;
case State.Walking:
if (Input.GetKey(KeyCode.LeftShift))
{
currentState = State.Running;
Debug.Log("State changed to Running");
}
else if (Input.GetKeyDown(KeyCode.Space))
{
currentState = State.Jumping;
Debug.Log("State changed to Jumping");
}
break;
case State.Running:
if (!Input.GetKey(KeyCode.LeftShift))
{
currentState = State.Walking;
Debug.Log("State changed to Walking");
}
else if (Input.GetKeyDown(KeyCode.Space))
{
currentState = State.Jumping;
Debug.Log("State changed to Jumping");
}
break;
case State.Jumping:
if (!Input.GetKey(KeyCode.Space))
{
currentState = State.Walking;
Debug.Log("State changed to Walking");
}
break;
}
}
}
26. 物理材质应用
这个脚本应用不同的物理材质到物体上,影响其摩擦力等物理特性。
using UnityEngine;
public class PhysicsMaterialApplier : MonoBehaviour
{
public PhysicMaterial[] materials;
public float frictionRange = 1.0f;
private int currentMaterialIndex = 0;
private Renderer rendererComponent;
void Start()
{
rendererComponent = GetComponent<Renderer>();
ApplyMaterial(0);
}
void Update()
{
// 根据键盘输入改变物理材质
if (Input.GetKeyDown(KeyCode.Alpha1))
{
ApplyMaterial(0);
}
else if (Input.GetKeyDown(KeyCode.Alpha2))
{
ApplyMaterial(1);
}
else if (Input.GetKeyDown(KeyCode.Alpha3))
{
ApplyMaterial(2);
}
}
void ApplyMaterial(int index)
{
// 应用物理材质
if (index >= 0 && index < materials.Length)
{
currentMaterialIndex = index;
GetComponent<Collider>().material = materials[index];
// 改变物体颜色表示当前材质
rendererComponent.material.color = materials[index].color;
}
}
}
27. 简单的AI巡逻系统
这个脚本使AI角色在巡逻点之间移动,实现简单的AI巡逻行为。
using UnityEngine;
using System.Collections;
public class AIPatrol : MonoBehaviour
{
public Transform[] patrolPoints;
public float moveSpeed = 2.0f;
private int currentPoint = 0;
private bool reachedDestination = true;
void Start()
{
// 随机选择一个初始巡逻点
currentPoint = Random.Range(0, patrolPoints.Length);
}
void Update()
{
if (reachedDestination)
{
// 到达一个巡逻点后选择下一个
currentPoint = (currentPoint + 1) % patrolPoints.Length;
reachedDestination = false;
}
// 移动到当前巡逻点
transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
// 检查是否到达巡逻点
if (Vector3.Distance(transform.position, patrolPoints[currentPoint].position) < 0.1f)
{
reachedDestination = true;
}
}
}
28. 鼠标锁定与解锁
这个脚本控制鼠标是否被锁定在游戏视图内,适用于第一人称视角游戏。
using UnityEngine;
public class MouseLock : MonoBehaviour
{
public bool lockMouse = true;
void Update()
{
// 根据键盘输入锁定/解锁鼠标
if (Input.GetKeyDown(KeyCode.M))
{
lockMouse = !lockMouse;
LockMouse(lockMouse);
}
}
void OnGUI()
{
// 显示鼠标锁定状态
GUI.Label(new Rect(10, 10, 200, 20), "Mouse locked: " + lockMouse);
}
void LockMouse(bool lockIt)
{
// 锁定/解锁鼠标
Cursor.lockState = lockIt ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !lockIt;
}
}
29. 简单的阶梯攀爬
这个脚本实现简单的阶梯攀爬功能,适用于平台游戏。
using UnityEngine;
public class LadderClimb : MonoBehaviour
{
public float climbSpeed = 5.0f;
public float ladderTopY = 10.0f;
public float ladderBottomY = 0.0f;
private bool isClimbing = false;
private float currentY = 0.0f;
void Update()
{
// 检查是否靠近梯子
if (Input.GetKeyDown(KeyCode.E) && IsNearLadder())
{
isClimbing = true;
currentY = transform.position.y;
}
// 攀爬梯子
if (isClimbing)
{
float movement = Input.GetAxis("Vertical") * climbSpeed * Time.deltaTime;
currentY += movement;
currentY = Mathf.Clamp(currentY, ladderBottomY, ladderTopY);
transform.position = new Vector3(transform.position.x, currentY, transform.position.z);
// 检查是否离开梯子
if (Input.GetKeyDown(KeyCode.Q))
{
isClimbing = false;
}
}
}
bool IsNearLadder()
{
// 检查玩家是否靠近梯子
Collider[] colliders = Physics.OverlapSphere(transform.position, 2.0f);
foreach (Collider collider in colliders)
{
if (collider.CompareTag("Ladder"))
{
return true;
}
}
return false;
}
}
30. 网络同步示例(Unity Netcode)
这个脚本展示了如何使用Unity Netcode进行网络同步,适用于多人游戏。
using Unity.Netcode;
using UnityEngine;
public class NetworkObjectExample : NetworkBehaviour
{
[SerializeField] private NetworkVariable<int> score = new NetworkVariable<int>();
[SerializeField] private NetworkVariable<bool> isReady = new NetworkVariable<bool>();
public override void OnNetworkSpawn()
{
// 当对象在网络上生成时调用
if (!IsOwner) return;
// 初始化网络变量
score.Value = 0;
isReady.Value = false;
}
[ServerRpc]
public void AddScoreServerRpc(int points)
{
// 服务器端方法,增加分数
score.Value += points;
}
[ClientRpc]
public void UpdateReadyStatusClientRpc(bool ready)
{
// 客户端方法,更新准备状态
isReady.Value = ready;
}
public void OnShootButton()
{
// 客户端调用服务器方法
AddScoreServerRpc(10);
}
public void OnReadyButton()
{
// 客户端调用服务器方法
UpdateReadyStatusClientRpc(true);
}
void Update()
{
// 仅在服务器端更新UI
if (IsServer)
{
Debug.Log("Server: Current Score = " + score.Value);
Debug.Log("Server: Player Ready? " + isReady.Value);
}
}
}
以上30个代码示例涵盖了Unity开发中常见的功能和场景,从简单的物体移动到复杂的网络同步。通过学习和应用这些示例,你可以提高自己的Unity开发技能,为你的游戏项目增添更多功能和趣味。希望这些代码能够帮助你在Unity开发的道路上越走越远!