- Home /
I'm using an Object Pooler for the projectiles in my game. How do I reset their movement speed when they are made active again?
I'm basing it on this - http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling
I have a pool of 20 bullets, and when they're shot, they will move in the direction the player is facing through a bool.
The problem arises when the bullets are reused, and I end up in a scenario where they maintain their movement speed. Basically, if I am facing left and fire 5 of those bullets, then fire the remaining 15 while facing right, once they recycle, they will travel in these same directions, regardless of what direction I'm facing.
Here's the script for my projectiles.
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour {
// Use this for initialization
public float speed;
bool bulletDirection;
void Start ()
{
bulletDirection = PlayerMovement.facingRight;
}
// Update is called once per frame
void Update ()
{
if (bulletDirection == false)
{
transform.Translate(-speed * Time.deltaTime, 0, 0);
}
else
{
transform.Translate(speed * Time.deltaTime, 0, 0);
}
//transform.Translate(-speed * Time.deltaTime, 0, 0);
}
}
This is the part of the Player Movement Script that handles left-right movement and the direction the player faces -
void Movement()
{
if (Input.GetKey("left"))
{
//Add force to the players rigidbody allowing it to move upwards if the above if statement is true
rigidbody2D.AddForce(Vector2.right * -speed);
//rigidbody2D.velocity = new Vector2(-speed, 0);
if (facingRight == true)
{
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
facingRight = false;
}
}
if (Input.GetKey("right"))
{
//Add force to the players rigidbody allowing it to move upwards if the above if statement is true
rigidbody2D.AddForce(Vector2.right * speed);
//rigidbody2D.velocity = new Vector2(speed, 0);
if (facingRight == false)
{
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
facingRight = true;
}
}
And here's what causes the projectiles to fire -
void Fire()
{
GameObject obj = ObjectPooler.current.GetPooledObject();
if (obj == null) return;
// Resets the Position and Rotation of the projectiles when they become active again
obj.transform.position = bulletOrigin.position;
obj.transform.rotation = bulletOrigin.rotation;
obj.SetActive(true);
}
And here's the game itself - http://howdoilookinthisshirt.com/Unity/2DGame.html
Arrow Keys to Move, Spacebar to Jump, and Left-CTRL to fire.
Answer by Kiwasi · Nov 16, 2014 at 06:25 PM
Start only gets called once in the lifetime of a GameObject. OnEnable gets called every time you activate it.
Change your Start method to OnEnable, and everything will work fine.