I am making a game in unity and i want to get the position of the player so i use the code for the enemy:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyScript : MonoBehaviour { public GameObjetct player; void Start() { Debug.Log(player.transform.position.x); } } 

I have a spawner and here is the code:

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); } } } 

But when i run it, it always gives me (0, 0, 0). Why do i get 0 and how can i fix it ( get the current position of the player )?

1

1 Answer

Probably your player variable of enemy is not correctly assigned.

Try to assign the player GameObject variable to your SpawnEnemies object, and let this one assign the player variable to the enemies script.

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. } } } 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy