Search Unity

Using OnTriggerStay to instantiate after time elapsed

Discussion in 'Scripting' started by SiMULOiD, Sep 3, 2015.

  1. SiMULOiD

    SiMULOiD

    Joined:
    Dec 23, 2013
    Posts:
    126
    Hi all,

    I've been searching the forum for a better way to instantiate an object using OnTriggerStay.
    Currently, I'm using the following, but having mixed success. My problem is that I'm getting multiple instances when triggered by the tagged object. Any thoughts?

    Thanks,
    Greg

    1. using UnityEngine;
    2. using System.Collections;


    3. public class OnTriggerStayInstance : MonoBehaviour {


    4. public GameObject projectilePrefab;
    5. float t = 0;

    6. void OnTriggerEnter(Collider other)
    7. {
    8. if(other.gameObject.tag=="Test")
    9. t = 0;
    10. }

    11. void OnTriggerStay(Collider other)
    12. {
    13. if(other.gameObject.tag=="Test")

    14. t += Time.deltaTime;
    15. if(t > 3) {

    16. Instantiate(projectilePrefab, transform.position,transform.rotation);


    17. Destroy(transform.gameObject);
    18. }
    19. }}
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    What's with your other thread?
    It won't help to create a thread with the same topic twice.

    In the other thread you said these problems occur only if there are several objects.
    This still suggests that there are several ones causing the method to be called.

    If you think that's not the problem:
    Describe your scene a little more and answer the following question:
    How many objects? Which objects hold this script? Which of the objects are marked as trigger and which of the objects have a rigidbody for example? Attach a screenshot if you want to.