- Home /
Runtime prefab instantiation issue
Update: I've been trying to figure this out for a few hours today, and I've discovered that if I create a new Spawner & Branch from the prefabs and press Play the velocity calculation doesn't work, but if I save and reload Unity the new Branch's velocity calculation works just fine but the instantiated ones continue to be broken.
After debugging the crap out of this and talking to another programmer on the project, I'm fairly certain it is an under the hood problem with some kind of memory allocation glitch.
I'm going to rewrite the scripts for the throwable objects and the respawner and if that fixes the problem I'll update this again.
Original Post: So as my project stands at the moment I have tree branches that the player can detach and throw, and empty objects that "regrow" the object after it is removed.
Before the branches are pulled off the tree, they are childed to the respawner. When they're detached, they're "un-childed" and after a set amount of time the respawner instantiates a new instance of the prefab.
If I set up a respawner and childed branch in the editor I can play the game, rip it off, throw it, and the respawner will spawn a new one.
BUT the problem is that once the new branch is thrown the velocity calculation no longer works, so as soon as it is let go it just falls straight to the ground. My velocity is calculated/applied with this code...
velocity = (gameObject.transform.position - prevPos) / Time.time;
gameObject.rigidbody.velocity = velocity * velocityMagnitude; //Apply velocity
.
It looks like everything I'm trying to do is working, but I can't find the problem and I suspect it may be this line of code.
myBranch = (GameObject)Instantiate(branchToGrow);
Can I not instantiate the new instance and store a reference to it on the same line?
Answer by MibZ · Sep 28, 2012 at 06:59 PM
In case someone with a similar problem actually searches before asking a new question, in the process of rewriting my scripts (They needed to be rewritten anyway, I wanted them to be more modular) I figured out that my problem was that the settings needed for the script to work were set up in the Start function, I changed that to Awake and my problem was solved.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081556im_/https://answers.unity.com/themes/thub/images/avi.jpg)