- Home /
How to get position of instantiated object before it is destroyed
So I have a line that shoots out from the player and rotates around them when the mouse button is held down. When I let up on the mouse the line disappears. I have a gameobject attached to the end of the line furthest from my player and I would like the player to teleport/move towards it when the line is gone. However, I cannot seem to figure out how to send the coordinates of the gameobject to another script so that I can do that. Does anyone know how to do this?
Answer by tecses1 · Mar 05, 2020 at 04:26 PM
Sounds like some sort of grapple system? Interesting.
If the object is a prefab that is instantiated and you have a trigger to detect collision:
//Make a variable on your player called last hit.
public Vector3 lastHit;
//Then from the game object script:
GameObject.FindObjectOfType<YourPlayerMonoBehaviorClass>().lastHit = transform.position;
This of course has a lot of room for error, and relies on collision detection from the GameObject.
A workaround here would be to instead just have the object always a child of the player, and set its script component as a variable and grab last hit from that script, and then SetActive when you want it.
public hitGameObject;
//In your player update function:
if (Input.GetKey(KeyCode.Space)){
hitGameObject.transform.SetActive(true);
if (hitGameObject.lastHit != null){
//move player twords last hit.
}
}else{
hitGameObject.lastHit = null;
hitGameObject.transform.SetActive(false);
}
//On your hitGameobject:
public class hitGameObject{
public Vector3 lastHit;
void OnTriggerStay(other collider){
lastHit = transform.position;
}
}
Alternatively, if it is a first person game, perhaps a raycast would suit you better?
RaycastHit hit;
float distance = 50.0f;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.forward, out hit, distance))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Vector3 gameobjectPosition = hit.point;
}
Answer by Jjadter · Mar 07, 2020 at 02:53 PM
Thank you so much! Unfortunately, I was not able to make the object a child as is does a weird flip whenever the player turns, so I just made it follow the player and set it as a separate gameobject. After working around a bit I ended up using your idea of activating/deactivating the scripts when the trigger was activated and just used GetComponent to find the position of the end target. Thank you for your help!
Your answer
Follow this Question
Related Questions
GameObject change Position after game started 1 Answer
transform.position on Instaniated object does not match inspector 0 Answers
How to instantiate prefabs with offset transform.position values? 2 Answers
Bullet Not Firing in Correct Direction 0 Answers
How do I instantiate on the game object's position that i put the script on 1 Answer