I was instantiating and destroying my gameobjects earlier but on learning that it is processor intensive, manipulated my code so that it is an object pool of 1 object. When I press Z, my object gets activated and starts scaling bigger as long as Z is pressed, and on key up, it deactivates the object, but when Z is pressed again, the object doesn't get Invoked again. What am I doing wrong ?
float speed = 2f;
public GameObject radius;
public int pooledAmount = 1;
List<GameObject> radiusorb;
void Start(){
radiusorb = new List<GameObject> ();
for (int i = 0; i < pooledAmount; i++)
{
GameObject obj = (GameObject)Instantiate (radius);
obj.SetActive(false);
radiusorb.Add (obj);
}
}
void Update (){
if(Input.GetKeyDown(KeyCode.Z))
{
Invoke("LetRadiusExist",0.001f); //Instantiating the prefab
}
if (Input.GetKey(KeyCode.Z)) { //Scale the object
if (gameObject != null)
{
gameObject.transform.localScale += gameObject.transform.localScale * (Time.deltaTime * speed);
}
}
if(Input.GetKeyUp(KeyCode.Z)) //To deactivate the prefab
{
gameObject.SetActive(false);
//Destroy(cloneRadius, 0);
}
}
void LetRadiusExist()
{
for (int i = 0; i < radiusorb.Count; i++)
{
if (!radiusorb[i].activeInHierarchy)
{
radiusorb[i].SetActive(true);
radiusorb[i].transform.parent = transform;
radiusorb[i].transform.localPosition = new Vector3(0,0,0);
break;
}
}
}
You are changing your actual game object instead of the radius object that you have pooled. So when the Z key is released, you are deactivating your game object and then no further processing is done.
Also you actually don't need a list, since you are using one object only. So this can be simplified a lot:
float speed = 2f;
public GameObject radiusPrefab;
// your "pooled" instance.
private GameObject instance;
void Start(){
instance = (GameObject)Instantiate (radiusPrefab);
instance.SetActive(false);
}
void Update (){
if(Input.GetKeyDown(KeyCode.Z))
{
instance.SetActive(true);
}
if (Input.GetKey(KeyCode.Z)) { //Scale the object
instance.transform.localScale += instance.transform.localScale * (Time.deltaTime * speed);
}
if(Input.GetKeyUp(KeyCode.Z)) //To deactivate the prefab
{
// make sure to reset the scale!
instance.transform.localScale = Vector3.one;
instance.SetActive(false);
}
}