So I’m making a system where you can grab an Item off the floor and use it, and guns will be derived from that script so when you use the gun item it ends up shooting.
Thing is, when I place the gun in the character’s hands in the editor and shoot, the raycasting works perfectly fine, but when the weapon is instantiated in runtime, the raycast’s origin is always at the world 0,0,0 no matter what I set the origin to, even other objects, even objects outside the parent.
I CANNOT seem to figure out how to reference the position of the bullet spawner after instantiating the weapon into the player’s hands. Which got me thinking it might be a problem with how the prefab is handling the positioning as in global position isn’t actually global, but once again, when manually attached to the character in the editor, the weapon fires fine and the raycasts spawn where intended.
I’m really lost on this one, I have solved this before but lost most my projects after getting a new PC.
Please help.
This is what happens when you shoot with a gun instantiated in runtime.
This is what happens when you shoot with a gun manually placed in the character’s hand in the editor.
private void Shoot()
{
Ray ray = new Ray(bulletSpawn.position, bulletSpawn.forward);
RaycastHit hit;
int layerMask = 1 << 9;
layerMask = ~layerMask;
Debug.Log("Shooting");
Debug.DrawRay(ray.origin, ray.direction, Color.blue, 10);
if (Physics.Raycast(ray, out hit, range, layerMask))
{
Debug.Log(hit.collider.gameObject.name);
Health targetHealth = hit.collider.GetComponentInParent<Health>();
if ( targetHealth != null )
{
targetHealth.TakeDamage(1f);
Debug.Log("hit target");
}
}
}