0

I'm currently working on a game and I ran into a small issue. I'm currently trying to create an object pool for objects that will reappear constantly in my game in order to improve the framerate of my game. However when creating this object pool whenever the game starts and the pool of objects is created and then activated and then deactivated and then reactivated again the game objects always get reactivated in a static state. I've tried going through my code to find out where this problem might be coming from but I have no Idea. All the reactivated game objects have rigidbodys and the proper tags.

Ive tried going trough all the different classes which might be creating this problem but I haven't found anything out of the ordinary myself.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class SpawnPoint: MonoBehaviour
{

    public Transform SpawnPoints;
    public GameObject[] interact;
    List<float> StarPositions = new List<float>();
    int Interact;
    int index = 1;
    public int pooledAmount = 40;
    List<GameObject> colouredBalls;
    public static bool spawnAllowed;
    public static int count = 0;


    public void Start()
    {
        colouredBalls = new List<GameObject>();
        for (int c = 0; c < pooledAmount; c++)
        {
            GameObject obj = (GameObject)Instantiate(interact[0]);
            obj.SetActive(false);
            colouredBalls.Add(obj);
        }

        if (ScoreScript.scoreValue < 5)
        {

            Vector2 pos = Camera.main.WorldToViewportPoint(transform.position);


            for (int x = 1; x < 5; x++)
            {
                //Vector3 SpawnPos = spawnPoints[d].position;
                int NrSpawnpoints = 4;
                int NrSpaces = NrSpawnpoints + 1;
                double Xlegnth = 1.0;
                double spawnPosX = x * Xlegnth / NrSpaces;
                pos.x = (float)spawnPosX;
                pos.y = 1.3f;
                Vector2 Posi = Camera.main.ViewportToWorldPoint(pos);
                Instantiate(SpawnPoints, Posi, Quaternion.identity);

                //Debug.Log(Posi);
            }

        }

        spawnAllowed = true;
        InvokeRepeating("SpawnAInteract", 0f, 1f);
    }

    void SpawnAInteract()
    {

        if (spawnAllowed)
        {
            int randomSpawnPoint;
            Vector2 pos = Camera.main.WorldToViewportPoint(transform.position);
            //Vector2 starpos = Camera.main.WorldToViewportPoint(transform.position);

            if (index % 10 != 0)
            {
                for (int d = 1; d < 5; d++)
                {
                    //Vector3 SpawnPos = spawnPoints[d].position;
                    int NrSpawnpoints = 4;
                    int NrSpaces = NrSpawnpoints + 1;
                    double Xlegnth = 1.0;
                    double spawnPosX = d * Xlegnth / NrSpaces;
                    pos.x = (float)spawnPosX;
                    pos.y = 1.3f;
                    Vector2 Posi = Camera.main.ViewportToWorldPoint(pos);

                    if (!colouredBalls[d].activeInHierarchy)
                    {
                        colouredBalls[d].transform.position = Posi;
                        colouredBalls[d].transform.rotation = transform.rotation;
                        colouredBalls[d].SetActive(true);
                        //Debug.Log("Nr active Balls:" + f + colouredBalls[f].activeInHierarchy);
                        Debug.Log("Nr active Balls:" + d + colouredBalls[d].activeInHierarchy);
                        count++;
                        break;


                    }

            }

                index++;
            }
            else
            {
                for (int d = 1; d < 5; d++)
                {
                    int NrSpawnpoints = 4;
                    int NrSpaces = NrSpawnpoints + 1;
                    double Xlegnth = 1.0;
                    double spawnPosX = d * Xlegnth / NrSpaces;
                    pos.x = (float)spawnPosX;
                    pos.y = 1.3f;
                    Vector2 Posi = Camera.main.ViewportToWorldPoint(pos);

                    StarPositions.Add((float)spawnPosX);
                    //Debug.Log("Starpositions " + StarPositions.ToString());
                    //edit this
                    double StarPos = spawnPosX - Xlegnth / NrSpaces / 2;

                    //Change to a list
                    //Debug.Log("Star " + d);
                    StarPositions[d - 1] = (float)StarPos;
                }

                //edit this to make the star appear at the StarPosition directly to the left or to the right of the WhiteBall
                Vector2 Start = new Vector2(0, 0);
                Vector2 StartCon = Camera.main.ViewportToWorldPoint(Start);

                float whiteBallX = GameObject.FindWithTag("White Ball").transform.position.x;

                for (int d = 1; d < 5; d++)
                {
                    if (whiteBallX >= StartCon.x && whiteBallX <= StarPositions[d - 1])
                    {
                        int[] potentialStarPositions = { d, d + 2 };
                        int positionIndex = Random.Range(0, 2);
                        int randomSpawnPoin = potentialStarPositions[positionIndex];
                        pos.x = StarPositions[randomSpawnPoin];
                        pos.y = 1.3f;
                        Vector2 StarPosi = Camera.main.ViewportToWorldPoint(pos);
                        Interact = 1;

                        Instantiate(interact[Interact], StarPosi, Quaternion.identity);

                        break;
                    }
                }
                index++;
            }
        }
    }

}



