I basically want to make a gameobject turn around after it reaches a certain position in space. I have a prefab, create the gameobject and make it move randomly. However, printing the position value gives me the same value (0,4,0) which is basically the spawners location. I want the location of the object while its moving through space. Here is the code:
If (Input.GetMouseButtonDown(0))
{
direction = new Vector3(Random.Range(-1.0f,1.0f), Random.Range(-1.0f,1.0f), Random.Range(-1.0f,1.0f));
GameObject sphere = Instantiate(spherePrefab, transform.position, Quaternion.identity);
sphere.GetComponent<Rigidbody>().velocity = direction * speed; // this moves the object randomly
position = sphere.transform.position;
Debug.Log(position); // This prints the spawners location every frame but no the spheres.
I have only created a spawner object in the scene and just instantiate the spheres with my script.
Any help appreciated!
CodePudding user response:
You're not updating the value you're printing in your log.
The position variable only holds the world position of the prefab at the moment it is instantiated.
Here is a basic script based on your code which gives the world position as you would expect it.
Below, spherePrefab is a 3D game object sphere on which I've only added a Rigidbody with default parameters.
Use case is as follows : Press the mouse button down, then watch the Unity console.
using UnityEngine;
public class Test : MonoBehaviour
{
[SerializeField] GameObject spherePrefab;
const float SPEED = 2f;
// Initialization
Vector3 _sphere_position = Vector3.zero;
bool _display_log = false;
GameObject _sphere_ref = null;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 direction = new(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f));
_sphere_ref = Instantiate(spherePrefab, transform.position, Quaternion.identity);
_sphere_ref.GetComponent<Rigidbody>().velocity = direction * SPEED; // this moves the object randomly
_sphere_position = _sphere_ref.transform.position;
Debug.Log(_sphere_position); // This prints the spawners location every frame but no the spheres.
_display_log = true;
}
// This case is expected to be entered after setting sphere_ref in order not to be null
if (_display_log)
{
// Update the value
_sphere_position = _sphere_ref.transform.position;
// Print it
Debug.Log(_sphere_position);
}
}
}