GameObject to a custom class

Hi All!
I have a problem with some code conversion.

I created a pool which contains a list of GameObject (a standard Unity tutorial). I add my custom objects there. But it works with GameObject class only:

GameObject obj = (GameObject)Instantiate(PooledObject);
pooledObjects.Add(obj);

And then I use these game objects:

GameObject obj = BonusesPool.GetPooledObject();
Bonus bonus = obj.GetComponent<Bonus>();
if (bonus == null)
      return;
...
Bonuses bonusType = (Bonuses)random;
bonus.SetType(bonusType);

All the objects are not null, but the SetType method fails. Every property withing the Bonus object is null.

private void Start()
{
        boxCollider = GetComponent<BoxCollider2D>();
        rigidBody = GetComponent<Rigidbody2D>();
        spriteRenderer = GetComponent<SpriteRenderer>();
}

All the objects in the pool are Bonus objects actuall. How can I convert them and work with them properly?

Thanks!

First off, use code tags. It’s tough to tell offhand what’s code and what’s not.

The post does appear to be missing a few crucial things. First off: what is “random”? How is it declared and initialized? What are the “Bonus” and especially “Bonuses” classes?

Probably most importantly, what are you actually trying to accomplish with this?

You probably need to use typeof(ClassName) when you pass the type into SetType. However, to be honest, I have no idea what you’re trying to accomplish and have a deep suspicion that using SetType at all is entirely the wrong way to go about whatever it is.

StarManta, sorry for the code, I couldn’t find that tag first.

Everything else just doesn’t matter. Random is just a random value, it works well (see the … in the code). Bonuses is an enum, Bonus is my custom class.

I just want to work with some of my custom classes objects. I use the pool which works with GameObjects, but when I get an object from the pool, I want to operate with it depending on its type (Bonus in this case), so I call the SetType method (a random value from the enum). Nothing special.

The problem is that the object Bonus has null properties after getting it from the pool. But I’m pretty sure the Start methods works well when the objects are instantiated befor adding to the pool.

Well, what I was asking for was its declaration and initialization, which matters a great deal for that block of code.

However, that block of code may not matter. If I understand your purpose correctly, all you need is the as keyword.

GameObject obj = BonusesPool.GetPooledObject();
Bonus bonus = obj.GetComponent<Bonus>();
if (bonus == null)
      return;
BonusDeriverativeType moreSpecificBonus = bonus as BonusDerivativeType; //if 'bonus' is any other class, this will now be null
if (moreSpecificBonus != null) {
moreSpecificBonus.someValue = foo;
}

Is that what you’re trying to do here?

No, Bonus is the only class, it doesn’t have any child class. So here

Bonus bonus = obj.GetComponent<Bonus>();

I must get the only result. It’s not null, but any property (Sprite renderer, for example) is null in that object.

Again, here is the class for my prefab:

internal class Bonus : MonoBehaviour
{
    private SpriteRenderer spriteRenderer;

    public Bonuses Type { get; protected set; }

    private void Start()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
    }

    public void SetType(Bonuses newType)
    {
        Type = newType;
        spriteRenderer.sprite = GameManager.Instance.GetBonusSprite(newType);
    }
}

There is a Pool class, which adds objects like this:

private void Start()
    {
        pooledObjects = new List<GameObject>();
        for (int i = 0; i < PoolSize; i++)
        {
            GameObject obj = (GameObject)Instantiate(PooledObject);
            obj.SetActive(false);
            obj.transform.parent = gameObject.transform;
            pooledObjects.Add(obj);
        }
    }

Of couse, PooledObject is a Bonus prefab.
Then I need to work with these objects:

GameObject obj = BonusesPool.GetPooledObject();
        if (obj == null)
            return;

        Bonus bonus = obj.GetComponent<Bonus>();
        if (bonus == null)
            return;

        var random = Random.Range(1, 4);
        Bonuses bonusType = (Bonuses)random;
        bonus.SetType(bonusType);

When I call the SetType method, spriteRenderer is null.

Of course, I may refactor my pool class to work with Bonus objects, not GameObject. But in this case the Unity tutorial is useless.

Okay, so SetType is your method. I thought you were using SetType from the .NET API. Context is important!

So, your problem is most likely that the Start method of the Bonus class has not yet been called when you call SetType. If the bonus object was just spawned that frame (e.g. when GetPooledObject is called), or if it had been inactive before that point, that would explain it. You could confirm this by adding in Debug.Log statements to both the Start and the GetType methods, and seeing which order they get called in.

I would make spriteRenderer (and the other similar references) a property, like so:

private SpriteRenderer m_spriteRenderer;
public SpriteRenderer spriteRenderer {
get {
if (m_spriteRenderer == null) m_spriteRenderer = GetComponent<SpriteRenderer>();
return m_spriteRenderer;
}
}

This will make it find the SpriteRenderer immediately on-demand rather than relying on Start to do it.

I agree, this MAY solve the problem, but I don’t think it’s a good way. Unity makes us write terrible code (script oriented instead of object oriented, which is the best from the point of organization). My code works perfect when I use another kind of pool.
I saw the Start is called before the object is used and it must be called before, when the Instantiate is called.
And calling GetComponent() everytime I use an object from the pool is too expensive, I think. Thats’ why I store the spriteRenderer as a variable.

Well, I think I should create something else… Thanks for you help!

Now I see one mistake - Start is not called when Instantiate works, but Awake does. Maybe I will use this way.

…sorry, what? In what way is that “terrible”? Accessor properties are pretty great across the board.

I think you’ve misunderstood my code snippet. Read it again - it only calls GetComponent once, and then caches it.

Yes, sorry, I didn’t pay attention to your cache there.
As for the scripting - yes, it’s terrible. I said that many times on this forum and will say that again. Object oriented is better, but Unity’s way is worse. I would like to organize all the game object logic in one class and not divide it into different scripts. But that’s the matter of tastes, so don’t want to start another holy war.
Again, thanks. My problem is solved.

…you want to have all your code in one class, in one script file, and Unity is the one with the problem?

1 Like

Unity is object oriented for the most part (certain little things don’t get object identities, like the ‘Random’ class…)

1 Like

Scripts are classes (objects). Unity is OO.

OP: Interfaces are probably a better approach for what you are trying to do. Or pool the class instead of the gameobject,