Help with falling rocks

I’m making a game and a part of a game when a player reach to a place the rocks start falling , And i wrote a script to do this job , But the problem is the rocks are keep falling through the Terrain , And the number of the rocks is unlimited , How can i fix that problem ?

here is the script that i used :

pragma strict
var prefabs : Transform[];

function OnTriggerEnter() { 
  
    Instantiate (prefabs[0]); 
}

Please help me!

Add a collider to the terrain and add a collider to the rocks and also add a rigidbody to the rocks so there wont be any problems with the rocks falling.

Your question is missing a few details, but here’s my guess of what’s going on:

  • You’ve got the script above attached to some static object in the scene, with a collider (with “Is Trigger” set) that represents the area in which you’d like the rocks to appear.
  • When the player first enters the collider, the OnTriggerEnter() function is fired, which causes a rock (specifically, the first object in the prefabs[] array) to be instantiated.
  • Since you’re not specified a position parameter in your Instantiate, the rock is being created at (0,0,0). However, I suspect this location lies within the trigger area.
  • So, the newly instantiated rock causes the OnTriggerEnter() to fire again, spawning a new rock, which causes OnTriggerEnter to fire again, ad infinitum.

To solve this problem, you need to be more specific to specify that OnTriggerEnter should only spawn a rock when the player enters the trigger, not just any object. i.e.:

function OnTriggerEnter(col : Collider)
{
    if (col.gameObject.tag == "Player")
    {
        Instantiate (prefabs[0]);
    }
}

(There’s a whole extra question about whether you want to, presumeably, spawn all the objects in the prefabs array rather than just the first, but we’ll address that separately.

To stop the rocks from falling, have a script deactivate the instantiating script when the player leaves the area. An example script here:

function OnTriggerEnter(col : Collider)
{
 
    if (col.gameObject.tag == "Player")
    {
   GetComponent("SCRIPTNAMEHERE").enabled = false;
   
   
   }
}

Add a collider component to the same gameobject that your instantation script is attached to. place it at the point where, when your player runs into it, you want to stop the rocks. Make sure the collider is a trigger, and make sure the player has the tag of “Player”.
Then, just change the “SCRIPTNAMEHERE” to whatever the name of your instantation script is.

I hope this helps. This might not be the best way of doing it, but it should work.