- Home /
How do I get an object to Instantiate infront of a specific object/player?
I'm trying to get an object to spawn in front of the player when I press a UI button, but the only way that will work is if the script is attached to the player which limits me to only being able to spawn one object. I want to be able to attach the script to the corresponding button and it will spawn in front of the player. How do I get the object to Instantiate in front of the player even when it isn't attached to the player? My script:
public GameObject gameobj1;
void Start()
{
}
public void ButtonInteract()
{
{
Instantiate(gameobj1, transform.position + (transform.forward * 2), transform.rotation);
}
}
}
Answer by thirtiesareoldies · May 28, 2020 at 10:29 PM
Try this:
public GameObject player;
void Start() { player = GameObject.Find("player"); }
public void ButtonInteract() { Instantiate(gameobj1, player.transform.position + (player.transform.forward * 2), player.transform.rotation); }
That worked, but I have one problem with it. The player opens a menu to spawn an object and for some reason when it enables the menu it removes the player gameobject
I can't tell you why without more information. Is the player being destroyed? Is it being moved far away? Is it being disabled? I would run your game without fullscreen. Then, find your player in the inspector and see what its status is.
Nothing happens to the actual player, but it just removes my selection for the player when the button and menu gets enabled
Your answer
Follow this Question
Related Questions
Save GameObject to file without Playerpref 0 Answers
Save GameObject to file without Playerpref 2 Answers
How can I apply a text variable to a prefab 2 Answers
How to Make an Expanding Spawn Area for Prefabs? 2 Answers
help with instantiating gameobject at random postition from a target gameobject? 1 Answer