Posted December 20, 2020 by Against the Tide
#unity #C# #GameObject #GetComponent #one-liner
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 ); } } }