Search code examples
c#unity-game-enginephysicsbulletgun

How to leave a mark on the texture of the walls when in contact with a physical object - a bullet?


Currently I am trying to have a bullet hole appear wherever the bullet from a player lands. Specifically on walls and the floor.

Below is my current script for shooting a gun.

private void Shoot()
{
    _audio.Stop();
    Ray ray = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
    RaycastHit hit;

    Vector3 targetPoint;
    if (Physics.Raycast(ray, out hit))
        targetPoint = hit.point;
    else
        targetPoint = ray.GetPoint(75);

    Vector3 dirWithoutSpread = targetPoint - spawnBullet.position;

    float x = Random.Range(-spread, spread);
    float y = Random.Range(-spread, spread);

    Vector3 dirWithSpread = dirWithoutSpread + new Vector3(x, y, 0);

    GameObject currentBullet = Instantiate(bullet, spawnBullet.position, Quaternion.identity);

    currentBullet.transform.forward = dirWithSpread.normalized;

    currentBullet.GetComponent<Rigidbody>().AddForce(dirWithSpread.normalized * shootForce, ForceMode.Impulse);
    _audio.time = 0.15f;
    _audio.Play();
}

THE CONTACT OF OBJECTS SHOULD BE READ, NOT RAY

Whats the best way of having a bullet hole appear on a wall/floor?


Solution

  • So the best solution is to use the Unity Decal system. It is similar to using texture but is an in built system that uses Unity shaders system. It would be more efficient then making a lot of gameobjects that contain a material.

    The way you use it depends on what is the main render pipeline your using. Either Universal Render Pipeline (URP) or High Definition Render Pipeline (HDRP). Links to guides can be found bellow. Make sure to use the appropiate image of bullet holes when

    Universal Render Pipeline (URP)

    Decal Rendering in URP

    High Definition Render Pipeline (HDRP)