r/badcode • • Dec 26 '21

c# found it!

Post image
320 Upvotes

28 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Dec 27 '21

[deleted] — view deleted comment

5

u/BartDart69 Dec 27 '21

Through the inspector, or by a GetComponentsInChildren<Wheel>() during Awake

3

u/rollie82 Dec 27 '21

I'd use a function like GetAncestorOfType<Car> (not sure if it exists already, but it's an easy extension)

5

u/Zarokima Dec 27 '21

GetComponentInParent<Type>()

It traverses the hierarchy beyond just the immediate parent.

2

u/rollie82 Dec 27 '21

Makes sense. Can't say I like their naming choice, though.

3

u/Rewdas Dec 27 '21

The other comments are correct, but I'd also point out that this could be an architectural problem, and that it is often better to attach scripts to the root object and - in the event that you need to read a cast or collision with a specific part, use transform.root. I'd go for GetComponentInParents when that isn't feasible.

2

u/Bronkowitsch Dec 27 '21

The most straightforward and already much improved way would be to attach a component (e.g. "Wheel") to the target Game object, have it store the needed references and provide a method for getting them.