I'm beginner here, I'm trying to instantiate a single object every specific duration, either form the left of the screen or from the the right, at the same time I want this object to move to the other side of the screen
So the troubles I'm facing here are:
- sometimes 2 objects are being instantiated at the same time.
- the objects move in the direction that are defined in the first if statement (both objects on the left and the right move in one direction)
the part where I instantiate objects is in the script(smallFishes) that's attached to an empty gameobject is :
void Start () {
timer = gameObject.AddComponent<Timer>();
width = 2f;
timer.Duration = 3;
timer.Run();
left = Resources.Load("Left") as GameObject;
right = Resources.Load("Right") as GameObject;
}
void Update () {
if (timer.Finished)
{
lr = Random.Range(1, 3);
if (lr == 1)
{
var generetx = -8.8f - width / 2;
Instantiate(left, new Vector2(generetx, Random.Range(-4.8f,4.8f)), Quaternion.identity);
}
else
{
var generetx = +8.8f + width / 2;
Instantiate(right, new Vector2(generetx, Random.Range(-4.8f, 4.8f)), Quaternion.identity);
}
timer.Duration = 3;
timer.Run();
}
}
public int state
{
get { return lr; }
}
the part where I make the object move from the script that's attached to the object prefab:
void Start () {
small = gameObject.AddComponent<smallFishes>();
rb2d = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
var fishes = GameObject.FindGameObjectsWithTag("small");
if (fishes!=null)
{
if (small.state == 1)
{
moveright = new Vector2(4 * Time.deltaTime, 0);
rb2d.AddForce(moveright, ForceMode2D.Impulse);
}
else
{
moveleft = new Vector2(-4 * Time.deltaTime, 0);
rb2d.AddForce(moveleft, ForceMode2D.Impulse);
}
}
}
Thanks in advance.
timer
? What issmall.state
and where does it come from? \$\endgroup\$