- Home /
Prefab instantiating at wrong position
I'm following a tutorial (https://gamedevelopment.tutsplus.com/tutorials/how-to-make-an-object-shatter-into-smaller-fragments-in-unity--gamedev-11795) but when I click the space bar, the prefab gets instantiated where I originally created it, not where I've transformed it. Only difference in my scene is that I wrote in C# not JavaScript.
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestructionCtrler : MonoBehaviour {
public GameObject remains; // this is the prefab, assigned manually in the editor
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.Space))
{
Instantiate (remains, gameObject.transform.position, gameObject.transform.rotation);
Destroy (gameObject);
}
}
}
At runtime, the prefab also instantiates as a clone (not sure if that's relevant).
Answer by NorthStar79 · Jan 18, 2018 at 05:54 AM
Hello, i did not watch tutorial but I am pretty sure that your code if fine. i guess your problem causes because your prefabs (or game object) have wrong transforms.
i suggest you to click your game object and reset its transform first.
then do this for its every child too (then you may need to re-place them by hand)
after this, you need to reset all your prefabs too.
I sıggest you to check this tutorial please pay attention to parent-child transforms.
You sir, are a genius. I have been sat here for 30 $$anonymous$$utes trying to figure out why it was instantiating on a weird transform, but it turns out the instantiated prefab had infact inherited some bizarre transform values.
I tip my hat :) :)
Answer by JVLVince · Jan 18, 2018 at 05:44 AM
As my exp, You should compare your practice and the provided source by the tutorial. You may find out where the problem is. And In my opinion, your code is no problem. I suggest you try to split the instantiate and set position process just like this:
GameObject go = Instantiate (remains) as GameObject;
go.transform.position = transform.position;
go.transform.rotation = transform.rotation;
or you can try this:
Instantiate (remains, transform.position, transform.rotation);
Maybe it's work.
Cheers!!!
Answer by Seraian · Mar 08, 2021 at 08:17 PM
What I realized was that an Animation in my Prefab was causing its position to get altered every time. Changing the animation to remove position properties fixed this issue.
Thank you! This is exactly the problem I had. For some reason when I made the animation for rotation only, it included some position values... You're my savior!