- Home /
How do you access a gameobject from a script that does not extend monodevelop
I want to access a game object called Challange Modes Button from a script that is not attached to it. I tried this to my code but it didnt work.
public class GravitronStateChallengeMode : GravitronState {
public GameObject challengeButton;
public void Awake( ){
challengeButton = GameObject.Find ("Challenge Modes Button");
}
}
I also tried this
public void Awake(){
challengeButton = GameObject.FindGameObjectWithTag ("Buttons");
}
These both gave me a null reference exception. Also not sure if this matters but this class does not extend monodevelop. It inherits from a different class.
What am I doing wrong?
Are you calling 'Awake' yourself? If this class does not extend from $$anonymous$$onoBehaviour, Awake won't be called
Answer by Taschenschieber · Jul 08, 2014 at 05:41 PM
You need to import the package UnityEngine. Add
using UnityEngine;
at the beginning of your script.
First off, it's not a package, it's a namespace. Secondly, that will only fix compile-time errors, which he's clearly not getting since he ran the code. Also, try explaining your answer, one line answer's aren't useful to anyone.
Answer by EternalClickbait · Aug 01, 2020 at 09:54 PM
You seem to have solved this yourself, but I'll answer anyway. GameObject.FindGameObjectWithTag (tag);
Will find the first GameObject in the currently loaded scenes that has a tag equal to tag
. Check the tags match, or find it another way, say by searching by name. Also, ensure Awake()
is acutally getting called. If you aren't inheriting from MonoBehaviour, Unity won't call it for you so you'll have to do it yourself
Your answer
![](https://koobas.hobune.stream/wayback/20220613153531im_/https://answers.unity.com/themes/thub/images/avi.jpg)