Unity API通读 UnityEngine.MonoBehaviour

本文深入探讨了Unity引擎中核心组件MonoBehaviour的功能与用法,包括其作为脚本基类的角色,以及Start、Update等关键方法的作用。同时,介绍了MonoBehaviour的属性如runInEditMode和useGUILayout,并提供了官方文档链接。

MonoBehaviour

MonoBehaviour是每个Unity脚本派生出来的基类
当你使用C#时 必须明确的继承MonoBehaviour
此类不支持空条件运算符(null-conditional operator)(?.)和空合并运算符(null-coalescing operator)(??)
UnityEngine类 继承自Behaviour 实现接口UnityEngine.CoreModule

注意 在Unity编辑器上有一个禁用MonoBehaviour的复选框 未勾选时禁用功能 如果脚本中没有这些函数 编辑器讲不显示复选框
方法包括:Start() Update() FixedUpdate() LateUpdate() OnGUI() OnDisable() OnEnable()

·属性
runInEditMode
允许在编辑模式下运行MonoBehavior的特定实例(仅在编辑器中可用)
如果存在ExecuteInEditMode 这个属性一直为true
如果不存在ExecuteInEditMode 这个属性可以被修改
useGUILayout
禁用这个属性可以跳过GUI布局阶段

官方文档 version 2018.3
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html

