热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

unity创建游戏对象_Unity:在运行时使用Prefabs创建游戏对象

unity创建游戏对象NowthatyouhaveunderstoodsomeofthebasicsofworkingwithUnity,andhavemadeagameortwo

unity 创建游戏对象

Now that you have understood some of the basics of working with Unity, and have made a game or two by yourself, let's try and dig in deeper, shall we? After all, we have just scraped the surface of the iceberg that is Unity!

现在您已经了解了使用Unity的一些基础知识,并且自己编写了一个或两个游戏,让我们尝试更深入地研究,对吧? 毕竟,我们只是刮掉了团结的冰山表面!

First of all, it's time to say goodbye to Mr. Star. He's been a good friend of ours for the journey up until now, but for what we have ahead, we need something a bit more complex, and a star drawn hastily in Paint.NET in mere 13 seconds doesn't really fit that description.

首先,是时候向斯塔先生说再见了。 到目前为止,他一直是我们的好朋友,但是对于我们要取得的成就,我们需要更复杂的东西,而在Paint.NET中匆匆绘制的一颗星星在短短的13秒之内并不符合该描述。

So what does fit that description? This, I guess...

那么,什么符合该描述呢? 我猜这...

A cartoon boy Game Object for Unity

Now, we'll be understanding more fundamental concepts related to Unity, more focused on gameObjects and prefabs.

现在,我们将了解与团结更多的基本概念,更侧重于gameObjects预制件

了解预制件和实例化 (Understanding Prefabs and Instantiation)

Okay, so the word Prefab looks a bit scary, doesn't it? Don't worry, it's not, in fact, it's one of game designer's best friends when it comes to creating gameObjects in real-time. So what exactly is a prefab? Well, a prefab is actually a blueprint or a template for a specific gameObject. We know this is kind of confusing to understand at first, so let's take a very basic example.

好的, Prefab这个词看起来有点吓人,不是吗? 不用担心,在实时创建gameObjects时,它并不是游戏设计师最好的朋友之一。 那么什么是预制件呢? 好吧,预制件实际上是特定游戏对象的蓝图或模板。 首先,我们知道这有点令人困惑,所以让我们举一个非常基本的例子。

Imagine we are making a basic space shooter game, and this here, little fellow, is an enemy character.

想象我们正在制作一个基本的太空射击游戏,而这里的小家伙是个敌人。

Enemy cartoon Game Object

Now, if we wanted to build a game scene in Unity with our main character, and an enemy, it would look something like this:

现在,如果我们想在Unity中以我们的主要角色和一个敌人来构建游戏场景,它将看起来像这样:

setup for space shooting game in unity

Sure, this is perfectly fine for when you have one enemy, but what if you wanted a lot of them? Not 2 or 3, assume like 15 or 20. As a beginner learning Unity, you might be thinking something along these lines: Using the same asset, multiple times by creating copies.

当然,当您有一个敌人时,这是完全可以的,但是如果您想要很多敌人怎么办? 假设不是2还是3,则假设是15或20。假设您是初学者学习Unity,您可能会按照以下思路进行思考: 使用同一资产,通过创建副本多次。

Basic Fundamentals of GameObjects

Ok, that's also a viable solution, we suppose, but what if every sprite has its own AI and its own custom properties? Would you really like, going through the trouble of adding a Rigidbody and Colliders to every single sprite? What if you wanted to generate more of these enemies, during gameplay and not during the scene making process? We would seriously not recommend placing every single enemy yourself, or your game might become really predictable and boring.

好的,我们认为这也是可行的解决方案,但是如果每个子画面都有自己的AI和自己的自定义属性怎么办? 您真的要为每一个精灵添加一个刚体碰撞器的麻烦吗? 如果您想在游戏过程中而不是在场景制作过程中产生更多这些敌人,该怎么办? 我们不建议您自己放置每个敌人,否则您的游戏可能会变得可预测且无聊。

What if we could define a single enemy, and have something generate copies of that enemy, since they're all the same? Well, the prefab is what solves exactly that.

如果我们可以定义一个敌人并拥有某种东西来生成该敌人的副本,因为它们都是相同的怎么办? 好吧, 预制件正是解决这个问题的方法。

A PreFab is a definition of a gameObject which we want to generate, and it produces an exact copy of the defined gameObject, whenever you need it, wherever you need it. This proves tremendously useful when you need to generate gameObjects on the fly, like bullets, aliens, coins etc, since Unity does most of the work here, making the gameObjects instantly available for us.