using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectDestroy: MonoBehaviour
{
    public Transform CameraCollider;
    int NonActive = 0;

    void Start()
    {
        Vector3 ScreenSize = new Vector3(1.5f, 1.5f, 1.5f);
        Vector3 ScreenSizeAdj = Camera.main.ViewportToWorldPoint(ScreenSize);
        CameraCollider.localScale = ScreenSizeAdj;
        Vector3 ScreenPos = new Vector3(0.5f, 0.5f, 0);
        Vector3 ScreenPosAdj = Camera.main.ViewportToWorldPoint(ScreenPos);
        Instantiate(CameraCollider, ScreenPosAdj, Quaternion.identity);

    }

    private void OnTriggerExit2D(Collider2D other)
    {

        if (other.gameObject.CompareTag("ColouredBall Highress") || other.gameObject.CompareTag("Star"))
        {

            other.gameObject.SetActive(false);

        }
    }

}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InteractControl : MonoBehaviour
{

    Rigidbody2D rb;
    GameObject target;
    float moveSpeed;
    Vector3 directionToTarget;
    Renderer m_Renderer;

    void Start()
    {
        target = GameObject.Find("White Ball");
        rb = GetComponent<Rigidbody2D>();
        moveSpeed = 3f; //Movement speed of all the obstacles and powerups
        MoveInteract(); //Method responsable for the movement of the obstacles and powerups, gets called at start
    }


    void MoveInteract() //Method responsable for the movement of the obstacles and stars
    {
        if (target != null)
        {
            if(ScoreScript.scoreValue > 5) //Determine when RedBall goes from going down in a straigh line to following white ball
            { 

            directionToTarget = (target.transform.position - transform.position).normalized;
            rb.velocity = new Vector2(directionToTarget.x * moveSpeed,
                                        directionToTarget.y * moveSpeed);
            }
            else //Red Ball goes down in a straigh line
            {
                directionToTarget = new Vector3(0, -1, 0);
                rb.velocity = new Vector2(0, directionToTarget.y * moveSpeed);

            }
        }
        else
             rb.velocity = Vector3.zero;

    }
}
Maurice Bekambo
  • 325
  • 6
  • 21

1 Answers1

0

This is normal, when you deactivate an object the velocity resets. You must save their velocity before deactivating then set it again when reactivated.

I would look for other kind of optimization, this makes code more complex and probably there are better ways of optimizing it.

Edit: A quick solution would be to deactivate the sprite renderer, instead of the whole game object. This would optimize gpu load which I guess is the problem.

janavarro
  • 869
  • 5
  • 24
  • Ok so you mean instead of object pooling I would just disable the spriterenderer? when I require the object to disappear? – Maurice Bekambo May 10 '19 at 10:34
  • Yes, the object would still be working but invisible. It would still move, if you want to freeze it also you can do it with constraints, just keep in mind that if you want to unfreeze it and resume its velocity you have to save the velocity before freezing. – janavarro May 10 '19 at 10:40
  • But that wouldn't solve my problem cause my issue is that I want to either completelly remove the object when it leaves the screen (which isn't efficient if I simply destroy it due to garbage collection) or reuse it when it leaves the screen which supposidly is much more efficient to do. Since just stopping it from rendering would still mean that all these unrendered objects are getting storred in memory and overtime due to the nature of my game will fill up all of the memory – Maurice Bekambo May 10 '19 at 10:45
  • It would be easier for me if you show me a gif from your game to see you problem. Nonetheless you can clean the sprite-disabled objects when you know that they can be erased. – janavarro May 10 '19 at 10:51