- Home /
 
Repeat a function only when an action occurs
I used the code below to instantiate the first object in an array in one of many positions I created using a vector array.
Another script I have destroys the instantiated object when it is touched.
When the object is destroyed, I want to repeat the script below to instantiate a second object, and be able to repeat the process. How do I go about doing this?
 function Update()
 
 {
 
 var num : int = Random.Range(0,vectorArray.Length);
 Instantiate (object[0], vectorArray[num], transform.rotation);
 gameObject.active = false; // This ensures that the instantiation only occurs once
 
 }
     
 
              Answer by gregzo · Apr 09, 2012 at 09:58 PM
Don't put this in the Update function! Write your own instead:
 function InstantiateObjectAtRandomIndexOfVectorArray(obj:GameObject, arrPos : Vector3[])
 {
       Instantiate (obj, arrPos[Random.Range(0,arrPos.Length)], transform.rotation);
 }
 
               Then, whenever you want to instantiate a new object :
 InstantiateObjectAtRandomIndexOfVectorArray(mySuperObjects[whateverIndex], myAmazingPossiblePositions);
 
              Your answer
 
             Follow this Question
Related Questions
Finding the angle between two GameObjects 1 Answer
Cloned Prefab 3 Answers
Array problem? help please! 1 Answer
C# UI component overflaping another gameobject function 0 Answers
How to call and run a function from another script on a transform. 0 Answers