SetActive(true) doesn't seem to be working
I attached all the objects and stuff correctly, but nothing is created. I'm sure it has to do with the part of the code that is SetActive(true) because it makes the objects from the pool it just doesn't reactivate them through the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPooler : MonoBehaviour
{
public int pooledAmount;
public GameObject pooledObject;
public List<GameObject> pooledObjects;
void Start ()
{
pooledObjects = new List<GameObject> ();
for (int i = 0; i < pooledAmount; i++) {
GameObject obj = (GameObject)Instantiate (pooledObject);
obj.SetActive (false);
pooledObjects.Add (obj);
}
}
public GameObject GetPooledObject ()
{
for (int i = 0; i < pooledObjects.Count; i++) {
if (!pooledObjects [i].activeInHierarchy) {
return pooledObjects [i];
}
}
GameObject obj = (GameObject)Instantiate (pooledObject);
obj.SetActive (false);
pooledObjects.Add (obj);
return obj;
}
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class RowsAndMovement : MonoBehaviour { public bool isAlive; public ObjectPooler[] theObjectPools; float xPos; Vector3 rowSpot; int random; public static GameObject newRow;
void start ()
{
isAlive = true;
InvokeRepeating ("Spawner", 2.0F, 1.0F);
xPos = 0;
}
void update ()
{
}
void Spawner ()
{
random = Random.Range (0, 4);
xPos = xPos + 10F;
rowSpot = new Vector3 (xPos, 0.35F, 0);
if (isAlive == true) {
newRow = theObjectPools [random].GetPooledObject ();
newRow.transform.position = rowSpot;
newRow.transform.rotation = Quaternion.identity;
newRow.SetActive(true);
}
}
}
Answer by MeronSoda · Mar 16, 2017 at 01:25 AM
Well, I see 3 problems in your code.
Present problem:
1) After you get the element from the pool, you are not activating it. So it is still deactivated, you get a disabled object: newRow.SetActive(true);
newRow = theObjectPools [random].GetPooledObject ();
newRow.transform.position = rowSpot;
newRow.transform.rotation = Quaternion.identity;
newRow.SetActive(true);
2) I don't get why you use !pooledObjects [i].activeInHierarchy
instead of !pooledObjects [i].activeSelf
. But I am assuming you have a reason.
Future problems:
3) You don't increment (update) the value of pooledAmount when you create a new element to expand the pool (due to insuficiency) in the last lines of GetPooledObject method.
I had newRow.SetActive(true); in my code for some reason it just didn't copy over, but even so with your other revisions nothing has changed.
Your answer
Follow this Question
Related Questions
Regarding SetActive function 1 Answer
Disable Object and Enable by Distance from Player 1 Answer
My Game Over Canvas is working in one level but not the other! 0 Answers
SetActive delay between code and actual object on the screen 0 Answers
Unable to reactivate an object that's been deactivated. C# 4 Answers