Noobie
Noobie

Reputation: 61

GameObject is finded as active when it's not active in the hierarchy

So I build a custom class named Obstacles

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

[System.Serializable]
public class Obstacle{

    public GameObject gameObj;
    public Color color;

    public GameObject[] particleEffects;

    public static Vector3 SpawnLocation()
    {
        int positionQuadran = Random.Range(1, 3);
        switch (positionQuadran)
        {
            //spawn above the player
            case 1:
                 return new Vector3(Random.Range(1.5f, -1.5f),
                                                      Random.Range(4f - SpawnStars.closerToPlayer, 4.5f),
                                                      Random.Range(1, -3.2f));
            //spawn benith the player
            case 2:
                return new Vector3(Random.Range(1.5f, -1.5f),
                                                      Random.Range(-0.5f, SpawnStars.closerToPlayer),
                                                      Random.Range(1f, -3.2f));
        }
        return Vector3.zero;
    }
}

Next I created a pool with 6 objects, every two objects with the same color, so there are 3 distinct colors in the obstaclePool

The problem is that I am trying to find the inactive Obstacle, it works for the first Objects that have a color, but when I ended all the colors and iterate again through the loop it says that the Obstacle.gameObj is active in the hierarchy, I don't understand, every Obstacle.gameObj is inactive (cuz I set them to be inactive in the start() so every Obstacle should have an inactive Obstacle.gameObj BUT after I activate the first Obstacle.gameObj the next ones seem to not exist, the loop "finds" only the gameObj that are active and assumes that EVERY Object in the list is now active, when actually only the first 3 are active, the remaining 3 are NOT active...And I don't understand why...Why doesn't the code find the remaining gameObj as inactive?

foreach (Obstacle star in obstaclePool)
{
    if (!star.gameObj.activeInHierarchy)
    {
        Color color = star.color;
        color.a = 0.5f;
        panel.GetComponent<Renderer>().material.color = color; 
        return star;
    }
}

Upvotes: 0

Views: 145

Answers (1)

Noobie
Noobie

Reputation: 61

Soo I eventually figure it out: So if I create a costum class like Obstacle I NEED TO MAKE SHORE that if the class has a variable like a GameObject or something that needs to be instantiated or assigned I will do that This is how I a eventually solved the problem:

        Obstacle go = new Obstacle
        {
            gameObj = Instantiate(prefab.gameObj)
        };
        poolList.Add(go);

So we literally create a new Object Obstacle and after that we make it's gameObj variable equal with Instantiate(prefab.gameObj), in this way we create every part of the Obstacle.

Upvotes: 0

Related Questions