- Home /
Instatiation on the wrong position
So I'm just trying to instantiate an object at a fire position (which is an empty object in front of a stick) but for some reason, the projectile seems to instantiate on the firepoint's parent's position instead which is the centre of a wand. It doesn't seem to even try to place it at the position that I want as if I move the empty object (aka the firepoint) way in front of the wand it still instantiated inside of it at the parent's position. It's been a while since I've done anything with unity so it's possible this is just me being pretty stupid and forgetting something obvious with a simple solution but any help would be appreciated, thanks.
public class WeaponFireProjectile : MonoBehaviour
{
public Transform firepoint;
public GameObject projectile;
private float firepersec;
public float starttimebtwnshots;
void Start()
{
firepoint = GetComponentInChildren <Transform>();
}
void Update()
{
if (firepersec <= 0)
{
if (Input.GetButtonDown("Fire1"))
{
Instantiate(projectile, firepoint.position, transform.rotation * Quaternion.Euler(0,0,90f));
firepersec = starttimebtwnshots;
}
}
else
{
firepersec -= Time.deltaTime;
}
}
}
Image of firepoint location
Image of actual spawn position
Answer by FuryFight3r · Dec 04, 2021 at 09:31 AM
The issue with using the GetComponentInChildren method, that I've personally found in my l time using this as well as GetComponent*s*InChildren for some weird reason the parent object (the object that is calling the 'GetComponentInChidren') is always the first Component that is found and not actually a 'Child' object, this could be why the projectile is being positioned at the 'parent' position and not the 'firepoint' position, seeing as you have the firepoint as a public variable, during runtime after the Start() function has been ran on the script in question, find in the inspector the assigned transform for the firepoint, you can double click the value that is there, if it refers you to the parent object and not the firepoint object then that is most certainly your problem and the GetComponentInChildren is not actually getting the Childs Transform, but the Parents Transform as that is always the first one found..
If I were you and seeing as you already have the firepoint variable as public, just remove the line you have in the Start() method and just manually drag and drop the actual firepoint object into the inspector of the WeaponFireProjectile script.
That solved it straight away, I don't even remember why I was trying to use GetComponentInChildren anymore but I'm glad it's sorted now. Thanks for the help!