- Home /
Objects Instantiated in a Loop Problem
Hi all. I have a parent object that when killed will spawn a number of other objects.
public void DeployChildren()
{
for (int i = 0; i < ChildCount; i++)
{
var child = (ChildObject)Instantiate(ChildPrefab, this.transform.position, Quaternion.identity);
}
}
The instantiation of these objects works fine. The issue comes when I try to move each of them a random direction in their Update methods.
public class ChildObject : MonoBehaviour
{
public void Update()
{
transform.Translate(GetRandomDirection() * Speed * Time.deltaTime);
}
}
I've been able to verify that the direction is in fact different for each ChildObject, but when they move on the screen they all move together. It appears that they will all move in the direction of the last ChildObject that gets updated.
Can someone please a)let me know how I can achieve this random movement and b)explain why I am seeing the behavior that I am?
Thanks!
can you tell me how you calculated random number? I means code in GetRandomDirection() ??
Answer by casperas14 · Dec 05, 2012 at 05:47 AM
@DeveshPandey, thanks for the reply. I'm responding in the answers section so the code will format properly.
GetRandomDirection() is a private method in the ChildObject class:
private Vector3 GetRandomDirection()
{
Rect groundRect = CoreHelper.GroundRectangle;
UnityEngine.Random.seed = DateTime.Now.Millisecond;
float x = UnityEngine.Random.Range(-groundRect.width, groundRect.width);
float z = Mathf.Sqrt(Mathf.Pow(groundRect.width, 2) - Mathf.Pow(x, 2));
return new Vector3(x, 0, -z).normalized;
}
Your answer
Follow this Question
Related Questions
Why is there a difference between script and in-game sequence of a script loop? 1 Answer
how to call something just once from an update function 5 Answers
Instantiate objects in a specific order 2 Answers
Best practice to change vertex color on a large amount of quads? 1 Answer
How to skip certain objects in List, in a for loop? GUI related. 1 Answer