I instantiated a GameObject using a prefab like so:
int randomIndex = Random.Range(0, spawns.Length);
// Instantiate a target
GameObject targetGameObject = Instantiate(target, spawns[randomIndex], Quaternion.identity);
targetGameObject.transform.parent = transform;
targetGameObject.GetComponent<TargetMover>().setVelocity(new Vector2(5f, 0f));
Debug.Log(targetGameObject.GetInstanceID());
nextSpawnTime = Time.time + Random.Range(minTime, maxTime);
target is public GameObject I assigned using the editor and the spawns are just vector3 array

The spawned target object has a script to move it to the right like this:
Rigidbody2D rb;
Vector2 velocity;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
velocity = Vector2.zero;
}
public void setVelocity(Vector2 newVelocity)
{
velocity = newVelocity;
Debug.Log("Setting new velocity: " + newVelocity );
}
public Vector2 getVelocity()
{
return velocity;
}
// Update is called once per frame
void FixedUpdate()
{
Debug.Log("Fixed Update: " + velocity + " --- " + this.GetInstanceID());
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
The problem is that this line gets executed and I can even check to see if I correctly set the new velocity after.
targetGameObject.GetComponent().setVelocity(new Vector2(5f, 0f));
But it is referencing some other object not the one created in the hierarchy.


The Fixed Update instanceID is the correct instantiated one, but instance returned from Instantiate doesn’t even exist in the hierarchy. Is this correct behavior?
Edit: Weird part is that setting transform parent works as expected.
targetGameObject.transform.parent = transform;
