Search code examples
c#unity-game-engineinstantiation

How to instantiate an object to the where the camera is looking at in Unity


I have been making a first person game called "shoot the ball into the bin". The camera is in a cylinder as a player also the cylinder has collision.

I have been struggling with the main driver of the game. Like in most first person shooter games, you shoot out from the center point of the camera or the cursor.

I have trouble replicating that. The code I have so far for the shooting is:

Instantiate(prefab, new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, Camera.main.transform.position.z), Camera.main.transform.rotation);

(Credits to @derHugo for helping me instantiate a prefab)

But that just spawns it on top of the player, not in front of it. How do I make it shoot away from the player, but also in front of the player, not on top.


Solution

  • In order to spawn in front of that position simply use

    // Already reference this via the Inspector if possible
    [SerializeField] private Camera _camera;
    // Adjust how far in front of the camera the object should spawn
    [SerializeField] private float distance;
    
    private void Awake ()
    {
        // otherwise get it ONCE
        if(!_camera) _camera = Camera.main;
    }
    

    And then simply add an offset in the direction of Transform.forward of the camera like

    Instantiate(prefab, _camera.transform.position + _camera.transform.forward * distance, _camera.transform.rotation);