- Home /
Instantiated Prefab not moving along transform points
Hi guys. In my code below, i cant seem to get my Instantiated bolt(ball) to move along the transform corners. in the code it is supposed to move along all 4 corners and then move back to the first corner and on and on. If i place a bolt already in the scene it works correctly, it moves just like i want it to, but if i instantiate the bolt (as a prefab), it just stays still at the first corner(Index0.transform.position).any ideas?
[SerializeField] private Transform[] corners;
[SerializeField]
private float moveSpeed;
private int cornerIndex;
public GameObject bolt;
// Start is called before the first frame update
void Awake(){
}
void Start()
{
Instantiate(bolt,corners[cornerIndex].transform.position, Quaternion.identity);
cornerIndex = 0;
bolt.GetComponent<Rigidbody2D>();
bolt.transform.position = corners[cornerIndex].transform.position;
}
// Update is called once per frame
private void Update()
{
Move();
}
private void Move(){
Debug.Log(""+cornerIndex);
Debug.Log(""+corners.Length);
if(cornerIndex <= (corners.Length - 1)){
bolt.transform.position = Vector2.MoveTowards(bolt.transform.position,corners[cornerIndex].transform.position,
moveSpeed * Time.deltaTime);
if(bolt.transform.position == corners[cornerIndex].transform.position){
cornerIndex += 1;
}
}
if(cornerIndex == (corners.Length)){
cornerIndex = 0;
}
}
}
Answer by TechTayyab · May 06, 2020 at 09:16 AM
Instantiate returns a gameObject that is now instanciated. Use that gameObject then to do the work on it. Do:
GameObject boltInstance = Instantiate(bolt, corners[cornerIndex].transform.position,Quaternion.identity);
Then use this boltInstance to move it to corners. Hope this helps.
Yep. you nailed it, thanks for the solution, works perfectly. I was somehow lost on thinking instantiating it and using the name of the Instantiated GameObject was enough.
Your answer
![](https://koobas.hobune.stream/wayback/20220612233427im_/https://answers.unity.com/themes/thub/images/avi.jpg)