My rigidbody gets destroyed

I have made bullet positioned inside a barrel and denoted as rigidbody. Now it all goes fine, however all suddenly it gets off the barrel and destroys itself. How to prevent this from occurring, should I wrap it with some object that will clamp it in the tight position or what?

Make a new C# script and name it FireTest and use this code for it. Attach this code to either the main camera, or an empty gameobject at the end of the gun barrel. Make sure the z axis of this object at the end of the barrel is facing forward.

using UnityEngine;
using System.Collections;

public class FireTest : MonoBehaviour 
{
	public GameObject bullet;
	GameObject clone;
	Vector3 fwd;
	public float speed = 300.0f;
	public float lifeTime = 2.0f;
	
	void Start () 
	{
	
	}
	
	void Update () 
	{
		fwd = transform.forward;
		if(Input.GetMouseButtonDown (0))
		{
			//Instantiate a clone of the bullet prefab.
			clone = (GameObject)Instantiate(bullet, transform.position + fwd, Quaternion.identity);
			
			//Add a rigidbody component to the clone if one does not exist.
			if(!clone.rigidbody)
				clone.AddComponent<Rigidbody>();
			
			//If and when a rigidbody component is added or already exists, set parameters.
			else if(clone.rigidbody)
			{
				//Disable the bullet's use of gravity to make travel smoother.
			    clone.rigidbody.useGravity = false;
				
				//Set collision detection on fast moving objects like this bullet to be Coninuous and Dynamic.
				clone.rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
				
				//Freeze rotation of the rigidbody (bullet).
				clone.rigidbody.freezeRotation = true;
				
				
				//Add an impulse force to the bullet.
				clone.rigidbody.AddForce(fwd * speed, ForceMode.Impulse);
				
				//Check if THIS transform is a collider.
				if(collider)
					//If this is a collider, the bullet should not collide with it.
					Physics.IgnoreCollision(clone.collider, collider);
				
				//Destroy bullet clone after lifetime expires.
				Destroy (clone.gameObject, lifeTime);
			}
		}
	}
}

You want to have an empty transform as a child of the gun, and positioned at the end of the barrel. When gun fires, you want to Instantiate a new bullet prefab. If it has a ridged body and collier, then set the bullets speed after it is instantiated.

Bullets are not actually a trivial thing to properly implement. You need to be aware that the physics system is not stable at the speeds that bullets move at. The best solution is to keep track of the bullets ‘lastPosition’ in the fixed update loop, and draw a ray from the ‘lastPosition’ to the current position and see what it hits.

The (Much) easier solution is just to draw a ray from the end of your gun and see what it hits. Don’t create a bullet anything.