12:Repurposing Diffusion-Based Image Generators for Monocular Depth Estimation

简介

官网
在这里插入图片描述
单目深度估计的扩散模型和相关的微调协议。核心原理是利用现代生成图像模型中存储的丰富视觉知识。模型源自于稳定扩散和微调合成数据,可以零样本转移到未见过的数据集,提供最先进的单目深度估计结果。

实现流程

在这里插入图片描述
Marigold微调过程。从预训练的稳定扩散开始,使用原始的稳定扩散VAE将图像 x 和深度 d 编码到潜在空间中。通过优化相对于深度潜在代码的标准扩散目标来微调 U-Net。图像调节是通过在将两个潜在代码输入U-Net之前连接它们来实现的。U-Net的第一层被修改为接受连接的潜在码。

Network Architecture

扩散模型的训练通常非常耗费资源。因此,为了提升训练效率,模型基于预训练的文本到图像LDM (Stable Diffusion v2),该LDM从LAION-5B学习了非常好的图像先验。通过对模型组件的最小更改,将其转换为图像条件深度估计器。

depth enconder and decoder
使用冻结的VAE将图像及其相应的深度图编码到一个潜在空间中,用于训练条件去噪器。考虑到为3通道(RGB)输入设计的编码器接收单通道深度图,将深度图复制到三个通道以模拟RGB图像

此时,深度数据的数据范围在实现仿射不变性方面起着重要作用。

在不改变VAE和潜空间结构的情况下,可以从编码的潜码重构深度图,误差可以忽略不计,即 d ≈ D ( ε ( d ) ) d≈D (\varepsilon(d)) dD(ε(d))。在推断时,在扩散结束时对深度潜码进行一次解码,取三个信道的平均值作为预测深度图。

Adapted denoising U-Net

为了实现对输入图像 x 的潜在去噪器 ϵ θ ( z t ( d ) , z ( x ) , t ) \epsilon_\theta(z_t^{(d)},z^{(x)},t) ϵθ(zt(d),z(x),t) 的调节,沿着特征维度将图像和深度潜在代码连接成单个输入 z t = c a t ( z t ( d ) , z ( x ) ) z_t = cat( z_t^{(d)},z^{(x)} ) zt=cat(zt(d),z(x)) 。然后将潜在去噪器的输入通道加倍以适应扩展的输入 z t z_t zt

为了防止第一层的激活量膨胀并保持预训练结构尽可能忠实,复制输入层的权重张量并将其值除以2

Fine-Tuning Protocol

Affine-invariant depth normalization.

对于真值深度图d,实现了线性归一化,使深度主要落在[−1,1]的值范围内,以匹配VAE的设计输入值范围。这种规范化有两个目的。

  • 它是使用原始的稳定扩散VAE的惯例。
  • 它强制一个独立于数据统计的标准仿射不变深度表示-任何场景必须由具有极端深度值的近和远平面包围。归一化是通过仿射变换实现的

d ˉ = ( d − d 2 d 98 − d 2 − 0.5 ) ∗ 2 \bar{d} = \Big( \frac{d-d_2}{d_{98}-d_2} -0.5 \Big) * 2 dˉ=(d98d2dd20.5)2

其中 d 2 d_2 d2 d 98 d_{98} d98 对应于单个深度图的 2% 和 98% 百分位数。这种归一化允许Marigold专注于纯仿射不变深度估计。

Training on synthetic data.

由于捕获设备的物理限制和传感器的物理特性,真实深度数据集存在深度值缺失的问题。具体来说,相机和反射表面之间的差异会导致激光雷达激光束偏离,这是真实噪声和缺失像素不可避免的来源。

这里只使用合成深度数据集进行训练。与深度归一化的理由一样,这一决定有两个客观原因。

  • 合成深度本质上是密集和完整的,这意味着每个像素都有一个有效的真值深度值,允许将这样的数据输入VAE,它不能处理无效像素的数据。
  • 合成深度是最干净的深度形式,由渲染管道保证。如果我们关于从文本到图像LDM微调可推广深度估计的可能性的假设是正确的,那么合成深度给出了最干净的示例集,并在短微调协议期间减少了梯度更新中的噪声。