PreFab是我们要生成的gameObject的定义,它可以在需要时,无论何时何地生成已定义gameObject的精确副本。 当您需要动态生成游戏对象(如子弹,外星人,硬币等)时,这被证明非常有用,因为Unity在这里完成了大部分工作,使我们可以立即使用游戏对象。

使用Prefab在运行时生成游戏对象 (Using Prefab to generate Game Object at runtime)

Let's put this to use. We'll start with a very simple exercise, to spawn a box every time we press the Spacebar. First of all, let's create a spawner. Now we don't really need a spawner to have graphics, just an empty gameObject will do. So, what you do is right-click in the Hierarchy, and click on Create Empty.

让我们使用它。 我们将从一个非常简单的练习开始, 每次按空格键时都会生成一个框 。 首先,让我们创建一个spawner 。 现在我们实际上并不需要生成器来拥有图形,只需一个空的 gameObject就可以了。 因此,您要做的是右键单击层次结构,然后单击创建空

Prefab to generate Game Object at runtime

You should see a new GameObject appear in the Hierarchy. But nothing appears on the screen. Because this is an empty gameObject, it doesn't have any components except a Transform. Remember that a Sprite Renderer is also a component. Since this gameObject doesn't have such a component, it simply doesn't render anything. It's simply, there. Empty gameObjects are really useful for things like spawners and reference points, since they're invisible during gameplay.

您应该看到一个新的GameObject出现在层次结构中。 但是屏幕上没有任何显示。 因为这是一个空的 gameObject,所以它除了Transform之外没有任何组件。 请记住,Sprite Renderer也是一个组件。 由于此gameObject没有此类组件,因此它根本不会呈现任何内容。 就在那儿。 空的GameObject对于生成器和参考点之类的东西真的很有用,因为它们在游戏过程中是不可见的。

Prefab to generate Game Object at runtime

You can always check where an empty gameObject is by simply clicking on the gameObject in the Hierarchy. It should then show you the location of that gameObject with a translucent circle. Anyways, let's rename our empty gameObject to Generator, just so we know what it actually is. We will leave you to find out how to rename the gameObject, it's quite simple.

您始终可以通过单击层次结构中的gameObject来检查一个空的gameObject在哪里。 然后应该用半透明的圆圈向您显示该游戏对象的位置。 无论如何,让我们将空的GameObject重命名为Generator ,以便我们知道它的实际含义。 我们将让您了解如何重命名gameObject,这很简单。

Now, let's create the actual box to generate. Create a sprite using the default sprite menu we used to generate that blockade back in the previous tutorials. (It doesn't really have to be a box, you can use any sprite. We are using the default square sprite for the sake of simplicity).

现在,让我们创建要生成的实际框。 使用默认的Sprite菜单创建一个Sprite,我们在先前的教程中曾使用该菜单来生成该封锁。 (实际上并不一定要是一个盒子,您可以使用任何精灵。为了简单起见,我们使用默认的方形精灵)。

Prefab to generate Game Object at runtime

Now, let's add a Rigidbody2D to the box, just to give it weight so it falls down when it's generated. That means we won't be modifying our gravity scale. (Or if you're the persistent type, set it to any value other than zero). Hit play button to test out your box. If it falls down, you're on the right track.

现在,让我们将Rigidbody2D添加到盒子中,只是为了赋予它重量,以便它在生成时掉落。 这意味着我们不会修改重力比例。 (或者,如果您是永久类型,请将其设置为零以外的任何值)。 点击播放按钮测试您的游戏机。 如果跌落,则您在正确的轨道上。

Prefab to generate Game Object at runtime

Now, remember how you added Mr. Star to the scene back when you were getting started? You dragged the sprite from the Assets to the Hierarchy.

现在,还记得刚开始时如何将Star先生添加到场景中吗? 您将精灵从“ 资产”拖动到了“ 层次结构”

Creating a prefab is the reverse of that process. You drag an existing gameObject from the Hierarchy to the Assets. Unity then generates a prefab of that gameObject in the folder you dragged it into. So, since we want to make a template of the Box, we will just drag the box sprite from the Hierarchy into our Prefabs folder.

创建预制件是该过程的相反步骤。 您将现有的gameObject从“ 层次结构”拖动到“ 资产” 。 然后,Unity在您将其拖动到的文件夹中生成该gameObject的预制件。 因此,由于我们要创建Box的模板,因此只需将Box Sprite从Hierarchy拖到Prefabs文件夹中即可。

