首页 > 解决方案 > transform.position 在 Unity 中无法正常工作

问题描述

我正在统一制作游戏,我想获得玩家的位置(女巫是预制件)所以我使用敌人的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyScript : MonoBehaviour
{
    public Transform player;

    void Start() 
    {
        Debug.Log(player.position.x);
    }

}

我有一个生成器,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnEnemies : MonoBehaviour
{
    public GameObject enemy;
    float randX;
    float randY;
    Vector2 whereToSpawn;
    public float spawnRate = 2f;
    float nextSpawn = 0.0f; 


    void Update()
    {
        if (Time.time > nextSpawn)
        {
            nextSpawn = Time.time + spawnRate;
            randX = Random.Range(-6.36f, 6.36f);
            randY = Random.Range(-4.99f, 4.99f);
            whereToSpawn = new Vector2(randX, randY);
            Instantiate (enemy, whereToSpawn, Quaternion.identity);
        }
    }
}

但是当我运行它时,它总是给我 (0, 0, 0)。为什么我得到 0 以及如何修复它(获取玩家的当前位置)?

标签: c#unity3d

解决方案


尝试

Vector3 position = transform.position;
debug.log(position.x);

你可以在这里看到更多Transform.position


推荐阅读