首页 > 解决方案 > 从对象池中旋转游戏对象

问题描述

我想在创建子弹对象后旋转它(即从池中取出)。

这是我的函数,其中子弹从对象池中取出并分别定位:

void CreateBullet (GameObject bulletObj, Transform _bulletPos, float xVal = 0f, float yVal = 0f) {

    //get bullet object from pool
    bulletObj = bulletPool.GetInstance (playerShotsGO);
    bulletObj.transform.position = _bulletPos.position;

    Vector2 pos = bulletPos.transform.position;//Position 0,0

    pos.x += xVal;
    pos.y += yVal;

    bulletObj.transform.position = pos;

    bulletObj.transform.SetParent (playerShotsGO.transform, true);
}

这是我的 PlayerBullet 脚本的更新函数,其中计算了子弹的位置:

void Update () {
    Vector2 position = transform.position;

    //compute the bullet's new position
    position = new Vector2 (position.x, position.y + speed * Time.deltaTime);

    //update the bullet's position
    transform.position = position;
}

在这里我的对象被实例化:

protected virtual GameObject AllocateInstance (bool parent, GameObject parentObj) {
    GameObject instance = (GameObject)GameObject.Instantiate (prefab);
    if (parent) {
        instance.transform.SetParent(parentObj.transform, true);
    }

    instance.SetActive(false);
    pool.Add(instance);

    return instance;
}

标签: c#unity3drotation

解决方案


根据Unity3d 教程中的https://unity3d.com/learn/tutorials/topics/scripting/object-pooling,您需要在池中搜索准备好使用的对象。如果没有找到,则生成一个新的。然后您使用SetActive(true)来显示它,并通过 设置旋转instance.transform.rotation = <Vector3>


推荐阅读