因此,剩下的问题是合成数据和真实数据之间的足够多样性或领域差距,这有时会限制泛化能力。正如实验所证明的那样,选择的合成数据集导致了令人印象深刻的零样本转移。

Annealed multi-resolution noise.

先前的研究已经探索了原始DDPM公式的偏差,如非高斯噪声或非马尔可夫时间表捷径。

建议的设置和上面概述的微调协议允许在微调阶段对噪音时间表进行更改

确定了多分辨率噪声和退火时间表的组合,以更快地收敛并大大提高标准DDPM配方的性能。

多分辨率噪声是由多个不同尺度的随机高斯噪声图像叠加而成,这些图像都被上采样到U-Net输入分辨率。

所提出的退火调度在 t = T t = T t=T 的多分辨率噪声和 t = 0 的标准高斯噪声之间进行插值。

Inference

在这里插入图片描述
Marigold推理方案。给定输入图像 x,用原始的稳定扩散VAE将其编码为潜码 z ( x ) z^{(x)} z(x),并与深度潜码 z t ( d ) z^{(d)}_t zt(d)连接,然后在每次去噪迭代中将其交给改进的微调U-Net。在执行 T 步调度后,将得到的深度潜函数 z 0 ( d ) z^{(d)}_0 z0(d) 解码成图像,对图像的3个通道进行平均,得到最终的估计值 d。

Latent diffusion denoising.
将输入图像编码到隐空间中,将深度隐初始化为标准高斯噪声,并以与微调时相同的调度逐步去噪。

经验发现,使用标准高斯噪声初始化比使用多分辨率噪声初始化效果更好,尽管模型是在后者上训练的。

遵循DDIM的方法,用重新间隔的步骤执行非马尔可夫抽样,以加速推理。最后的深度图是使用VAE解码器从潜码解码,并通过平均信道进行后处理。

Test-time ensembling

推理管道的随机性质导致根据 z T ( d ) z^{(d)}_T zT(d) b中的初始化噪声产生不同的预测。利用这一点,提出了以下测试时间集成方案,能够在相同的输入上组合多个推理传递。

对于每个输入样本,可以运行 N 次推理

为了汇总这些仿射不变深度预测 { d ^ 1 , ⋯   , d ^ N } \{ \hat{d}_1, \cdots,\hat{d}_N \} {d^1,,d^N},联合估计相应的尺度 s ^ j \hat{s}_j s^j 和 移位 t ^ i \hat{t}_i t^i,相对于一些标准尺度和范围,以迭代的方式。所提出的目标最小化每对缩放和移位预测 ( d ^ i , d ^ j ) (\hat{d}_i,\hat{d}_j) (d^i,d^j) 之间的距离,其中 d ^ ′ = d ^ × s ^ + t ^ \hat{d}' = \hat{d} \times \hat{s} + \hat{t} d^=d^×s^+t^。在每个优化步骤中,通过采用逐像素的中位数 m(x, y) =中位数 ( d ^ 1 ′ ( x , y ) , … , d ^ N ′ ( x , y ) ) (\hat{d}'_1(x,y),\dots,\hat{d}'_N(x,y)) (d^1(x,y),,d^N(x,y)) 来计算合并深度图 m。增加一个额外的正则化项 R = ∣ m i n ( m ) ∣ + ∣ 1 − m a x ( m ) ∣ R=|min(m)| + |1-max(m)| R=min(m)+∣1max(m),以防止坍缩到平凡解,并加强 m 的单位尺度。因此,目标函数可以写为:
在这里插入图片描述

其中二项式系数 b = ( N 2 ) b=\left( \begin{matrix} N \\ 2 \end{matrix} \right) b=(N2) 表示 N 张图像中图像对可能组合的个数。经过空间对准迭代优化后,将合并深度 m 作为集合预测。

注意,这个集成步骤不需要基本事实来校准独立的预测。该方案通过选择相应的 N,实现了计算效率和预测质量之间的灵活权衡。

