0
\$\begingroup\$

I am new to unity and trying to make a bouble trouble game. I have enemy prefabs with BoxCollider with is triggered checked. I also have a shooting script. when I am trying to instantiate the enemy prefabs on runtime, they dont seem to trigger the OnTriggerEnter function, but if I am placing an Enemy prefab not ingame, it does trigger the funtion. I have no idea why.

The on run-time instantiate:

public class CreateBalls : MonoBehaviour
{
    public Rigidbody prefab;
    public Transform position1;
    
    void Awake()
    {
        

        for (int i = 0; i < 1; i++)
        {
            float random = Random.Range(-45.08f, 44.41f);
            Vector3 vec = new Vector3(random, position1.position.y, position1.position.z);
            Rigidbody ball= Instantiate(prefab, vec, position1.rotation) as Rigidbody;
        
        }
    }
}

The funtion not being called:

public class DestroyBalls : MonoBehaviour
{
    public Rigidbody potion;
    public Transform posToSpawn;

    private void OnTriggerEnter(Collider other)
    {
        if (this.gameObject.tag == "Enemy"&& other.gameObject.tag=="Bullet")
        {
           //a code not relevent
        }
    }
}

Any idea of why the funtion isnt being called? the bullets are tagged "Bullet" and the Enemies are tagged "Enemy"


Update: The funtion is triggered when colliding with another Enemy tagged, but not being trigged after collision with anyother tagged object

Also, I have another component on the Enemy Prefab, which also instantiates enemies on run-time and these trigger the function perfectly fine. very wierd. the code:

public Rigidbody ballToSpawn;
    public Transform spawnPoint;

    private void OnTriggerEnter(Collider other)
    {
        if (this.gameObject.tag == "Enemy" && other.gameObject.tag == "Bullet")
        {
            if (this.gameObject.GetComponent<Size>().size > 1)
            {
                Rigidbody small;

                for (int i = 0,y=-1 ; i < 2; i++,y+=2)
                {
                    Vector3 vec = new Vector3(spawnPoint.position.x+y, spawnPoint.position.y, spawnPoint.position.z);
                    small = Instantiate(ballToSpawn, vec, spawnPoint.rotation) as Rigidbody;
                    small.gameObject.transform.localScale = new Vector3(1, 1, 0);
                    small.gameObject.GetComponent<AutoMoveForBall>().GoToX = this.gameObject.GetComponent<AutoMoveForBall>().GoToX;
                    small.gameObject.GetComponent<AutoMoveForBall>().GoToY = this.gameObject.GetComponent<AutoMoveForBall>().GoToY;
                    small.gameObject.GetComponent<Size>().size = this.gameObject.GetComponent<Size>().size - 1;
                }
            }
        }
    }
\$\endgroup\$

Your Answer

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

Browse other questions tagged or ask your own question.