Search Unity

How to spawn objects when player is close

Discussion in 'Scripting' started by onurduha, Feb 9, 2019.

  1. onurduha

    onurduha

    Joined:
    Dec 29, 2018
    Posts:
    51
    Im making a 3D endless runner everything is good but my enemy spawner is spawning too soon i want to spawn when player is close to spawner how can i make it
     
  2. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    Spawn the enemies when the player is closer.

    If you want us to give you non-trivial answers, we need more info - perhaps show the code where your spawner decides when to spawn.We'd love to help, but only very ffew of us have mastered the art of reading a poster's mind :)
     
  3. onurduha

    onurduha

    Joined:
    Dec 29, 2018
    Posts:
    51
    That's the enemy script
    Code (CSharp):
    1. private Rigidbody rigidbody;
    2.  
    3.     private float speed = 5.0f;
    4.  
    5.     private void Start()
    6.     {
    7.         rigidbody = GetComponent<Rigidbody>();
    8.     }
    9.  
    10.     private void Update()
    11.     {
    12.         rigidbody.AddForce(new Vector3(0, 0, -1) * speed);
    13.      
    14.     }
    That's the spawner script
    Code (CSharp):
    1. public GameObject fireball;
    2.  
    3.     private void Start()
    4.     {
    5.         if(Random.value > 0.9)
    6.         {
    7.             Instantiate(fireball, transform.position, Quaternion.identity);
    8.         }
    9.     }
    Spawner.png

    I have tiles like this and some of them has spawner and tiles are spawning randomly maybe i can do with collider but if there is a better way i like to hear it
     
  4. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    If you have the position of the player, all you need to do is to make sure you only spawn if the distance to the player is smaller than a trigger distance, e.g.

    Code (CSharp):
    1. if ((Random.value > 0.9) && (Vector3.Distance(transform.position, player.transform.position) < 5))
    2.         {
    3.             Instantiate(fireball, transform.position, Quaternion.identity);
    4.         }
    I don't understand why you spawn in Start(), but I guess that's your choice.
     
  5. onurduha

    onurduha

    Joined:
    Dec 29, 2018
    Posts:
    51
    Ok i'll try this. Why i didn't spawn in update it spawns non stop so start spawns just for once might be a another way but it works so i didn't look for another way thanks for your help :)