Implementation

使用PyTorch实现Marigold,并利用Stable Diffusion v2作为主干,遵循原始的v-objective预训练设置。

禁用文本条件反射,在训练过程中,使用具有1000个扩散步长的DDPM噪声调度器。

在推理时,使用DDIM调度器,只采样50步。对于最终的预测,汇总了具有不同启动噪声的10个推理运行的结果。

训练需要使用批大小为32的18K次迭代。为了适应一个GPU,累积了16步的梯度。使用学习率为 3 ⋅ 1 0 − 5 3·10^{−5} 3105 的Adam优化器。此外,对训练数据应用随机水平翻转增强。在单个Nvidia RTX 4090 GPU卡上训练收敛大约需要 2.5 天。

在这里插入图片描述

  • 21
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Acknowledgments xiii Introduction xv 1. Making Games the Modular Way 1 1.1 Important Programming Concepts.....................................2 1.1.1 Manager and Controller Scripts...............................2 1.1.2 Script Communication.......................................3 1.1.3 Using the Singleton Pattern in Unity...........................5 1.1.4 Inheritance.................................................6 1.1.5 Where to Now?.............................................8 2. Building the Core Game Framework 9 2.1 Controllers and Managers............................................11 2.1.1 Controllers................................................11 2.1.2 Managers.................................................11 2.2 Building the Core Framework Scripts..................................11 2.2.1 BaseGameController.cs.....................................12 2.2.1.1 Script Breakdown................................14 viii Contents 2.2.2 Scene Manager.............................................17 2.2.2.1 Script Breakdown................................17 2.2.3 ExtendedCustomMonoBehavior.cs...........................19 2.2.4 BaseUserManager.cs........................................20 2.2.4.1 Script Breakdown................................22 2.2.5 BasePlayerManager.cs.......................................22 2.2.5.1 Script Breakdown................................23 2.2.6 BaseInputController.cs......................................24 2.2.6.1 Script Breakdown................................26 3. Player Structure 29 3.1 Game-Specific Player Controller......................................31 3.2 Dealing with Input..................................................32 3.3 Player Manager.....................................................35 3.3.1 Script Breakdown..........................................36 3.4 User Data Manager (Dealing with Player Stats Such as Health, Lives, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recipes: Common Components 41 4.1 Introduction.......................................................41 4.2 The Timer Class....................................................43 4.2.1 Script Breakdown..........................................45 4.3 Spawn Scripts......................................................48 4.3.1 A Simple Spawn Controller..................................49 4.3.1.1 Script Breakdown................................52 4.3.2 Trigger Spawner...........................................56 4.3.3 Path Spawner..............................................57 4.3.3.1 Script Breakdown................................61 4.4 Set Gravity.........................................................66 4.5 Pretend Friction—Friction Simulation to Prevent Slipping Around........66 4.5.1 Script Breakdown..........................................68 4.6 Cameras. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 4.6.1 Third-Person Camera.......................................69 4.6.1.1 Script Breakdown................................71 4.6.2 Top-Down Camera.........................................74 4.6.2.1 Script Breakdown................................74 4.7 Input Scripts.......................................................75 4.7.1 Mouse Input...............................................75 4.7.1.1 Script Breakdown................................76 4.7.2 Single Axis Keyboard Input.................................78 4.8 Automatic Self-Destruction Script.....................................79 4.8.1 Script Breakdown..........................................79 4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager.....................................................81 4.10.1 Script Breakdown..........................................82 5. Building Player Movement Controllers 85 5.1 Shoot ’Em Up Spaceship.............................................85 5.2 Humanoid Character................................................91 5.2.1 Script Breakdown..........................................96 5.3 Wheeled Vehicle...................................................106 5.3.1 Script Breakdown.........................................109 5.3.2 Wheel Alignment.........................................114 5.3.3 Script Breakdown.........................................116 6. Weapon Systems 121 6.1 Building the Scripts................................................122 6.1.1 BaseWeaponController.cs..................................122 6.1.1.1 Script Breakdown...............................127 6.1.2 BaseWeaponScript.cs......................................134 6.1.2.1 Script Breakdown...............................138 7. Recipe: Waypoints Manager 143 7.1 Waypoint System..................................................143 8. Recipe: Sound Manager 157 8.1 The Sound Controller...............................................158 8.1.1 Script Breakdown.........................................160 8.2 The Music Player...................................................163 8.2.1 Script Breakdown.........................................165 8.3 Adding Sound to the Weapons.......................................167 9. AI Manager 169 9.1 The AI State Control Script..........................................171 9.2 The Base AI Control Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 9.2.1 Script Breakdown.........................................185 9.3 Adding Weapon Control to the AI Controller..........................206 9.3.1 Script Breakdown.........................................210 10. Menus and User Interface 215 10.1 The Main Menu....................................................215 10.1.1 Script Breakdown.........................................223 10.2 In-Game User Interface.............................................231 x Contents 11. Dish: Lazer Blast Survival 233 11.1 Main Menu Scene..................................................235 11.2 Main Game Scene..................................................236 11.3 Prefabs...........................................................237 11.4 Ingredients........................................................238 11.5 Game Controller...................................................239 11.5.1 Script Breakdown.........................................243 11.6 Player Controller...................................................250 11.6.1 Script Breakdown.........................................253 11.7 Enemies..........................................................259 11.7.1 Script Breakdown.........................................260 11.8 Wave Spawning and Control........................................261 11.8.1 Script Breakdown.........................................263 11.9 Wave Properties...................................................265 11.10 Weapons and Projectiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..266 11.11 User Interface.....................................................266 11.11.1 Script Breakdown.........................................267 12. Dish: Metal Vehicle Doom 271 12.1 Main Menu Scene..................................................272 12.2 Main Game Scene..................................................272 12.2.1 Prefabs...................................................275 12.3 Ingredients........................................................275 12.3.1 Game Controller..........................................276 12.3.1.1 Script Breakdown...............................282 12.3.2 Race Controller...........................................291 12.3.2.1 Script Breakdown...............................297 12.3.3 Global Race Manager......................................306 12.3.3.1 Script Breakdown...............................311 12.3.4 Vehicle/Custom Player Control.............................318 12.3.4.1 Script Breakdown...............................327 12.3.5 User Interface.............................................344 13. Dish: Making the Game Tank Battle 345 13.1 Main Game Scene..................................................347 13.2 Prefabs...........................................................349 13.3 Ingredients........................................................349 13.4 Game Controller...................................................350 13.4.1 Script Breakdown.........................................356 13.5 Battle Controller...................................................361 13.5.1 Script Breakdown.........................................363 13.6 Global Battle Manager..............................................364 13.6.1 Script Breakdown.........................................368 13.7 Players............................................................373 13.7.1 Script Breakdown.........................................382 xi Contents 13.8 AI Chasing with SetAIChaseTargetBasedOnTag.cs.....................383 13.8.1 Script Breakdown.........................................385 14. Dish: Making the Game Interstellar Paranoids 389 14.1 Main Menu.......................................................392 14.2 Game Scenes......................................................392 14.3 Prefabs...........................................................393 14.3.1 Ingredients...............................................394 14.3.2 Game Controller..........................................395 14.3.2.1 Script Breakdown...............................401 14.3.3 Player Spaceship..........................................411 14.3.3.1 Script Breakdown...............................415 14.3.4 Enemies..................................................423 14.3.4.1 Script Breakdown...............................424 14.3.5 Waypoint Follower........................................426 14.3.5.1 Script Breakdown...............................427 Final Note 429 xiii I would like to thank my wife for all the encouragement, support, and nice cups of tea. I would also like to thank my mum and dad, my brother Steve, and everyone else who knows me. Sophie cat, be nice to the boys. Sincere thanks go to the many people who positively influence my life directly or indirectly: Michelle Ashton, Brian Robbins, George Bray, Nadeem Rasool, Christian Boutin, James and Anna, Rich and Sharon, Liz and Peter, Rob Fearon (the curator of all things shiny), everyone on Twitter who RTs my babble (you know who you are, guys!), Matthew Smith (the creator of Manic Miner), David Braben, Tōru Iwatani, and anyone who made Atari games in the 1980s. I would like to thank everyone at AK Peters/CRC Press for the help and support and for publishing my work. Finally, a massive thank you goes out to you for buying this book and for wanting to do something as cool as to make games. I sincerely hope this book helps your gamemaking adventures—feel free to tell me about them on Twitter @psychicparrot or drop by my website at http://www.psychicparrot.com. Acknowledgments xv As I was starting out as a game developer, as a self-taught programmer my skills took a while to reach a level where I could achieve what I wanted. Sometimes I wanted to do things that I just didn’t have yet the technical skills to achieve. Now and again, software packages came along that could either help me in my quest to make games or even make full games for me; complete game systems such as the Shoot ’Em-Up Construction Kit (aka SEUCK) from Sensible Software, Gary Kitchen’s GameMaker, or The Quill Adventure System could bring to life the kinds of games that went way beyond anything that my limited programming skills could ever dream of building. The downside to using game creation software was that it was tailored to create games within their chosen specific genre. If I wanted to do something outside of the limitations of the software, the source code was inaccessible and there was no way to extend or modify it. When that happened, I longed for a modular code-based system that I could plug together to create different types of games but modify parts of it without having to spend a lot of time learning how the entire system internals work—building block game development that I could actually script and modify if I needed to. After completing my first book, Game Development for iOS with Unity3D, I wanted to follow up by applying a modular style of game building to Unity3D that would provide readers with a highly flexible framework to create just about any kind of game by “plugging in” the different script components. My intention was to make a more technical second book, based on C# programming, that would offer extensibility in any direction a developer might require. In essence, what you are holding in your hands right now is a cookbook Introduction xvi Introduction for game development that has a highly flexible core framework for just about any type of game. A lot of the work I put in at the start of writing this book was in designing a framework that not only made sense in the context of Unity but also could easily cope with the demands of different genres. Prerequisites You can get up and running with the required software for the grand total of zero dollars. Everything you need can be downloaded free of charge with no catches. You may want to consider an upgrade to Unity Pro at some point in the future, to take advantage of some of its advanced features, but to get started all you need to do is grab the free version from the Unity website. Unity Free or Unity Pro (available from the Unity store at http://www.unity3d.com) Unity Free is completely free for anyone or any company making less than $100,000 per year—it may be downloaded for no charge at all, and you don’t even need a credit card. It’s a really sweet deal! We are talking about a fully functional game engine, ready to make 3D or 2D games that may be sold commercially or otherwise. There are no royalties to pay, either. Unity Pro adds a whole host of professional functionality to the engine, such as render culling and profiling. If you are a company with more than $100,000 per year of turnover, you will need a Pro license, but if you find that Unity Free doesn’t pack quite enough power, you may also want to consider going Pro. You can arrange a free trial of the Pro version right from the Unity website to try before you buy. If the trial licence runs out before you feel you know enough to make a purchase, contact Unity about extending it and they are usually very friendly and helpful about it (just don’t try using a trial license for 6 months at a time, as they may just figure it out!). C# programming knowledge Again, to reiterate this very important point, this is nota book about learning how to program. You will need to know some C#, and there are a number of other books out there for that purpose, even if I have tried to make the examples as simple as possible! This book is about making games, not about learning to program. What This Book Doesn’t Cover This is not a book about programming and it is not a book about the right or wrong way to do things. We assume that the reader has some experience with the C# programming language. I am a self-taught programmer, and I understand that there may well be better ways to do things. xvii Introduction This is a book about concepts, and it is inevitable that there will be better methods for achieving some of the same goals. The techniques and concepts offered in this book are meant to provide solid foundation, not to be the final word on any subject. It is the author’s intention that, as you gain your own experiences in game development, you make your own rules and draw your own conclusions. Additional material is available from the CRC Press Web site: http://www.crcpress. com/product/isbn/9781466581401. 1 1 Making Games the Modular Way When I first started making games, I would approach development on a project-to-project basis, recoding and rebuilding everything from scratch each time. As I became a professional developer, landing a job at a game development studio making browser-based games, I was lucky enough to work with a guy who was innovating the scene. He was a master at turning out great games (both visually and gameplay-wise) very quickly. One secret to his success lay in the development of a reusable framework that could easily be refactored to use on all of his projects. His framework was set up to deal with server communication, input handling, browser communication, and UI among other things, saving an incredible amount of time in putting together all of the essentials. By reusing the framework, it allowed more time for him and his team to concentrate on great gameplay and graphics optimization, resulting in games that, at the time, blew the competition away. Of course, the structure was tailored to how he worked (he did build it, after all), and it took me a while to get to grips with his style of development; but once I did, it really opened my eyes. From then on, I used the framework for every project and even taught other programmers how to go about using it. Development time was substantially reduced, which left more time to concentrate on making better games. This book is based on a similar concept of a game-centric framework for use with many different types of games, rather than a set of different games in different styles. The overall goal of this book is to provide script-based components that you can use within that framework to make a head start with your own projects in a way that reduces recoding, repurposing, or adaptation time. 2 1. Making Games the Modular Way In terms of this book as a cookbook, think of the framework as a base soup and the scripting components as ingredients. We can mix and match script components from different games that use the same framework to make new games, and we can share several of the same core scripts in many different games. The framework takes care of the essentials, and we add a little “glue” code to pull everything together the way we want it all to work. This framework is, of course, optional, but you should spend some time familiarizing yourself with it to help understand the book. If you intend to use the components in this book for your own games, the framework may serve either as a base to build your games on or simply as a tutorial test bed for you to rip apart and see how things work. Perhaps you can develop a better framework or maybe you already have a solid framework in place. If you do, find a way to develop a cleaner, more efficient framework or even a framework that isn’t quite so efficient but works better with your own code, and do it. In this chapter, we start by examining some of the major programming concepts used in this book and look at how they affect the design decisions of the framework. 1.1 Important Programming Concepts I had been programming in C# for a fairly long time before I actually sat down and figured out some of the concepts covered in this chapter. It was not because of any particular problem or difficulty with the concepts themselves but more because I had solved the problems in a different way that meant I had no real requirement to learn anything new. For most programmers, these concepts will be second nature and perhaps something taught in school, but I did not know how important they could be. I had heard about things like inheritance, and it was something I put in the to-do list, buried somewhere under “finish the project.” Once I took the time to figure them out, they saved me a lot of time and led to much cleaner code than I would have previously pulled together. If there’s something you are unsure about, give this chapter a read-through and see whether you can work through the ideas. Hopefully, they may save some of you some time in the long run. 1.1.1 Manager and Controller Scripts I am a strong believer in manager and controller scripts. I like to try and split things out into separate areas; for example, in the Metal Vehicle Doomgame, I have race controller scripts and a global race controller script. The race controller scripts are attached to the players and track their positions on the track, waypoints, and other relevant player-specific race information. The global race controller script talks to all the race controller scripts attached to the players to determine who is winning and when the race starts or finishes. By keeping this logic separate from the other game scripts and contained in their own controller scripts, it makes it easier to migrate them from project to project. Essentially, I can take the race controller and global race controller scripts out of the game and apply them to another game, perhaps one that features a completely different type of gameplay— for example, alien characters running around a track instead of cars. As long as I apply the correct control scripts, the race logic is in place, and I can access it in the new game. In the framework that this book contains, there are individual manager and controller scripts dealing with user data, input, game functions, and user interface. We look at those in detail in Chapter 2, but as you read this chapter, you should keep in mind the idea of separated scripts dedicated to managing particular parts of the game structure. It was 3 1.1 Important Programming Concepts important to me to design scripts as standalone so that they may be used in more than one situation. For example, our weapon slot manager will not care what kind of weapon is in any of the slots. The weapon slot manager is merely an interface between the player and the weapon, taking a call to “fire” and responding to it by telling the weapon in the currently selected weapon slot to fire. What happens on the player end will not affect the slot manager just as anything that happens with the weapon itself will not affect the slot manager. It just doesn’t care as long as your code talks to it in the proper way and as long as your weapons receive commands in the proper way. It doesn’t even matter what type of object the slot manager is attached to. If you decide to attach the weapon slot manager to a car, a boat, a telegraph pole, etc., it doesn’t really matter just as long as when you want them to fire, you use the correct function in the slot manager to get it to tell a weapon to fire. Since our core game logic is controlled by manager and controller scripts, we need to be a little smart about how we piece everything together. Some manager scripts may benefit from being static and available globally (for all other scripts to access), whereas others may be better attached to other scripts. We deal with these on a case-by-case basis. To get things started, we will be looking at some of the ways that these manager scripts can communicate with each other. As a final note for the topic in this section, you may be wondering what the difference is between managers and controllers. There really isn’t all that much, and I have only chosen to differentiate for my own sanity. I see controllers as scripts that are larger global systems, such as game state control, and managers as smaller scripts applied to gameObjects, such as weapon slot management or physics control. The terms are applied loosely, so don’t worry if there appear to be inconsistencies in the application of the term in one case versus another. I’ll try my best to keep things logical, but that doesn’t mean it’ll always make sense to everyone else! 1.1.2 Script Communication An important part of our manager- and component-based structures is how our scripts are going to communicate with each other. It is inevitable that we will need to access our scripts from a multitude of other areas of the game, which means we should try to provide interfaces that make the most sense. There are several different ways of communicating between scripts and objects in Unity: 1. Direct referencing manager scripts via variables set in the editor by the Inspector window. The easiest way to have your scripts talk to each other is to have direct references to them in the form of public variables within a class. They are populated in the Unity editor with a direct link to another script. Here is an example of direct referencing: public void aScript otherScript; In the editor window, the Inspector shows the otherScript field. We drag and drop an object containing the script component that we want to talk to. Within the class, function calls are made directly on the variable, such as otherScript.DoSomething(); 4 1. Making Games the Modular Way 2. GameObject referencing using SendMessage. SendMessage is a great way to send a message to a gameObject and call a function in one of its attached scripts or components when we do not need any kind of return result. For example, SomeGameObject.SendMessage("DoSomething"); SendMessage may also take several parameters, such as setting whether or not the engine should throw an error when there is no receiver, that is, no function in any script attached to the gameObject with a name matching the one in the SendMessage call. (SendMessageOptions). You can also pass one parameter into the chosen function just as if you were passing it via a regular function call such as SomeGameObject.SendMessage("AddScore",2); SomeGameObject.SendMessage("AddScore", SendMessageOptions.RequireReceiver); SomeGameObject.SendMessage("AddScore", SendMessageOptions.DontRequireReceiver); 3. Static variables. The static variable type is useful in that it extends across the entire system; it will be accessible in every other script. This is a particularly useful behavior for a game control script, where several different scripts may want to communicate with it to do things such as add to the player’s score, lose a life, or perhaps change a level. An example declaration of a static variable might be private static GameController aController; Although static variables extend across the entire program, you can have private and public static variables. Things get a little tricky when you try to understand the differences between public and private static types—I was glad to have friends on Twitter that could explain it all to me, so let me pass on what I was told: Public static A public static variable exists everywhere in the system and may be accessed from other classes and other types of script. Imagine a situation where a player control script needs to tell the game controller script whenever a player picks up a banana. We could deal with it like this: 1. In our gamecontroller.cs game controller script, we set up a public static: public static GameController gateway; 2. When the game controller (gamecontroller.cs) runs its Start() function, it stores a reference to itself in a public static variable like this: gateway = this; 3. In any other class, we can now access the game controller by referring to its type followed by that static variable (GameController.gateway) such as GameController.gateway.GotBanana(); 5 1.1 Important Programming Concepts Private static A private static variable exists within the class it was declared and in any other instances of the same class. Other classes/types of script will not be able to access it. As a working example, try to imagine that a script named player.cs directly controls player objects in your game. They all need to tell a player manager script when something happens, so we declare the player manager as a static variable in our player.cs script like this: private static PlayerManager playerManager; The playerManager object only needs to be set up once, by a single instance of the player class, to be ready to use for all the other instances of the same class. All player.cs scripts will be able to access the same instance of the PlayerManager. 4. The singleton design pattern. In the previous part of this section, we looked at using a static variable to share a manager script across the entire game code. The biggest danger with this method is that it is possible to create multiple instances of the same script. If this happens, you may find that your player code is talking to the wrong instance of the game controller. A singletonis a commonly used design pattern that allows for only one instance of a particular class to be instantiated at a time. This pattern is ideal for our game scripts that may need to communicate (or be communicated with) across the entire game code. Note that we will be providing a static reference to the script, exactly as we did in the “Static Variables” method earlier in this section, but in implementing a singleton class, we will be adding some extra code to make sure that only one instance of our script is ever created. 1.1.3 Using the Singleton Pattern in Unity It is not too difficult to see how useful static variables can be in communication between different script objects. In the public static example cited earlier, the idea was that we had a game controller object that needed to be accessed from one or more other scripts in our game. The method shown here was demonstrated on the Unity public wiki*by a user named Emil Johansen (AngryAnt). It uses a private static variable in conjunction with a public static function. Other scripts access the public function to gain access to the private static instance of this script, which is returned via the public function so that only one instance of the object will ever exist in a scene regardless of how many components it is attached to and regardless of how many times it is instantiated. A simple singleton structure: public class MySingleton { private static MySingleton instance; public MySingleton () *http://wiki.unity3d.com/index.php/Singleton. 6 1. Making Games the Modular Way { if (instance != null) { Debug.LogError ("Cannot have two instances of singleton."); return; } instance = this; } public static MySingleton Instance { get { if (instance == null) { new MySingleton (); } return instance; } } } The singleton instance of our script may be accessed anywhere, by any script, simply with the following syntax: MySingleton.Instance.MySingletonMember; 1.1.4 Inheritance Inheritanceis a complex concept, which demands some explanation here because of its key role within the scripts provided in this book. Have a read through this section, but don’t worry if you don’t pick up inheritance right away. Once we get to the programming, it will most likely become clear. The bottom line is that inheritance is used in programming to describe a method of providing template scripts that may be overridden, or added to, by other scripts. As a metaphor, imagine a car. All cars have four wheels and an engine. The types of wheels may vary from car to car, as will the engine, so when we say “this is a car” and try to describe how our car behaves, we may also describe the engine and wheels. These relationships may be shown in a hierarchical order: Car -Wheels -Engine Now try to picture this as a C# script: Car class Wheels function Engine function 7 1.1 Important Programming Concepts
1. "The Power of Color" - A short video showcasing the impact of color on our emotions, using vibrant visuals and upbeat music. 2. "The Journey of a Seed" - A stop-motion animation following the life cycle of a seed, from planting to blooming, accompanied by a soothing voiceover. 3. "The Art of Upcycling" - A fast-paced montage of creative ideas for repurposing old items, set to an upbeat soundtrack and featuring witty captions. 4. "The Magic of Nature" - A cinematic exploration of the beauty of the natural world, using time-lapse and slow-motion footage to capture the wonder of the outdoors. 5. "The Joy of Dance" - A lively video showcasing different dance styles, from hip-hop to ballet, set to an energetic soundtrack and featuring dancers of all ages. 6. "The Power of Words" - A thought-provoking video using typography and animation to explore the impact of language on our thoughts and emotions. 7. "The Beauty of Diversity" - A celebration of different cultures and identities, featuring a diverse cast of people sharing their stories and experiences. 8. "The Art of Mindfulness" - A calming video using nature and ambient sounds to guide viewers through a mindfulness meditation practice. 9. "The Future of Sustainable Living" - A futuristic video exploring the potential of green technology and sustainable practices to shape a better world. 10. "The Joy of Pets" - A heartwarming video showcasing the bond between humans and their furry friends, set to a cheerful soundtrack and featuring cute animal footage.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值