Question by
Firedan1176 · Jan 10, 2016 at 01:16 AM ·
gameobjectobjectcast
How can I access an Object's GameObject (if it is a script)?
Essentially, this is what I have:
public Object anotherComponent;
void Start() {
GameObject go = (GameObject)anotherComponent;
}
Essentially, 'anotherComponent' will be any script that can be dragged into from the inspector. Now what I need is to be able to access the GameObject that the component/script is attached to. Is this even possible? Because the above snippet won't work (which makes sense, since I cannot cast from a script such as MyScript.cs to GameObject).
Thank you.
Comment
Best Answer
Answer by Firedan1176 · Jan 10, 2016 at 01:21 AM
I found out that I need to be using Component
instead of Object
. Component is the base class for everything attached to a GameObject, which is exactly what I needed. Now I can simply use Component.gameObject
, instead of trying to do some workaround.
Answer by leonardherndon · Jan 10, 2016 at 01:23 AM
public anotherComponent aC;
//If you're attaching the other component via the inspector this is all
//If you're going to attach the component via script you'll need to grab beforehand.
void Start() {
aC.gameObject //This will access the components gameObject.
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612055631im_/https://answers.unity.com/themes/thub/images/avi.jpg)