unity 实例化预制体_Unity:预制实例化,使其移动并设置速度

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.

当然,我们可以将实例化用于更好的用途。 让我们尝试向可以移动的玩家发射子弹。 首先,让我们的小伙伴进入游戏。

Complicated Prefab Instantiation

Next up, we'll give him something to shoot. How about a tiny little fireball?

接下来,我们给他一些东西来射击。 一个小小的火球怎么样?

Complicated Prefab Instantiation
Complicated Prefab Instantiation

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.

这仅仅是到目前为止我们为移动实例化编写的代码的组合。 没什么复杂的。 如果您保存此脚本并将其附加到您的主要角色,则现在可以移动他,并且如果您按下空格键 ,火球将出现并掉下。

More Complicated Prefab Instantiation

设置新预制件的位置 (Setting Position for new Prefabs)

The bullets are not really doing anything, just falling (you can

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值