簡體   English   中英

GameObject.transform.position 在 Unity 中無法正常工作

[英]GameObject.transform.position not working properly in Unity

我正在統一制作游戲,我想獲得玩家的 position 所以我使用敵人的代碼:

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

public class EnemyScript : MonoBehaviour
{
    public GameObjetct player;

    void Start() 
    {
        Debug.Log(player.transform.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 以及如何修復它(獲取播放器的當前 position)?

可能沒有正確分配敵人的玩家變量。

嘗試將 player GameObject 變量分配給您的 SpawnEnemies object,並讓這個變量將 player 變量分配給敵人腳本。

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; 

    public GameObject player = null; //Remember to assign this through the editor!

    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);
            GameObject enemy = Instantiate (enemy, whereToSpawn, Quaternion.identity);
            enemy.player = this.player; //here you can assign to each new created enemy your player position on runtime.
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM