Unity 不会让我将“变换目标”设置为玩家,直到游戏中存在敌人。我要更改什么才能使其自动以玩家为目标而不通过统一指定目标?这是我的代码。
using UnityEngine;
public class PawnRotate : MonoBehaviour
{
//public Transform target;
public Transform target;
public float speed = 3f;
private void Start()
{
if (Vector3.Distance(transform.position, target.position) > 1f)
{
RotateTowards(target.position);
target = GameObject.FindObjectOfType<Player>().transform;
}
}
private void RotateTowards(Vector2 target)
{
var offset = 90f;
Vector2 direction = target - (Vector2)transform.position;
direction.Normalize();
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(Vector3.forward * (angle + offset));
}
}
答案 0 :(得分:0)
有很多方法可以做到这一点。
基本上,您需要通过代码找到玩家的 GameObject(或 Transform)。
按标签
如果您的播放器有标签,您可以使用 GameObject.FindGameObjectsWithTag
(https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html) 找到它。
private void Start()
{
target = GameObject.FindGameObjectsWithTag("Player").transform; // "Player" should be your player tag
}
通过脚本
如果您的播放器有一个独特的脚本,您可以使用 GameObject.FindObjectOfType
(https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html) 找到它。
private void Start()
{
target = GameObject.FindObjectOfType<Player>().transform; // "Player" should be your player MonoBehaviour script
}
还有其他方法可以做到这一点。
例如:使用单例,某种类型的具有玩家引用的 GameController 等。
PS:两种方式都期望 Player 对象已经在场景中