unity 实例化预制体
Of course, we can put instantiation to much better uses. Let's try firing a bullet from a player who can move. First of all, let's get our little pal into the game.
当然,我们可以将实例化用于更好的用途。 让我们尝试向可以移动的玩家发射子弹。 首先,让我们的小伙伴进入游戏。
Next up, we'll give him something to shoot. How about a tiny little fireball?
接下来,我们给他一些东西来射击。 一个小小的火球怎么样?
Wonderful. Now, let's make him move using the arrow keys. We already know how to do that, so we'll skip over that part. Now, let's create a prefab out of that fireball. Once again, drag and drop the fireball into the Hierarchy to make it an active gameObject, then drag it back into the Assets to generate a prefab out of it.
精彩。 现在,让我们使用箭头键移动他。 我们已经知道如何执行此操作,因此我们将跳过该部分。 现在,让我们用该火球创建一个预制件 。 再次将火球拖放到“ 层次结构”中 ,使其成为活动的gameObject ,然后将其拖回到“ 资产”中,以从中生成预制件。
NOTE: A great way to test, if a prefab exists, is to simply look at the name of the gameObject in the Hierarchy. Game Objects which have a prefab existing for them will have their name written in blue.
注意:测试是否存在预制件的一种好方法是简单地查看Hierarchy中的gameObject的名称。 现有的预制游戏对象的名称将以蓝色表示。
Now, we will go ahead and create a new script named Shooter
.
现在,我们将继续创建一个名为Shooter
的新脚本。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooter : MonoBehaviour
{
public GameObject fireball;
public RigidBody2D body;
public float speed;
void Update()
{
body.velocity = new Vector2(Input.GetAxisRaw("Horizontal")*speed, Input.GetAxisRaw("Vertical")*speed);
// When spacebar is hit
if(Input.GetKeyDown(KeyCode.Space))
{
// instantiate the fireball object
Instantiate(fireball);
}
}
}
This is simply a combination of the code we have written for movement and instantiation so far. Nothing too complicated. If you save this script and attach it to your main character, you can now move him around and if you press the Spacebar, the fireballs will appear and fall down.
这仅仅是到目前为止我们为移动和实例化编写的代码的组合。 没什么复杂的。 如果您保存此脚本并将其附加到您的主要角色,则现在可以移动他,并且如果您按下空格键 ,火球将出现并掉下。
设置新预制件的位置 (Setting Position for new Prefabs)
The bullets are not really doing anything, just falling (you can