- Home /
Inconsistencies in Instantiation Code
I'm using the code from Unity's Instantiate tutorial (very slightly modified) to create projectiles in my project. However, I'm noticing that it works inconsistently. Most of the time when I click "Fire1" it creates one projectile properly. But other times it will either not create any projectile or create two of them that will launch at once. Here's my code:
using UnityEngine;
using System.Collections;
public class UsingInstantiate : MonoBehaviour
{
public Rigidbody rocketPrefab;
public Transform barrelEnd;
public int shotSpeed;
void FixedUpdate()
{
if(Input.GetButtonDown("Fire1"))
{
Rigidbody rocketInstance;
rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
rocketInstance.AddForce(barrelEnd.forward * shotSpeed);
}
}
}
Here's the original tutorial for reference: http://unity3d.com/learn/tutorials/modules/beginner/scripting/instantiate?playlist=17117
Any ideas what the problem is in my version, or if something else might be the cause?
Answer by Aggrojag · Nov 29, 2015 at 04:24 AM
Change FixedUpdate to Update, and it should fix when they don't fire. I would imagine them double firing is something that's not in this code.
Edit: Fixed is called on certain intervals, update is not. In most scenarios Update runs more often. Anything that is physics related should generally go in fixed update, things that aren't sensitive to being called whenever possible (example being input), then use Update.
Right, one-time-events only lasts for one frame. Since FixedUpdate doesn't necessarily run every frame you can easily miss one-time-events. FixedUpdate should only be used for applying forces over time. Even things like a jump force or your one time launch impulse should be applied in Update ins$$anonymous$$d of FixedUpdate.
Good call on clarifying that. $$anonymous$$y wording was sloppy.
Changing it back to Update appears to have fixed both issues. I changed it because in Update, the projectiles will sometimes pass through objects at the velocity I wanted, which FixedUpdate resolved. But, it seems like that's the lesser of the two evils. Thanks!
I don't see how FixedUpdate would resolve that. The same amount of force will be applied regardless of where it's called. Unless force is applied continuously to the same object, this type of error will likely still be present. As far as the projectiles passing through, either it sounds as if they are moving too quickly, or objects that they are interacting with are too small. Best of luck.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
GameObject instantiation in C# static constructor 2 Answers
How to Instantiate a GameObject from a ScriptableObject piece of script? 0 Answers
Multiple Cars not working 1 Answer
Cloning Objects with Instantiate() - variables/references for added Components not stored? 3 Answers