Place object relative to player location

Firstly I’d just like to say that this community so far has been invaluable to me!

Secondly the question, I’m trying to place an object (at the moment a cube) into the world via a keypress. I know the key press is all functional and everything, and I can place the object fine. I’m just not sure how to transform the object location to say 4 blocks infront of the player. I’ve been reading the transform.position help and to be honest I’m just not sure how to apply it.

Just to give as much info as I can, the script for this key input is on the player object which is called surprisingly “player”. At the moment the cube is placed directly on top of the player. I can see that you can create objects at certain locations but I’m just not sure how to get the player’s location, store that as a variable, then do object location = player.x + 4 in a sense.

Thanks! :slight_smile:

	private string message = "";
	 public Transform building;
 
void Update()
{
 if (Input.GetKeyDown("h")) // You must use 'Input' only at the 'Update' functions
 {
    if(variablesResources.GetWood() >= 3)
    {
      message = "YOU BUILT A HOUSE";
      variablesResources.SetWood(-3);

		Invoke("HideMessage", 3);
		var house = Instantiate(building, transform.position, transform.rotation);  
    }
    else
    {
         message = "YOU DONT HAVE ENOUGH WOOD";
						Invoke("HideMessage", 3);

    }
  }
}
	void HideMessage()
	{
		message = "";
	}

void OnGUI() // Is not static and you should not be making it so
{
    GUI.Label(new Rect(50, 50, 300, 20), message);
    
	}
}

var is valid C#, since C# 3.0 I think.

Anyway, if you always want to instantiate the object some distance in front of your current location, this would do the trick (using 4 as distance).

float distance = 4.0f;
		
Instantiate(building, transform.position + transform.forward*distance, transform.rotation);