using UnityEngine; using System.Collections; using UnityEngine.UI; using ConsoleTestWindows; using XLua; namespace LuaFramework { /// <summary> /// </summary> [LuaCallCSharp] public class Main : MonoBehaviour { private ConsoleWindow consoleWin; //public string ResUrl; public string WebUrl; public string AgentID; public string UIVersion; public int GameCode; public bool updateMode; void Start() { AppConst.GameCode = GameCode; #if UNITY_EDITOR AppConst.UpdateMode = updateMode; AppConst.UIVersion = UIVersion; AppConst.WebUrl = WebUrl; AppConst.AgentID = AgentID; consoleWin = new ConsoleWindow(); consoleWin.Initialize(); consoleWin.SetTitle("Lua_Dating"); #endif //Debug.LogError("Main Start**********************************"); //System.Console.OutputEncoding = System.Text.Encoding.Default; AppFacade.Instance.StartUp(); //启动游戏 } public static void consoleprint(string str, int color) { switch(color) { case 1: System.Console.ForegroundColor = System.ConsoleColor.Black; break; case 2: System.Console.ForegroundColor = System.ConsoleColor.DarkBlue; break; case 3: System.Console.ForegroundColor = System.ConsoleColor.DarkGreen; break; case 4: System.Console.ForegroundColor = System.ConsoleColor.DarkCyan; break; case 5: System.Console.ForegroundColor = System.ConsoleColor.DarkRed; break; case 6: System.Console.ForegroundColor = System.ConsoleColor.DarkMagenta; break; case 7: System.Console.ForegroundColor = System.ConsoleColor.DarkYellow; break; case 8: System.Console.ForegroundColor = System.ConsoleColor.Gray; break; case 9: System.Console.ForegroundColor = System.ConsoleColor.DarkGray; break; case 10: System.Console.ForegroundColor = System.ConsoleColor.Blue; break; case 11: System.Console.ForegroundColor = System.ConsoleColor.Green; break; case 12: System.Console.ForegroundColor = System.ConsoleColor.Cyan; break; case 13: System.Console.ForegroundColor = System.ConsoleColor.Red; break; case 14: System.Console.ForegroundColor = System.ConsoleColor.Magenta; break; case 15: System.Console.ForegroundColor = System.ConsoleColor.Yellow; break; default: System.Console.ForegroundColor = System.ConsoleColor.White; break; } System.Console.WriteLine(str); } private void OnDestroy() { #if UNITY_EDITOR consoleWin.Shutdown(); #endif } } }
07-19
using UnityEngine; using UnityEngine.UI; public class ConnectionManager : MonoBehaviour { [Header(“UI Settings”)] public GameObject errorPanel; // 错误提示面板 public Text errorMessage; // 错误信息文本 public Button confirmButton; // 确认按钮 private GameObject _firstSelected; private LineRenderer _currentLine; private void Start() { // 初始化UI errorPanel.SetActive(false); confirmButton.onClick.AddListener(() => errorPanel.SetActive(false)); } private void Update() { // 保持连线位置更新(如果需要动态跟随) if (_currentLine != null && _firstSelected != null) { _currentLine.SetPosition(0, _firstSelected.transform.position); } } private void OnMouseDown() { GameObject clickedObj = gameObject; // 第一次选择 if (_firstSelected == null) { if (clickedObj.CompareTag("Model1") || clickedObj.CompareTag("Model2")) { _firstSelected = clickedObj; HighlightObject(_firstSelected); } return; } // 第二次选择 if (CheckValidConnection(_firstSelected, clickedObj)) { CreateConnection(_firstSelected.transform, clickedObj.transform); } else { ShowError("无效连接!只允许连接模型1和模型2"); } // 重置选择 ClearSelection(); } bool CheckValidConnection(GameObject a, GameObject b) { // 有效组合:1-2 或 2-1 return (a.CompareTag("Model1") && b.CompareTag("Model2")) || (a.CompareTag("Model2") && b.CompareTag("Model1")); } void CreateConnection(Transform start, Transform end) { // 创建连线对象 GameObject lineObj = new GameObject("ConnectionLine"); _currentLine = lineObj.AddComponent<LineRenderer>(); // 配置连线属性 _currentLine.startWidth = 0.1f; _currentLine.endWidth = 0.1f; _currentLine.material = new Material(Shader.Find("Sprites/Default")); _currentLine.startColor = Color.red; _currentLine.endColor = Color.red; // 设置不可删除标记 DontDestroyOnLoad(lineObj); // 设置位置 _currentLine.SetPositions(new Vector3[] { start.position, end.position }); } void HighlightObject(GameObject obj) { // 临时高亮效果(可选) obj.GetComponent<Renderer>().material.color = Color.yellow; } void ClearSelection() { if (_firstSelected != null) { _firstSelected.GetComponent<Renderer>().material.color = Color.white; _firstSelected = null; } } void ShowError(string message) { errorMessage.text = message; errorPanel.SetActive(true); } } 这个代码有错误吗,如果有,怎么在功能不变情况下改好,给我一个完整的代码
04-02
以下是对游戏特效实现技术的深入分析与优化建议,结合最新技术趋势与工程实践经验: 一、火焰与描边融合的进阶实现 1. 屏幕空间惯性补偿算法 - 动态坐标系转换: hlsl float3 localVelocity = UnityObjectToWorldDir(v.normal) * _Speed; float3 screenVelocity = ComputeScreenPos(UNITY_MATRIX_MV * float4(localVelocity, 0));   - 惯性衰减曲线: python def motionCurve(time): return smoothstep(0, 1, time) * pow(1 - time, 2.0)   2. Billboard动态衔接方案 - 三阶段混合过渡: - 初始阶段:Billboard面片与模型法线对齐 - 过渡阶段:基于距离的混合权重插值 - 稳定阶段:完全屏幕空间控制 3. 分层渲染策略 - 火焰层分离: csharp // 分层渲染队列设置 renderer.sortingLayerID = SortingLayer.NameToID("FireLayer"); renderer.sortingOrder = 100;   二、火焰效果的多维度优化 1. 动态面片管理系统 - 四叉树空间划分: csharp public class QuadTree { public void Insert(FireBillboard billboard) { // 根据屏幕坐标划分层级 } }   2. 光照烘焙技术 - 动态GI集成: hlsl float3 indirectLight = SAMPLE_GI(UNITY_MATRIX_IT_MV, i.normal);   3. 物理模拟增强 - 流体-刚体耦合: csharp Rigidbody rb = GetComponent<Rigidbody>(); rb.AddForce(fluidVelocity * _Density);   三、Shader开发的工程化实践 1. 材质变体管理 - 着色器变体剔除: csharp ShaderVariantCollection svc = new ShaderVariantCollection(); svc.Add("UNITY_PASS_FORWARDBASE");   2. 性能分析工具链 - GPU捕获分析: csharp // 关键帧标记 Gfx.WaitForPresent(); UnityEngine.Profiling.Profiler.BeginSample("FireShader");   3. 跨平台优化 - 纹理压缩策略: csharp #if UNITY_ANDROID textureCompression = TextureCompression.ASTC_RGBA_8x8; #elif UNITY_IOS textureCompression = TextureCompression.PVRTC_RGBA4; #endif   四、Blender与引擎协同工作流 1. 实时渲染优化 - Grease Pencil实时预览: python # 脚本自动生成Billboard面片 import bpy bpy.ops.mesh.primitive_plane_add(size=0.5)   2. 多通道输出方案 - AOV节点配置: plaintext RenderLayer → ID Mask → Alpha Over → Composite   3. 资产导出规范 - FBX动画烘焙: csharp // 骨骼动画烘焙设置 fbxExporter.animationType = FBXExporter.AnimationType.LOCAL;   五、前沿技术探索 1. 神经辐射场(NERF)应用 - 动态火焰重建: python # NeRF训练脚本片段 def train_nerf(): dataset = NeRFDataset("fire_data") model = NeRFNetwork() optimizer = Adam(model.parameters(), lr=5e-4)   2. 体积雾效技术 - GPU加速的烟雾模拟: hlsl // 密度场更新 float3 vorticity = cross(ddx(velocity), ddy(velocity));   3. 机器学习辅助生成 - GAN生成火焰纹理: python # PyTorch GAN示例 class FireGAN(nn.Module): def __init__(self): super().__init__() self.generator = nn.Sequential( nn.Conv2d(100, 512, 4, 1, 0), nn.ReLU(True), # ... )   六、质量验证体系 1. 自动化测试框架 - 冒烟测试脚本: csharp public class SmokeTest : MonoBehaviour { void Start() { Assert.IsTrue(FlameEffect.isInitialized, "Fire system not initialized"); } }   2. 视觉回归测试 - 像素差异分析: python # Python图像比较 from PIL import Image, ImageChops diff = ImageChops.difference(img1, img2) assert diff.getbbox() is None, "Visual regression detected"   3. 极端条件测试 - 压力测试场景: csharp public class StressTest : MonoBehaviour { void SpawnFire() { for(int i=0; i<1000; i++) { Instantiate(firePrefab, Random.insideUnitSphere, Quaternion.identity); } } }   七、行业趋势观察 1. 元宇宙场景中的动态特效:需支持10万+并发粒子系统 2. 虚实融合渲染:AR/VR设备中的实时遮挡处理 3. 可持续性优化:Shader代码的碳足迹计算 4. AI驱动的美术生产:从概念设计到代码生成的全流程自动化 建议建立特效资源管理系统,实现资产版本控制、性能数据追踪和跨项目复用。对于复杂效果,可采用"预计算+实时修正"的混合渲染模式,在保持视觉效果的同时优化运行效率。
03-28
using UnityEngine; using UnityEngine.SceneManagement; public class VictoryManager : MonoBehaviour { [Header(“UI Settings”)] [Tooltip(“胜利UI面板”)] public GameObject victoryUI; [Header("Scene Settings")] [Tooltip("指定生效的场景名称")] public string targetSceneName ; [Header("Audio Settings")] [Tooltip("背景音乐音频源")] public AudioSource backgroundMusic; private bool isVictory = false; private float previousMusicVolume; private void Awake() { // 确保只在目标场景生效 if (SceneManager.GetActiveScene().name != targetSceneName) { Destroy(gameObject); return; } // 检查当前场景是否已存在 VictoryManager VictoryManager[] existingManagers = FindObjectsOfType<VictoryManager>(); foreach (VictoryManager manager in existingManagers) { if (manager != this) { Destroy(manager.gameObject); // 销毁重复对象 } } // 初始化UI引用 if (victoryUI == null) { Debug.LogError("未分配 victoryUI!请拖入Inspector。"); } } private void Start() { // 确保UI初始状态 if (victoryUI != null) { victoryUI.SetActive(false); } else { Debug.LogError("victoryUI未分配!", this); // 尝试自动查找 victoryUI = GameObject.Find("VictoryUI"); // 根据实际UI名称修改 if (victoryUI != null) { victoryUI.SetActive(false); } } // 自动查找背景音乐 if (backgroundMusic == null) { backgroundMusic = FindObjectOfType<AudioSource>(); if (backgroundMusic != null && backgroundMusic.playOnAwake) { Debug.Log("自动找到背景音乐: " + backgroundMusic.name); } } } private void Update() { if (isVictory && Input.GetKeyDown(KeyCode.Escape)) { ResumeGame(); } } public void ShowVictoryUI() { if (victoryUI != null && !isVictory) { victoryUI.SetActive(true); Time.timeScale = 0f; isVictory = true; Cursor.lockState = CursorLockMode.None; Cursor.visible = true; if (backgroundMusic != null && backgroundMusic.isPlaying) { previousMusicVolume = backgroundMusic.volume; backgroundMusic.volume = 0; } } } public void ResumeGame() { if (victoryUI != null && isVictory) { victoryUI.SetActive(false); Time.timeScale = 1f; isVictory = false; if (backgroundMusic != null) { backgroundMusic.volume = previousMusicVolume; } } } }这是我的胜利代码,两个场景,一个场景开局胜利UI能隐藏正常的,一个不能错误的,怎么解决
04-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值