热门标签 | 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 创建游戏对象



推荐阅读
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 篇首语:本文由编程笔记#小编为大家整理,主要介绍了10分钟了解Android的事件分发相关的知识,希望对你有一定的参考价值。什么是事件分发?大家 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了logistic回归(线性和非线性)相关的知识,包括线性logistic回归的代码和数据集的分布情况。希望对你有一定的参考价值。 ... [详细]
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文介绍了机器学习手册中关于日期和时区操作的重要性以及其在实际应用中的作用。文章以一个故事为背景,描述了学童们面对老先生的教导时的反应,以及上官如在这个过程中的表现。同时,文章也提到了顾慎为对上官如的恨意以及他们之间的矛盾源于早年的结局。最后,文章强调了日期和时区操作在机器学习中的重要性,并指出了其在实际应用中的作用和意义。 ... [详细]
  • 本文详细介绍了如何使用MySQL来显示SQL语句的执行时间,并通过MySQL Query Profiler获取CPU和内存使用量以及系统锁和表锁的时间。同时介绍了效能分析的三种方法:瓶颈分析、工作负载分析和基于比率的分析。 ... [详细]
  • This article discusses the efficiency of using char str[] and char *str and whether there is any reason to prefer one over the other. It explains the difference between the two and provides an example to illustrate their usage. ... [详细]
  • MPLS VP恩 后门链路shamlink实验及配置步骤
    本文介绍了MPLS VP恩 后门链路shamlink的实验步骤及配置过程,包括拓扑、CE1、PE1、P1、P2、PE2和CE2的配置。详细讲解了shamlink实验的目的和操作步骤,帮助读者理解和实践该技术。 ... [详细]
  • 本文由编程笔记#小编整理,主要介绍了关于数论相关的知识,包括数论的算法和百度百科的链接。文章还介绍了欧几里得算法、辗转相除法、gcd、lcm和扩展欧几里得算法的使用方法。此外,文章还提到了数论在求解不定方程、模线性方程和乘法逆元方面的应用。摘要长度:184字。 ... [详细]
  • 本文介绍了一个适用于PHP应用快速接入TRX和TRC20数字资产的开发包,该开发包支持使用自有Tron区块链节点的应用场景,也支持基于Tron官方公共API服务的轻量级部署场景。提供的功能包括生成地址、验证地址、查询余额、交易转账、查询最新区块和查询交易信息等。详细信息可参考tron-php的Github地址:https://github.com/Fenguoz/tron-php。 ... [详细]
  • 本文讨论了在VMWARE5.1的虚拟服务器Windows Server 2008R2上安装oracle 10g客户端时出现的问题,并提供了解决方法。错误日志显示了异常访问违例,通过分析日志中的问题帧,找到了解决问题的线索。文章详细介绍了解决方法,帮助读者顺利安装oracle 10g客户端。 ... [详细]
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社区 版权所有