实例1:基础对象创建与销毁
Unity中的GameObject是构成游戏世界的基本元素。以下是一个简单的实例,展示如何创建和销毁对象。
using UnityEngine;
public class GameObjectManagement : MonoBehaviour
{
void Start()
{
// 创建一个新的GameObject
GameObject newObject = new GameObject("NewObject");
// 销毁一个GameObject
Destroy(newObject, 2.0f);
}
}
实例2:游戏对象位置变换
移动游戏对象到指定位置。
using UnityEngine;
public class MoveObject : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// 移动到指定位置
transform.position = new Vector3(10.0f, 0.0f, 0.0f);
}
}
}
实例3:添加组件
在运行时动态给对象添加组件。
using UnityEngine;
public class AddComponent : MonoBehaviour
{
void Start()
{
// 添加Rigidbody组件
Rigidbody rb = gameObject.AddComponent<Rigidbody>();
// 设置刚体质量
rb.mass = 10.0f;
}
}
实例4:碰撞检测
检测游戏对象间的碰撞。
using UnityEngine;
public class CollisionDetection : MonoBehaviour
{
void OnCollisionEnter(Collision collision)
{
Debug.Log("Collision with " + collision.gameObject.name);
}
}
实例5:物理力的应用
施加力使游戏对象产生物理反应。
using UnityEngine;
public class ApplyForce : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Rigidbody rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * 10.0f, ForceMode.Impulse);
}
}
}
实例6:玩家控制
实现一个简单的玩家控制。
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5.0f;
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontal, 0.0f, vertical) * moveSpeed * Time.deltaTime;
transform.Translate(movement);
}
}
实例7:动画控制
通过脚本控制动画播放。
using UnityEngine;
public class AnimationControl : MonoBehaviour
{
private Animator anim;
void Start()
{
anim = GetComponent<Animator>();
}
public void PlayAnimation(string animName)
{
anim.Play(animName);
}
}
实例8:音频播放
在游戏运行时播放音频。
using UnityEngine;
public class AudioPlayer : MonoBehaviour
{
public AudioClip jumpSound;
void PlaySound()
{
AudioSource.PlayClipAtPoint(jumpSound, transform.position);
}
}
实例9:UI交互
通过按钮点击显示文本。
using UnityEngine;
using UnityEngine.UI;
public class ButtonText : MonoBehaviour
{
public Text text;
void OnClick()
{
text.text = "Button Clicked!";
}
}
实例10:状态管理
管理游戏对象的状态。
public class StateManager : MonoBehaviour
{
public enum State { Idle, Running, Jumping }
private State currentState = State.Idle;
void Update()
{
switch (currentState)
{
case State.Idle:
// 状态逻辑
break;
case State.Running:
// 状态逻辑
break;
case State.Jumping:
// 状态逻辑
break;
}
}
}
实例11:时间管理
实现倒计时功能。
using UnityEngine;
public class Timer : MonoBehaviour
{
public float countdownTime = 10.0f;
void Update()
{
countdownTime -= Time.deltaTime;
if (countdownTime <= 0)
{
Debug.Log("Time's up!");
}
}
}
实例12:粒子系统控制
控制粒子系统的播放和停止。
using UnityEngine;
public class ParticleControl : MonoBehaviour
{
public ParticleSystem particleSystem;
public void PlayParticleSystem()
{
particleSystem.Play();
}
public void StopParticleSystem()
{
particleSystem.Stop();
}
}
实例13:摄像机控制
控制摄像机跟随游戏对象。
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform target;
public float smoothing = 5f;
void LateUpdate()
{
Vector3 smoothPosition = Vector3.Lerp(transform.position, target.position, smoothing * Time.deltaTime);
transform.position = smoothPosition;
}
}
实例14:网络同步
实现简单的网络同步。
using UnityEngine;
public class NetworkSync : MonoBehaviour
{
public float networkDelay = 0.1f;
void Update()
{
// 假设有一个网络延迟
if (Network.time - Time.time > networkDelay)
{
transform.position = NetworkTransform.position;
}
}
}
实例15:资源管理
动态加载资源。
using UnityEngine;
public class ResourceManager : MonoBehaviour
{
public string resourcePath = "Assets/MyResources/MyObject";
void Start()
{
// 加载资源
GameObject resource = Resources.Load<GameObject>(resourcePath);
Instantiate(resource, Vector3.zero, Quaternion.identity);
}
}
实例16:多线程编程
使用Unity的多线程来提高性能。
using System.Threading;
using UnityEngine;
public class MultiThreadedExecution : MonoBehaviour
{
Thread myThread;
void Start()
{
// 创建一个新线程
myThread = new Thread(new ThreadStart(ExecuteThreadFunction));
myThread.Start();
}
void ExecuteThreadFunction()
{
// 线程中的代码
}
}
实例17:脚本调试
使用断点和日志输出调试信息。
using UnityEngine;
public class Debugging : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Button Pressed!");
Debug.Break();
}
}
}
实例18:事件系统
使用事件系统来管理游戏事件。
using UnityEngine;
public class EventSystem : MonoBehaviour
{
public delegate void MyEvent();
public static event MyEvent myEvent;
void OnEnable()
{
myEvent += MyEventMethod;
}
void OnDisable()
{
myEvent -= MyEventMethod;
}
void MyEventMethod()
{
Debug.Log("Event Triggered!");
}
}
实例19:序列化属性
在脚本中保存和加载属性。
using UnityEngine;
[Serializable]
public class MyData
{
public int intValue;
public float floatValue;
}
public class SaveData : MonoBehaviour
{
public MyData myData;
void Start()
{
// 保存数据
PlayerPrefs.SetInt("intValue", myData.intValue);
PlayerPrefs.SetFloat("floatValue", myData.floatValue);
// 加载数据
myData.intValue = PlayerPrefs.GetInt("intValue");
myData.floatValue = PlayerPrefs.GetFloat("floatValue");
}
}
实例20:动画曲线
使用动画曲线来创建非线性的动画。
using UnityEngine;
public class AnimationCurveExample : MonoBehaviour
{
private AnimationCurve animationCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 10));
void Update()
{
// 计算动画曲线在0到1之间的值
float value = animationCurve.Evaluate(Time.time);
Debug.Log(value);
}
}
实例21:物理模拟
使用物理模拟来创建更真实的游戏体验。
using UnityEngine;
public class PhysicsSimulation : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// 施加力使对象产生物理反应
Rigidbody rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.up * 10.0f, ForceMode.Impulse);
}
}
}
实例22:网络编程
实现基于网络的玩家对战。
using UnityEngine;
public class NetworkCombat : MonoBehaviour
{
public float attackRange = 5.0f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// 检查网络中的玩家是否在攻击范围内
NetworkPlayer player = Network.GetClosestPlayer(transform.position, attackRange);
if (player != null)
{
// 攻击玩家
player.health -= 10;
}
}
}
}
实例23:文本解析
解析并显示文本数据。
using System.Collections.Generic;
using UnityEngine;
public class TextParser : MonoBehaviour
{
public TextAsset textAsset;
public List<string> lines = new List<string>();
void Start()
{
// 解析文本数据
string[] textLines = textAsset.text.Split('\n');
lines.AddRange(textLines);
}
}
实例24:数据库操作
使用脚本与数据库进行交互。
using UnityEngine;
using System.Data;
using Mono.Data.Sqlite;
public class DatabaseInteraction : MonoBehaviour
{
public string connectionString = "URI=file:PathToDatabase.db";
void Start()
{
using (IDbConnection dbConnection = new SqliteConnection(connectionString))
{
dbConnection.Open();
IDbCommand dbCommand = dbConnection.CreateCommand();
string sqlQuery = "SELECT * FROM Table";
dbCommand.CommandText = sqlQuery;
IDbDataReader dataReader = dbCommand.ExecuteReader();
while (dataReader.Read())
{
// 读取数据
string name = dataReader.GetString(0);
int value = dataReader.GetInt32(1);
}
}
}
}
实例25:数据结构
使用数据结构来优化内存使用。
using UnityEngine;
using System.Collections.Generic;
public class DataStructureExample : MonoBehaviour
{
public List<int> numbers = new List<int>();
void Start()
{
// 添加数据到列表
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// 获取特定数据
int firstNumber = numbers[0];
Debug.Log(firstNumber);
}
}
实例26:文件操作
读写文件。
using System.IO;
using UnityEngine;
public class FileOperation : MonoBehaviour
{
public string filePath = "PathToMyFile.txt";
void Start()
{
// 写入文件
File.WriteAllText(filePath, "Hello, World!");
// 读取文件
string content = File.ReadAllText(filePath);
Debug.Log(content);
}
}
实例27:加密与解密
使用加密算法来保护敏感数据。
using System;
using System.Security.Cryptography;
using UnityEngine;
public class Encryption : MonoBehaviour
{
private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
private static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold the decrypted text.
string plaintext = null;
// Create an Aes object with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
void Start()
{
// 密钥和IV
byte[] key = Encoding.UTF8.GetBytes("YourKey123");
byte[] iv = Encoding.UTF8.GetBytes("YourIV123");
// 加密
string plainText = "Hello, World!";
byte[] encrypted = EncryptStringToBytes_Aes(plainText, key, iv);
string encryptedString = Convert.ToBase64String(encrypted);
Debug.Log(encryptedString);
// 解密
string decryptedText = DecryptStringFromBytes_Aes(encrypted, key, iv);
Debug.Log(decryptedText);
}
}
实例28:内存管理
优化Unity游戏的内存使用。
using UnityEngine;
public class MemoryManagement : MonoBehaviour
{
void Start()
{
// 避免在内存中创建大量对象
for (int i = 0; i < 1000000; i++)
{
GameObject obj = new GameObject("Object" + i);
Destroy(obj);
}
}
}
实例29:资源优化
优化游戏资源的加载和使用。
using UnityEngine;
public class ResourceOptimization : MonoBehaviour
{
void Start()
{
// 预加载资源
AssetBundle bundle = AssetBundle.LoadFromFile("PathToAssetBundle");
bundle.LoadAllAssets();
bundle.Unload(false);
// 在需要时动态加载资源
GameObject obj = Instantiate(Resources.Load<GameObject>("MyObject"));
Destroy(obj, 5.0f);
}
}
实例30:UI优化
优化Unity UI的性能。
using UnityEngine;
public class UIOptimization : MonoBehaviour
{
void Start()
{
// 使用Canvas Scaler优化UI缩放
CanvasScaler canvasScaler = GetComponent<CanvasScaler>();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
// 使用Canvas Render Mode来优化渲染
canvasScaler.renderMode = RenderMode.ScreenSpaceOverlay;
}
}
实例31:动画优化
优化Unity动画的性能。
using UnityEngine;
public class AnimationOptimization : MonoBehaviour
{
public Animator anim;
void Update()
{
// 使用Update方法而非LateUpdate来减少动画计算
if (Input.GetKeyDown(KeyCode.Space))
{
anim.SetBool("IsRunning", true);
}
}
}
实例32:物理优化
优化Unity物理性能。
using UnityEngine;
public class PhysicsOptimization : MonoBehaviour
{
void Start()
{
// 使用物理层来优化碰撞检测
Physics.IgnoreLayerCollision("LayerA", "LayerB");
// 关闭不必要的物理影响
Rigidbody rb = GetComponent<Rigidbody>();
rb.useGravity = false;
rb.isKinematic = true;
}
}
实例33:网络优化
优化Unity网络性能。
using UnityEngine;
public class NetworkOptimization : MonoBehaviour
{
void Start()
{
// 使用WebSocket来优化网络传输
// 示例代码(假设存在WebSocket接口)
WebSocket webSocket = new WebSocket("wss://example.com/socket");
webSocket.OnMessage += (message) => {
// 处理消息
Debug.Log(message);
};
// 使用网络压缩算法来减少数据大小
// 示例代码(假设存在压缩接口)
string originalString = "This is a long string that we want to compress";
string compressedString = Compress(originalString);
Debug.Log(compressedString);
}
string Compress(string input)
{
// 压缩逻辑
return input;
}
}
实例34:游戏循环优化
优化Unity游戏循环性能。
using UnityEngine;
public class GameLoopOptimization : MonoBehaviour
{
void Update()
{
// 避免在Update方法中进行复杂的计算
if (Input.GetKeyDown(KeyCode.Space))
{
// 使用协程进行复杂的计算
StartCoroutine(ComplexCalculation());
}
}
IEnumerator ComplexCalculation()
{
for (int i = 0; i < 100; i++)
{
// 复杂的计算
yield return null;
}
}
}
实例35:内存池
使用内存池来提高性能。
using UnityEngine;
public class MemoryPool : MonoBehaviour
{
private Queue<GameObject> objectPool = new Queue<GameObject>();
public GameObject CreateObject(GameObject prefab)
{
if (objectPool.Count > 0)
{
GameObject obj = objectPool.Dequeue();
obj.SetActive(true);
return obj;
}
else
{
GameObject obj = Instantiate(prefab);
return obj;
}
}
public void ReturnObject(GameObject obj)
{
obj.SetActive(false);
objectPool.Enqueue(obj);
}
}
实例36:资源加载
优化资源加载。
”`csharp using UnityEngine;
public class ResourceLoading : MonoBehaviour
