A nice Unity "one-liner" for creating a game object and getting the actual component you wanted


Often times I created a game object in Unity then GetComponent the bit I actually want that does the business I'm after. So I would end up with a bunch of this mess:

GameObject someGameObject = Instantiate(prefab, location, rotation, anchor);
Bullet theThingIActuallyWant = someGameObject.GetComponent<Bullet>();
theThingIActuallyWant.Shoot(someDirection, someStrength);

Over and over and over. But the ghost of Billy Mays has you covered! How's this look instead?

// somewhere in your code
Game.Create
    .GameObjectForComponent<Bullet>(Instantiate, prefab, anchor)
    .Shoot(someDirection, someStrength);

So much better. Also, it's still three lines, haha. Sure it's no shorter, but all the boilerplate code has been moved to a nice reusable function. You'll notice I pass in the Instantiate function from the MonoBehaviour creating the Bullet. I could make my Create class (see below) its own MonoBehaviour so it wouldn't need Instantiate passed in. But then you need to make sure the Create is added to your scene, in all scenes you'd use this code. Singleton this, DoNotDestroyOnLoad that. Here, it's just cleaner.

Order now and I'll give you a second code example for free! Operators are standing by.

// Create.cs
using System;
using UnityEngine;
namespace Game {
    public static class Create {
        // if you want to supply the position and rotation
        public static T GameObjectForComponent<T>(
            Func<GameObject, Vector3, Quaternion, Transform, GameObject> instantiate,
            GameObject prefab,
            Transform anchor,
            Vector3 position,
            Quaternion rotation
        ) {
            GameObject gameObject = instantiate(prefab, position, rotation, anchor);
            T component = gameObject.GetComponent<T>();
            return component;
        }
        // I often don't, especially for UI components
        public static T GameObjectForComponent<T>(
            Func<GameObject, Vector3, Quaternion, Transform, GameObject> instantiate,
            GameObject prefab,
            Transform anchor
        ) {
            return GameObjectForComponent<T>(
                instantiate,
                prefab,
                anchor,
                Vector3.zero,
                Quaternion.identity
            );
        }
    }
}

Get Against the Tide

Download NowName your own price

Leave a comment

Log in with itch.io to leave a comment.