Let's say I have a very simple 2D square prefab that has a script like this attached to it:
public class Square : MonoBehaviour
{
public GameObject GameObject { get; private set; }
public Transform Transform { get; private set; }
public SpriteRenderer SpriteRenderer { get; private set; }
private void Awake()
{
GameObject = gameObject;
Transform = transform;
SpriteRenderer = GetComponent<SpriteRenderer>();
}
}
I want to be able to arrange groups of these squares with different positions and sprite colors, saving them as prefabs to be used by a spawner (with object pooling), sort of like this:
public class SquareSpawner : MonoBehaviour
{
[SerializeField]
private Square[] squares;
private ObjectPool<Square> pool;
public void Spawn(Vector2 position)
{
foreach (var square in squares)
{
/* Get a square prefab from object pool
(this will instantiate a Square prefab into the scene
if one does not yet exist) */
Square pooledSquare = pool.Get();
/* Set up the squares we got from the pool
to match the squares given to the squares array */
pooledSquare.Transform.position = position + square.Transform.localPosition;
pooledSquare.SpriteRenderer.Color = square.SpriteRenderer.Color;
// etc.
}
}
}
Basically, I'm trying to create a spawning system that is easily visualizable using prefabs. Since object pooling is used, I don't know the configuration of the square I'll be getting back, so I always have to set the given squares' properties to match the desired configuration (this could be size, color, position, etc.).
The issue is that I can't read the properties from the Square
prefabs that are not being instantiated (the ones I'm putting into the Square[] squares
array) because the Awake()
method only gets called upon instantiation into the scene.
Perhaps there's a better way for me to set all of this up, but I'm wondering if there's a way for me to cache the properties in the Square
class so that I can read them whether the script is on a prefab and/or an instantiated Square
in the scene. It would also be nice if I could use a custom editor to test things in edit mode, which has also been hindered by my inability to cache these fields.
GameObject GameObject
use at leastGameObject gameobject
\$\endgroup\$OnValidate
rather thanAwake
, so the date is already available at edit time and does not need to wait for instantiation? Also, note thatMonoBehavíour
classes already have a reference to.gameObject
and.transform
, so there's no particular benefit to be had in making your own aliases/copies of these public properties. \$\endgroup\$OnValidate
, but I could try that. Also, I've heard countless times that cachinggameObject
andtransform
was a good idea for the minor performance improvements if one is going to be calling those properties all the time (which I will be doing). \$\endgroup\$myType.foo
vsMyType.bar
\$\endgroup\$