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
Against the Tide
Tower Defense + Match 3
Status | In development |
Author | Against the Tide |
Genre | Strategy |
Tags | Fantasy, Level Editor, match3, Mouse only, realtime, Real time strategy, Singleplayer, Tower Defense |
Languages | English |
More posts
- New game page layoutJan 24, 2021
- 0.150.0 Released & DiscordJan 15, 2021
- 0.100.0 released!Jan 14, 2021
- It's awhile, but I'm still working!Jan 10, 2021
- Almost done with loadoutsJan 02, 2021
- Working on the loadout screensJan 02, 2021
- Take a screenshot in unity (with transparent background)Dec 31, 2020
- Finally! Play and upload levels online!Dec 30, 2020
- How to implement "wait at least this long" in Unity/C#Dec 28, 2020
- Level Editor is live!Dec 27, 2020
Leave a comment
Log in with itch.io to leave a comment.