Basic Fundamentals of GameObjects

You should see something new appear in your Prefabs folder. It's the exact same image of the box, but it appears in a grey container. That's your prefab! Easy, wasn't it? Now, to generate an instance of this prefab whenever the Spacebar is pressed, we will need to write a tiny script for the Generator. For the sole purpose of generating a box whenever you press the Spacebar, the following code is perfect.

您应该在Prefabs文件夹中看到一些新内容。 这是与盒子完全相同的图像,但是它显示在灰色容器中。 那是你的预制件! 很简单,不是吗? 现在,要在按下空格键时生成此预制实例,我们将需要为Generator编写一个小脚本。 仅当您按下空格键时才生成一个框,下面的代码是完美的。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Generator : MonoBehaviour
{public GameObject boxToGenerate;void update() {// When spacebar is hitif(Input.GetKeyDown(KeyCode.Space)){// instantiate the box objectInstantiate(boxToGenerate);}}}

You remember how to create a new script and rename it, right? If not, check the last tutorial. We will also name our script as Generator.

您还记得如何创建一个新脚本并将其重命名,对吗? 如果没有,请检查上一个教程。 我们还将脚本命名为Generator

Note how the Start() method is missing here. Getting rid of empty the Start() and Update() methods is something which you should do, and is quite recommended when developing in Unity.

请注意,这里缺少Start()方法。 摆脱空的Start()Update()方法是您应该做的事情,在Unity中进行开发时,强烈建议您这样做。

  • Line 7: You should be familiar with this line by now. It's a declaration to Unity to ask it for a gameObject to generate, by making that slot in the editor we saw earlier.

    第7行:您现在应该已经熟悉此行。 这是Unity的声明,要求它通过在我们之前看到的编辑器中放置该插槽来要求生成一个gameObject。

  • Basic Fundamentals of GameObjects


  • Line 11: This has some interesting stuff going on. The Input class, as we know, contains definitions for various methods of providing input to the game. This includes mouse buttons, gamepad keys and keyboard keys.

    第11行:正在进行一些有趣的事情。 我们知道, Input类包含为游戏提供输入的各种方法的定义。 这包括鼠标按钮 , 游戏手柄键键盘键

    In our case, we're using the GetKeyDown method. This detects when a key has just been pressed. Other methods for keyboards are GetKey (detects a keypress that is then held) and GetKeyUp (detects the key which is just released). Inside the GetKeyDown method, we have an enum as a parameter, the KeyCode enum. It's basically an enumerated list of all the keys on a keyboard.

    在我们的例子中,我们使用的是GetKeyDown方法。 这将检测何时刚按下一个键。 键盘的其他方法是GetKey (检测然后GetKeyUp的按键)和GetKeyUp (检测刚刚释放的键)。 在GetKeyDown方法内部,我们有一个枚举作为参数,即KeyCode枚举。 它基本上是键盘上所有键的枚举列表。

  • Line 12: As you can guess, this is the main magical line, as we've been calling it. The Instantiate method is a method in the GameObject class (note the capital G), which has a few overloaded variations. The main parameter across all these overloads, however, is the actual gameObject to instantiate, or, generate. Since we want to generate the box that we plug in the editor, we will supply the boxToGenerate as the parameter. Simply save and attach this script to the Generator gameObject in the editor.

    第12行:您可以猜到,这就是我们一直在称呼的神奇主线。 Instantiate方法是GameObject类中的一种方法(请注意大写G),它具有一些重载的变化形式。 但是,所有这些重载的主要参数是要实例化或生成的实际gameObject。 由于我们要生成要插入编辑器中的框,因此我们将提供boxToGenerate作为参数。 只需保存此脚本并将其附加到编辑器中的Generator游戏对象。

Now, to fill in the Box To Generate slot that appears in the script's properties, we will simply click on the circle-dot, and pick our box's prefab. Alternatively, you can just drag and drop the box prefab into the slot. What this is doing is telling Unity what to generate. boxToGenerate is simply the name of the gameObject variable, that variable still needs to be something.

现在,要填充出现在脚本属性中的“要生成框”插槽,我们只需单击圆点,然后选择框的prefab即可 。 或者,您可以将预制的预制盒子拖放到插槽中。 这是在告诉Unity生成什么。 boxToGenerate只是gameObject变量的名称,该变量仍需要是某些东西。

Save your work in a new scene, and click play. If everything goes right, a new box should get generated whenever you press the Spacebar.

将您的作品保存在新场景中,然后单击“播放”。 如果一切正常,每当您按空格键时,都会生成一个新框。

Basic Fundamentals of GameObjects

If you pay attention to the Hierarchy, you'll notice that you're generating a new Box(Clone) every time. Even though they fall off the screen, they're still in the hierarchy.

如果您注意层次结构,则会注意到每次都在生成一个新的Box(克隆)。 即使它们从屏幕上掉下来,它们仍然处于层次结构中。

Here's where we should warn you to not generate too many of them, since they'll just fall indefinitely and too many of them could start lagging the program. I'll explain how to destroy objects later on.

在这里,我们应该警告您不要生成过多的代码,因为它们会无限期下降,并且太多的代码可能会滞后于程序。 稍后将说明如何销毁对象。

翻译自: https://www.studytonight.com/game-development-in-2D/basic-fundamentals-of-game-objects

unity 创建游戏对象



推荐阅读
  • 深入解析Java枚举及其高级特性
    本文详细介绍了Java枚举的概念、语法、使用规则和应用场景,并探讨了其在实际编程中的高级应用。所有相关内容已收录于GitHub仓库[JavaLearningmanual](https://github.com/Ziphtracks/JavaLearningmanual),欢迎Star并持续关注。 ... [详细]
  • 本文探讨了如何通过预处理器开关选择不同的类实现,并解决在特定情况下遇到的链接器错误。 ... [详细]
  • 在编译BSP包过程中,遇到了一个与 'gets' 函数相关的编译错误。该问题通常发生在较新的编译环境中,由于 'gets' 函数已被弃用并视为安全漏洞。本文将详细介绍如何通过修改源代码和配置文件来解决这一问题。 ... [详细]
  • Asp.net MVC 中 Bundle 配置详解:合并与压缩 JS 和 CSS 文件
    本文深入探讨了 Asp.net MVC 中如何利用 Bundle 功能来合并和压缩 JavaScript 和 CSS 文件,提供了详细的配置步骤和示例代码,适合开发人员参考学习。 ... [详细]
  • 本文探讨了浏览器的同源策略限制及其对 AJAX 请求的影响,并详细介绍了如何在 Spring Boot 应用中优雅地处理跨域请求,特别是当请求包含自定义 Headers 时的解决方案。 ... [详细]
  • 深入解析Spring启动过程
    本文详细介绍了Spring框架的启动流程,帮助开发者理解其内部机制。通过具体示例和代码片段,解释了Bean定义、工厂类、读取器以及条件评估等关键概念,使读者能够更全面地掌握Spring的初始化过程。 ... [详细]
  • docker镜像重启_docker怎么启动镜像dock ... [详细]
  • 本文介绍如何在Linux系统中卸载预装的OpenJDK,安装指定版本的JDK 1.8,并配置防火墙以确保系统安全性和软件兼容性。 ... [详细]
  • 利用YAML配置Resilience4J的Circuit Breaker
    本文探讨了Resilience4j作为现代Java应用程序中不可或缺的容错工具,特别介绍了如何通过YAML文件配置Circuit Breaker以提高服务的弹性和稳定性。 ... [详细]
  • js常用方法(1)startWithJava代码varstartsWithfunction(str,regex){if(regexundefined||strundefined|| ... [详细]
  • 利用Excel VBA调用Linux命令及Bash脚本
    Excel VBA不仅能够处理日常办公任务,还具备调用外部命令行或Bash脚本的能力。本文将介绍如何使用VBA中的Shell函数来执行命令行指令,并通过实际示例展示如何获取计算机网络配置信息。 ... [详细]
  • 本文探讨了一个特定的问题:当应用程序通过安装器启动后最小化,再次打开时,会触发窗口丢失错误,导致应用重启,并且之前的异步线程无法正常管理。这一现象在直接从应用图标启动时不会出现。 ... [详细]
  • 本文深入探讨了HTML5中十五个重要的新特性,为开发者提供了详细的指南。 ... [详细]
  • 搭建Jenkins、Ant与TestNG集成环境
    本文详细介绍了如何在Ubuntu 16.04系统上配置Jenkins、Ant和TestNG的集成开发环境,涵盖从安装到配置的具体步骤,并提供了创建Windows Slave节点及项目构建的指南。 ... [详细]
  • 本文总结了多位高分考生的经验,详细介绍了提升雅思听力的有效方法和必备资料,帮助考生更好地准备雅思听力考试。 ... [详细]
author-avatar
猫儿
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有