- Home /
 
Supplying Input from Update To FixedUpdate
I want to spawn some rigidbodies and apply some initial force to them on spawning.But i want the rigidbodies to spawn in FixedUpdate and add force to them there.However I spawn them on user input and the input is taken in Update for avoiding misses as compared to FixedUpdate .So i tried and wrote the following code in C#
 void FixedUpdate()
 {
     
     while(InputCount!=0)
     {
     temp = Instantiate(bomb,childTransform.position,Quaternion.identity)as GameObject;
         
         
     temp.rigidbody.AddForce(this.transform.right*(-1)*forceAmount);
     InputCount--;
     }
 }
 void Update () 
 {
     if(Input.GetMouseButtonDown(0))
     {
         InputCount++;
     }
 }
 
               Here I had Single input so I just incremented its count,But in general case I intend to keep a hash map with keys with their count and supply it to FixedUpdate from Update as in above code.Is there any standard practice for doing this or I am doing it right?
Answer by Antony-Blackett · Dec 13, 2014 at 03:03 PM
There aren't any standard practices for this or a lot of things in Unity. Basically that's up to you to decide.
There are a tonne of different ways to achieve what you're doing. If yours works for you then I'd say it's good enough.
You could try using a coroutine. Whe you detect the input use this line of code to wait for fixed update:
 void Start()
 {
     StartCoroutine( SpawnThingsOnClick() );
 }
 
 IEnumorator SpawnThingsOnClick()
 {
     While(true)
     {
         If( Input.Get$$anonymous$$ouseButtonDown(0) )
         {
             yield return new WaitForFixedUpdate();
             // do your physics stuff here
         }
    
         yield return null; // this yields the coroutine for a single frame
     }
 }
 
                  You should read the manual on coroutine a as they can be very useful but can take a bit of time to get your head around them.
Your answer
 
             Follow this Question
Related Questions
Mouse Input for RayCast - Update or FixedUpdate 1 Answer
How do I pass an input in Update() to FixedUpdate() for Physics movement? 2 Answers
Why Do Inputs Have to Been in Update (Rather than FixedUpdate)? 3 Answers
Input and applying physics, Update or FixedUpdate? 3 Answers
Not registering input when checking input in Update and using input in FixedUpdate 1 Answer