Instantiating At Runtime without Inspector


As an old habit, I was a little frustrated with how the “Instantiate at Runtime” was shown, given I really like to make things as dynamic as I can. Maybe this will be taught later in the course, maybe not. Truth is, I couldn’t stand having to prefab all my “enemies” to support a DeathFX field to inform the FX prefab, and then drag the FX into the inspector… that doesn’t do much different than just add the FX to the objects in the scene.

So, I read the docs and I found a Resources.Load, that completely loads a whole resource, as long as it is placed inside a “Resources” folder. So I created a Resources folder and placed my “Enemy Death FX” prefab inside it.

On my Enemy script, instead of making deathFX a SerializeField, I just made it a plain field and in the Start method I load the resource:

void Start () {
    deathFX = Resources.Load ("Enemy Death FX", typeof (GameObject)) as GameObject;
    AddNonTriggerBoxCollider ();

After that, in the OnParticleCollision method, I’ve instantiated the object the same way Ben did on the video, and it did work, at least I could hear the explosion, although the explosion particles did not appear.

I thought it could be a position problem, but even after zooming out the scene, the explosion did not show up anywhere. So I coded to play the particle system as well and everything was fine. I even added the SelfDestruct component at runtime like this… a completely dynamic generated exploding enemy…

Here is the code:

    void OnParticleCollision (GameObject other) {
        var explosion = Instantiate (deathFX, transform.position, Quaternion.identity, transform.parent.transform);
        explosion.transform.parent = transform.parent;

        var particles = explosion.GetComponent<ParticleSystem>();

        Destroy (gameObject);

Now, it would be good to know from you guys, what do you think about this… this may be prefab’ed for enemies and everything would be alright. And even if we choose to make a set of different explosions to be randomly defined at runtime, it should be just added to the prefab.

What do you guys think? Is there any downsides for this implementation that I should be worried about?


I’m not quite sure I understand the difference. Does Resource.load cache the death FX on play then instantiate from there rather than the prefab folder? This might make a difference in performance on a mobile device (but I am not exactly sure if performance would be improved or slowed down).

Privacy & Terms