简体   繁体   English

如何获得预制件的统一地位?

[英]How to get the Prefabs position in unity?

I want to rotate tank face to moving enemy direction, and I need position of enemy . 我想将坦克的脸旋转到敌人移动的方向,并且我需要enemy位置。

enemy.transform.position; works when enemy is in the Hierarchy, but my enemy is in the Prefabs and following code not work. 当敌人处于层次结构中时起作用,但是我的敌人位于Prefabs中,并且以下代码不起作用。 please help :) 请帮忙 :)

using UnityEngine;
using System.Collections;

public class RotateTank : MonoBehaviour {
public GameObject enemy;

void Update () {
    faceTank ();
}

void faceTank(){

    Vector3 enemyPosition;

    enemyPosition = enemy.transform.position;


    Vector2 direction = new Vector2 (
                             enemyPosition.x - transform.position.x,
                             enemyPosition.y - transform.position.y

                         );

    transform.up = direction;
}
}

A prefab does not exist in the game world. 游戏世界中不存在预制件。 Prefabs are "templates" that can be instantiated. 预制件是可以实例化的“模板”。 If what you want to do is make your tank rotate towards any enemy that exists in the game world, you'll need to reference those GameObjects in your RotateTank script. 如果您想做的是使战车向游戏世界中存在的任何敌人旋转,则需要在RotateTank脚本中引用这些GameObject。 You could do this a number of ways, such as adding an 'Enemy' tag to your enemy prefab and using GameObject.FindGameObjectsWithTag to find spawned Enemies. 您可以通过多种方式执行此操作,例如向敌人的预制件添加“敌人”标签,并使用GameObject.FindGameObjectsWithTag查找生成的敌人。 You could also have a static List<GameObject> in your RotateTank script that holds references to existing enemies, and add them to that list when they spawn and remove them when they die. 您还可以在RotateTank脚本中有一个静态List<GameObject> RotateTank List<GameObject> ,其中包含对现有敌人的引用,并在它们生成时将其添加到该列表中,并在它们死亡时将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM